+
+;; State used by `comint-insert-previous-argument' when cycling.
+(defvar comint-insert-previous-argument-last-start-pos nil)
+(make-variable-buffer-local 'comint-insert-previous-argument-last-start-pos)
+(defvar comint-insert-previous-argument-last-index nil)
+(make-variable-buffer-local 'comint-insert-previous-argument-last-index)
+
+;; Needs fixing:
+;; make comint-arguments understand negative indices as bash does
+(defun comint-insert-previous-argument (index)
+ "Insert the INDEXth argument from the previous Comint command-line at point.
+Spaces are added at beginning and/or end of the inserted string if
+necessary to ensure that it's separated from adjacent arguments.
+Interactively, if no prefix argument is given, the last argument is inserted.
+Repeated interactive invocations will cycle through the same argument
+from progressively earlier commands (using the value of INDEX specified
+with the first command).
+This command is like `M-.' in bash."
+ (interactive "P")
+ (unless (null index)
+ (setq index (prefix-numeric-value index)))
+ (cond ((eq last-command this-command)
+ ;; Delete last input inserted by this command.
+ (delete-region comint-insert-previous-argument-last-start-pos (point))
+ (setq index comint-insert-previous-argument-last-index))
+ (t
+ ;; This is a non-repeat invocation, so initialize state.
+ (setq comint-input-ring-index nil)
+ (setq comint-insert-previous-argument-last-index index)
+ (when (null comint-insert-previous-argument-last-start-pos)
+ ;; First usage; initialize to a marker
+ (setq comint-insert-previous-argument-last-start-pos
+ (make-marker)))))
+ ;; Make sure we're not in the prompt, and add a beginning space if necess.
+ (if (<= (point) (comint-line-beginning-position))
+ (comint-bol)
+ (just-one-space))
+ ;; Remember the beginning of what we insert, so we can delete it if
+ ;; the command is repeated.
+ (set-marker comint-insert-previous-argument-last-start-pos (point))
+ ;; Insert the argument.
+ (let ((input-string (comint-previous-input-string 0)))
+ (when (string-match "[ \t\n]*&" input-string)
+ ;; strip terminating '&'
+ (setq input-string (substring input-string 0 (match-beginning 0))))
+ (insert (comint-arguments input-string index index)))
+ ;; Make next invocation return arg from previous input
+ (setq comint-input-ring-index (1+ (or comint-input-ring-index 0)))
+ ;; Add a terminating space if necessary.
+ (unless (eolp)
+ (just-one-space)))
+