* keyboard.c (parse_tool_bar_item): For QClabel, set TOOL_BAR_ITEM_LABEL not HELP.
[bpt/emacs.git] / lisp / minibuffer.el
index 783e219..f7dc035 100644 (file)
@@ -1,8 +1,9 @@
 ;;; minibuffer.el --- Minibuffer completion functions
 
-;; Copyright (C) 2008, 2009  Free Software Foundation, Inc.
+;; Copyright (C) 2008, 2009, 2010  Free Software Foundation, Inc.
 
 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
+;; Package: emacs
 
 ;; This file is part of GNU Emacs.
 
 
 ;;; Todo:
 
-;; - make partial-complete-mode obsolete:
+;; - extend `boundaries' to provide various other meta-data about the
+;;   output of `all-completions':
+;;   - preferred sorting order when displayed in *Completions*.
+;;   - annotations/text-properties to add when displayed in *Completions*.
+;;   - quoting/unquoting (so we can complete files names with envvars
+;;     and backslashes, and all-completion can list names without
+;;     quoting backslashes and dollars).
+;;   - indicate how to turn all-completion's output into
+;;     try-completion's output: e.g. completion-ignored-extensions.
+;;     maybe that could be merged with the "quote" operation above.
+;;   - completion hook to run when the completion is
+;;     selected/inserted (maybe this should be provided some other
+;;     way, e.g. as text-property, so `try-completion can also return it?)
+;;     both for when it's inserted via TAB or via choose-completion.
+;;   - indicate that `all-completions' doesn't do prefix-completion
+;;     but just returns some list that relates in some other way to
+;;     the provided string (as is the case in filecache.el), in which
+;;     case partial-completion (for example) doesn't make any sense
+;;     and neither does the completions-first-difference highlight.
+;;   - indicate how to display the completions in *Completions* (turn
+;;     \n into something else, add special boundaries between
+;;     completions).  E.g. when completing from the kill-ring.
+
+;; - make partial-completion-mode obsolete:
 ;;   - (?) <foo.h> style completion for file names.
 ;;     This can't be done identically just by tweaking completion,
 ;;     because partial-completion-mode's behavior is to expand <string.h>
@@ -358,21 +382,41 @@ the second failed attempt to complete."
   :type '(choice (const nil) (const t) (const lazy))
   :group 'minibuffer)
 
-(defvar completion-styles-alist
+(defconst completion-styles-alist
   '((emacs21
      completion-emacs21-try-completion completion-emacs21-all-completions
-     "Simple prefix-based completion.")
+     "Simple prefix-based completion.
+I.e. when completing \"foo_bar\" (where _ is the position of point),
+it will consider all completions candidates matching the glob
+pattern \"foobar*\".")
     (emacs22
      completion-emacs22-try-completion completion-emacs22-all-completions
-     "Prefix completion that only operates on the text before point.")
+     "Prefix completion that only operates on the text before point.
+I.e. when completing \"foo_bar\" (where _ is the position of point),
+it will consider all completions candidates matching the glob
+pattern \"foo*\" and will add back \"bar\" to the end of it.")
     (basic
      completion-basic-try-completion completion-basic-all-completions
-     "Completion of the prefix before point and the suffix after point.")
+     "Completion of the prefix before point and the suffix after point.
+I.e. when completing \"foo_bar\" (where _ is the position of point),
+it will consider all completions candidates matching the glob
+pattern \"foo*bar*\".")
     (partial-completion
      completion-pcm-try-completion completion-pcm-all-completions
      "Completion of multiple words, each one taken as a prefix.
-E.g. M-x l-c-h can complete to list-command-history
-and C-x C-f /u/m/s to /usr/monnier/src.")
+I.e. when completing \"l-co_h\" (where _ is the position of point),
+it will consider all completions candidates matching the glob
+pattern \"l*-co*h*\".
+Furthermore, for completions that are done step by step in subfields,
+the method is applied to all the preceding fields that do not yet match.
+E.g. C-x C-f /u/mo/s TAB could complete to /usr/monnier/src.
+Additionally the user can use the char \"*\" as a glob pattern.")
+    (substring
+     completion-substring-try-completion completion-substring-all-completions
+     "Completion of the string taken as a substring.
+I.e. when completing \"foo_bar\" (where _ is the position of point),
+it will consider all completions candidates matching the glob
+pattern \"*foo*bar*\".")
     (initials
      completion-initials-try-completion completion-initials-all-completions
      "Completion of acronyms and initialisms.
@@ -387,7 +431,19 @@ ALL-COMPLETIONS is the function that lists the completions (it should
 follow the calling convention of `completion-all-completions'),
 and DOC describes the way this style of completion works.")
 
-(defcustom completion-styles '(basic partial-completion emacs22)
+(defcustom completion-styles
+  ;; First, use `basic' because prefix completion has been the standard
+  ;; for "ever" and works well in most cases, so using it first
+  ;; ensures that we obey previous behavior in most cases.
+  '(basic
+    ;; Then use `partial-completion' because it has proven to
+    ;; be a very convenient extension.
+    partial-completion
+    ;; Finally use `emacs22' so as to maintain (in many/most cases)
+    ;; the previous behavior that when completing "foobar" with point
+    ;; between "foo" and "bar" the completion try to complete "foo"
+    ;; and simply add "bar" to the end of the result.
+    emacs22)
   "List of completion styles to use.
 The available styles are listed in `completion-styles-alist'."
   :type `(repeat (choice ,@(mapcar (lambda (x) (list 'const (car x)))
@@ -414,8 +470,8 @@ Only the elements of table that satisfy predicate PRED are considered.
 POINT is the position of point within STRING.
 The return value is a list of completions and may contain the base-size
 in the last `cdr'."
-  ;; FIXME: We need to additionally return completion-extra-size (similar
-  ;; to completion-base-size but for the text after point).
+  ;; FIXME: We need to additionally return the info needed for the
+  ;; second part of completion-base-position.
   (completion--some (lambda (style)
                       (funcall (nth 2 (assq style completion-styles-alist))
                                string table pred point))
@@ -426,6 +482,29 @@ in the last `cdr'."
           (if completions 2 0)
           (if exact       1 0)))
 
+(defun completion--replace (beg end newtext)
+  "Replace the buffer text between BEG and END with NEWTEXT.
+Moves point to the end of the new text."
+  ;; This should be in subr.el.
+  ;; You'd think this is trivial to do, but details matter if you want
+  ;; to keep markers "at the right place" and be robust in the face of
+  ;; after-change-functions that may themselves modify the buffer.
+  (goto-char beg)
+  (insert newtext)
+  (delete-region (point) (+ (point) (- end beg))))
+
+(defcustom completion-cycle-threshold nil
+  "Number of completion candidates below which cycling is used.
+Depending on this setting `minibuffer-complete' may use cycling,
+like `minibuffer-force-complete'.
+If nil, cycling is never used.
+If t, cycling is always used.
+If an integer, cycling is used as soon as there are fewer completion
+candidates than this number."
+  :type '(choice (const :tag "No cycling" nil)
+          (const :tag "Always cycle" t)
+          (integer :tag "Threshold")))
+
 (defun completion--do-completion (&optional try-completion-function)
   "Do the completion and return a summary of what happened.
 M = completion was performed, the text was Modified.
@@ -468,14 +547,12 @@ E = after completion we now have an Exact match.
                                                    string nil nil t))))
             (unchanged (eq t (compare-strings completion nil nil
                                               string nil nil nil))))
-        (unless unchanged
-
-          ;; Insert in minibuffer the chars we got.
+        (if unchanged
           (goto-char end)
-          (insert completion)
-          (delete-region beg end))
-       ;; Move point.
-       (goto-char (+ beg comp-pos))
+          ;; Insert in minibuffer the chars we got.
+          (completion--replace beg end completion))
+       ;; Move point to its completion-mandated destination.
+       (forward-char (- comp-pos (length completion)))
 
         (if (not (or unchanged completed))
           ;; The case of the string changed, but that's all.  We're not sure
@@ -487,14 +564,43 @@ E = after completion we now have an Exact match.
           ;; It did find a match.  Do we match some possibility exactly now?
           (let ((exact (test-completion completion
                                        minibuffer-completion-table
-                                       minibuffer-completion-predicate)))
-            (if completed
+                                       minibuffer-completion-predicate))
+                (comps
+                 ;; Check to see if we want to do cycling.  We do it
+                 ;; here, after having performed the normal completion,
+                 ;; so as to take advantage of the difference between
+                 ;; try-completion and all-completions, for things
+                 ;; like completion-ignored-extensions.
+                 (when (and completion-cycle-threshold
+                            ;; Check that the completion didn't make
+                            ;; us jump to a different boundary.
+                            (or (not completed)
+                                (< (car (completion-boundaries
+                                         (substring completion 0 comp-pos)
+                                         minibuffer-completion-table
+                                         minibuffer-completion-predicate
+                                         ""))
+                                   comp-pos)))
+                   (completion-all-sorted-completions))))
+            (setq completion-all-sorted-completions nil)
+            (cond
+             ((and (not (ignore-errors
+                          ;; This signal an (intended) error if comps is too
+                          ;; short or if completion-cycle-threshold is t.
+                          (consp (nthcdr completion-cycle-threshold comps))))
+                   ;; More than 1, so there's something to cycle.
+                   (consp (cdr comps)))
+              ;; Fewer than completion-cycle-threshold remaining
+              ;; completions: let's cycle.
+              (setq completed t exact t)
+              (setq completion-all-sorted-completions comps)
+              (minibuffer-force-complete))
+             (completed
                 ;; We could also decide to refresh the completions,
                 ;; if they're displayed (and assuming there are
                 ;; completions left).
-                (minibuffer-hide-completions)
+              (minibuffer-hide-completions))
               ;; Show the completion table, if requested.
-              (cond
                ((not exact)
                 (if (case completion-auto-help
                       (lazy (eq this-command last-command))
@@ -505,7 +611,7 @@ E = after completion we now have an Exact match.
                ;; means we've already given a "Next char not unique" message
                ;; and the user's hit TAB again, so now we give him help.
                ((eq this-command last-command)
-                (if completion-auto-help (minibuffer-completion-help)))))
+              (if completion-auto-help (minibuffer-completion-help))))
 
             (minibuffer--bitset completed t exact))))))))
 
@@ -519,21 +625,26 @@ scroll the window of possible completions."
   ;; If the previous command was not this,
   ;; mark the completion buffer obsolete.
   (unless (eq this-command last-command)
+    (setq completion-all-sorted-completions nil)
     (setq minibuffer-scroll-window nil))
 
-  (let ((window minibuffer-scroll-window))
+  (cond
     ;; If there's a fresh completion window with a live buffer,
     ;; and this command is repeated, scroll that window.
-    (if (window-live-p window)
+   ((window-live-p minibuffer-scroll-window)
+    (let ((window minibuffer-scroll-window))
         (with-current-buffer (window-buffer window)
           (if (pos-visible-in-window-p (point-max) window)
              ;; If end is in view, scroll up to the beginning.
              (set-window-start window (point-min) nil)
            ;; Else scroll down one screen.
            (scroll-other-window))
-         nil)
-
-      (case (completion--do-completion)
+        nil)))
+   ;; If we're cycling, keep on cycling.
+   (completion-all-sorted-completions
+    (minibuffer-force-complete)
+    t)
+   (t (case (completion--do-completion)
         (#b000 nil)
         (#b001 (minibuffer-message "Sole completion")
                t)
@@ -626,6 +737,12 @@ If `minibuffer-completion-confirm' is `confirm-after-completion',
      ((test-completion (buffer-substring beg end)
                        minibuffer-completion-table
                        minibuffer-completion-predicate)
+      ;; FIXME: completion-ignore-case has various slightly
+      ;; incompatible meanings.  E.g. it can reflect whether the user
+      ;; wants completion to pay attention to case, or whether the
+      ;; string will be used in a context where case is significant.
+      ;; E.g. usually try-completion should obey the first, whereas
+      ;; test-completion should obey the second.
       (when completion-ignore-case
         ;; Fixup case of the field, if necessary.
         (let* ((string (buffer-substring beg end))
@@ -633,7 +750,7 @@ If `minibuffer-completion-confirm' is `confirm-after-completion',
                        string
                        minibuffer-completion-table
                        minibuffer-completion-predicate)))
-          (when (and (stringp compl)
+          (when (and (stringp compl) (not (equal string compl))
                      ;; If it weren't for this piece of paranoia, I'd replace
                      ;; the whole thing with a call to do-completion.
                      ;; This is important, e.g. when the current minibuffer's
@@ -646,22 +763,19 @@ If `minibuffer-completion-confirm' is `confirm-after-completion',
             (delete-region beg end))))
       (exit-minibuffer))
 
-     ((eq minibuffer-completion-confirm 'confirm)
+     ((memq minibuffer-completion-confirm '(confirm confirm-after-completion))
       ;; The user is permitted to exit with an input that's rejected
       ;; by test-completion, after confirming her choice.
-      (if (eq last-command this-command)
+      (if (or (eq last-command this-command)
+              ;; For `confirm-after-completion' we only ask for confirmation
+              ;; if trying to exit immediately after typing TAB (this
+              ;; catches most minibuffer typos).
+              (and (eq minibuffer-completion-confirm 'confirm-after-completion)
+                   (not (memq last-command minibuffer-confirm-exit-commands))))
           (exit-minibuffer)
         (minibuffer-message "Confirm")
         nil))
 
-     ((eq minibuffer-completion-confirm 'confirm-after-completion)
-      ;; Similar to the above, but only if trying to exit immediately
-      ;; after typing TAB (this catches most minibuffer typos).
-      (if (memq last-command minibuffer-confirm-exit-commands)
-         (progn (minibuffer-message "Confirm")
-                nil)
-       (exit-minibuffer)))
-
      (t
       ;; Call do-completion, but ignore errors.
       (case (condition-case nil
@@ -778,6 +892,16 @@ Return nil if there is no valid completion, else t."
 (defface completions-annotations '((t :inherit italic))
   "Face to use for annotations in the *Completions* buffer.")
 
+(defcustom completions-format 'horizontal
+  "Define the appearance and sorting of completions.
+If the value is `vertical', display completions sorted vertically
+in columns in the *Completions* buffer.
+If the value is `horizontal', display completions sorted
+horizontally in alphabetical order, rather than down the screen."
+  :type '(choice (const horizontal) (const vertical))
+  :group 'minibuffer
+  :version "23.2")
+
 (defun completion--insert-strings (strings)
   "Insert a list of STRINGS into the current buffer.
 Uses columns to keep the listing readable but compact.
@@ -800,6 +924,8 @@ It also eliminates runs of equal strings."
                     (max 1 (/ (length strings) 2))))
           (colwidth (/ wwidth columns))
            (column 0)
+          (rows (/ (length strings) columns))
+          (row 0)
           (laststring nil))
       ;; The insertion should be "sensible" no matter what choices were made
       ;; for the parameters above.
@@ -810,20 +936,38 @@ It also eliminates runs of equal strings."
                             (+ (string-width (car str))
                                (string-width (cadr str)))
                           (string-width str))))
-            (unless (bolp)
-              (if (< wwidth (+ (max colwidth length) column))
-                  ;; No space for `str' at point, move to next line.
-                  (progn (insert "\n") (setq column 0))
-                (insert " \t")
-                ;; Leave the space unpropertized so that in the case we're
-                ;; already past the goal column, there is still
-                ;; a space displayed.
-                (set-text-properties (- (point) 1) (point)
-                                     ;; We can't just set tab-width, because
-                                     ;; completion-setup-function will kill all
-                                     ;; local variables :-(
-                                     `(display (space :align-to ,column)))
-                nil))
+            (cond
+            ((eq completions-format 'vertical)
+             ;; Vertical format
+             (when (> row rows)
+               (forward-line (- -1 rows))
+               (setq row 0 column (+ column colwidth)))
+             (when (> column 0)
+               (end-of-line)
+               (while (> (current-column) column)
+                 (if (eobp)
+                     (insert "\n")
+                   (forward-line 1)
+                   (end-of-line)))
+               (insert " \t")
+               (set-text-properties (- (point) 1) (point)
+                                    `(display (space :align-to ,column)))))
+            (t
+             ;; Horizontal format
+             (unless (bolp)
+               (if (< wwidth (+ (max colwidth length) column))
+                   ;; No space for `str' at point, move to next line.
+                   (progn (insert "\n") (setq column 0))
+                 (insert " \t")
+                 ;; Leave the space unpropertized so that in the case we're
+                 ;; already past the goal column, there is still
+                 ;; a space displayed.
+                 (set-text-properties (- (point) 1) (point)
+                                      ;; We can't just set tab-width, because
+                                      ;; completion-setup-function will kill all
+                                      ;; local variables :-(
+                                      `(display (space :align-to ,column)))
+                 nil))))
             (if (not (consp str))
                 (put-text-property (point) (progn (insert str) (point))
                                    'mouse-face 'highlight)
@@ -831,11 +975,20 @@ It also eliminates runs of equal strings."
                                  'mouse-face 'highlight)
               (add-text-properties (point) (progn (insert (cadr str)) (point))
                                    '(mouse-face nil
-                                     face completions-annotations)))
-            ;; Next column to align to.
-            (setq column (+ column
-                            ;; Round up to a whole number of columns.
-                            (* colwidth (ceiling length colwidth))))))))))
+                                               face completions-annotations)))
+           (cond
+            ((eq completions-format 'vertical)
+             ;; Vertical format
+             (if (> column 0)
+                 (forward-line)
+               (insert "\n"))
+             (setq row (1+ row)))
+            (t
+             ;; Horizontal format
+             ;; Next column to align to.
+             (setq column (+ column
+                             ;; Round up to a whole number of columns.
+                             (* colwidth (ceiling length colwidth))))))))))))
 
 (defvar completion-common-substring nil)
 (make-obsolete-variable 'completion-common-substring nil "23.1")
@@ -954,7 +1107,8 @@ variables.")
   "Display a list of possible completions of the current minibuffer contents."
   (interactive)
   (message "Making completion list...")
-  (let* ((start (field-beginning))
+  (let* ((non-essential t)
+        (start (field-beginning))
          (string (field-string))
          (completions (completion-all-completions
                        string
@@ -965,9 +1119,14 @@ variables.")
     (if (and completions
              (or (consp (cdr completions))
                  (not (equal (car completions) string))))
-        (with-output-to-temp-buffer "*Completions*"
-          (let* ((last (last completions))
-                 (base-size (cdr last)))
+        (let* ((last (last completions))
+               (base-size (cdr last))
+               ;; If the *Completions* buffer is shown in a new
+               ;; window, mark it as softly-dedicated, so bury-buffer in
+               ;; minibuffer-hide-completions will know whether to
+               ;; delete the window or not.
+               (display-buffer-mark-dedicated 'soft))
+          (with-output-to-temp-buffer "*Completions*"
             ;; Remove the base-size tail because `sort' requires a properly
             ;; nil-terminated list.
             (when last (setcdr last nil))
@@ -980,21 +1139,16 @@ variables.")
                                 (if ann (list s ann) s)))
                             completions)))
             (with-current-buffer standard-output
-             (set (make-local-variable 'completion-base-position)
-                  ;; FIXME: We should provide the END part as well, but
-                  ;; currently completion-all-completions does not give
-                  ;; us the necessary information.
-                  (list (+ start base-size) nil)))
+              (set (make-local-variable 'completion-base-position)
+                   ;; FIXME: We should provide the END part as well, but
+                   ;; currently completion-all-completions does not give
+                   ;; us the necessary information.
+                   (list (+ start base-size) nil)))
             (display-completion-list completions)))
 
       ;; If there are no completions, or if the current input is already the
       ;; only possible completion, then hide (previous&stale) completions.
-      (let ((window (and (get-buffer "*Completions*")
-                         (get-buffer-window "*Completions*" 0))))
-        (when (and (window-live-p window) (window-dedicated-p window))
-          (condition-case ()
-              (delete-window window)
-            (error (iconify-frame (window-frame window))))))
+      (minibuffer-hide-completions)
       (ding)
       (minibuffer-message
        (if completions "Sole completion" "No completions")))
@@ -1027,6 +1181,70 @@ variables.")
     (ding))
   (exit-minibuffer))
 
+(defvar completion-in-region-functions nil
+  "Wrapper hook around `completion-in-region'.
+The functions on this special hook are called with 5 arguments:
+  NEXT-FUN START END COLLECTION PREDICATE.
+NEXT-FUN is a function of four arguments (START END COLLECTION PREDICATE)
+that performs the default operation.  The other four arguments are like
+the ones passed to `completion-in-region'.  The functions on this hook
+are expected to perform completion on START..END using COLLECTION
+and PREDICATE, either by calling NEXT-FUN or by doing it themselves.")
+
+(defun completion-in-region (start end collection &optional predicate)
+  "Complete the text between START and END using COLLECTION.
+Return nil if there is no valid completion, else t.
+Point needs to be somewhere between START and END."
+  (assert (<= start (point)) (<= (point) end))
+  ;; FIXME: undisplay the *Completions* buffer once the completion is done.
+  (with-wrapper-hook
+      completion-in-region-functions (start end collection predicate)
+    (let ((minibuffer-completion-table collection)
+          (minibuffer-completion-predicate predicate)
+          (ol (make-overlay start end nil nil t)))
+      (overlay-put ol 'field 'completion)
+      (unwind-protect
+          (call-interactively 'minibuffer-complete)
+        (delete-overlay ol)))))
+
+(defvar completion-at-point-functions '(tags-completion-at-point-function)
+  "Special hook to find the completion table for the thing at point.
+It is called without any argument and should return either nil,
+or a function of no argument to perform completion (discouraged),
+or a list of the form (START END COLLECTION &rest PROPS) where
+ START and END delimit the entity to complete and should include point,
+ COLLECTION is the completion table to use to complete it, and
+ PROPS is a property list for additional information.
+Currently supported properties are:
+ `:predicate'           a predicate that completion candidates need to satisfy.
+ `:annotation-function' the value to use for `completion-annotate-function'.")
+
+(defun completion-at-point (&optional arg)
+  "Perform completion on the text around point.
+The completion method is determined by `completion-at-point-functions'.
+
+With a prefix argument, this command does completion within
+the collection of symbols listed in the index of the manual for the
+language you are using."
+  (interactive "P")
+  (if arg
+      (info-complete-symbol)
+    (let ((res (run-hook-with-args-until-success
+               'completion-at-point-functions)))
+      (cond
+       ((functionp res) (funcall res))
+       (res
+       (let* ((plist (nthcdr 3 res))
+              (start (nth 0 res))
+              (end (nth 1 res))
+              (completion-annotate-function
+               (or (plist-get plist :annotation-function)
+                   completion-annotate-function)))
+         (completion-in-region start end (nth 2 res)
+                               (plist-get plist :predicate))))))))
+
+(define-obsolete-function-alias 'complete-symbol 'completion-at-point "24.1")
+
 ;;; Key bindings.
 
 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
@@ -1125,12 +1343,19 @@ same as `substitute-in-file-name'."
    ((eq (car-safe action) 'boundaries)
     (let ((start (length (file-name-directory string)))
           (end (string-match-p "/" (cdr action))))
-      (list* 'boundaries start end)))
-
-     ((eq action 'lambda)
-      (if (zerop (length string))
-          nil    ;Not sure why it's here, but it probably doesn't harm.
-        (funcall (or pred 'file-exists-p) string)))
+      (list* 'boundaries
+             ;; if `string' is "C:" in w32, (file-name-directory string)
+             ;; returns "C:/", so `start' is 3 rather than 2.
+             ;; Not quite sure what is The Right Fix, but clipping it
+             ;; back to 2 will work for this particular case.  We'll
+             ;; see if we can come up with a better fix when we bump
+             ;; into more such problematic cases.
+             (min start (length string)) end)))
+
+   ((eq action 'lambda)
+    (if (zerop (length string))
+        nil    ;Not sure why it's here, but it probably doesn't harm.
+      (funcall (or pred 'file-exists-p) string)))
 
    (t
       (let* ((name (file-name-nondirectory string))
@@ -1178,17 +1403,20 @@ except that it passes the file name through `substitute-in-file-name'."
   (cond
    ((eq (car-safe action) 'boundaries)
     ;; For the boundaries, we can't really delegate to
-    ;; completion-file-name-table and then fix them up, because it
-    ;; would require us to track the relationship between `str' and
+    ;; substitute-in-file-name+completion-file-name-table and then fix
+    ;; them up (as we do for the other actions), because it would
+    ;; require us to track the relationship between `str' and
     ;; `string', which is difficult.  And in any case, if
-    ;; substitute-in-file-name turns "fo-$TO-ba" into "fo-o/b-ba", there's
-    ;; no way for us to return proper boundaries info, because the
-    ;; boundary is not (yet) in `string'.
-    (let ((start (length (file-name-directory string)))
-          (end (string-match-p "/" (cdr action))))
-      (list* 'boundaries start end)))
+    ;; substitute-in-file-name turns "fo-$TO-ba" into "fo-o/b-ba",
+    ;; there's no way for us to return proper boundaries info, because
+    ;; the boundary is not (yet) in `string'.
+    ;;
+    ;; FIXME: Actually there is a way to return correct boundaries
+    ;; info, at the condition of modifying the all-completions
+    ;; return accordingly. But for now, let's not bother.
+    (completion-file-name-table string pred action))
 
-       (t
+   (t
     (let* ((default-directory
              (if (stringp pred)
                  ;; It used to be that `pred' was abused to pass `dir'
@@ -1200,7 +1428,9 @@ except that it passes the file name through `substitute-in-file-name'."
                     (substitute-in-file-name string)
                   (error string)))
            (comp (completion-file-name-table
-                  str (or pred read-file-name-predicate) action)))
+                  str
+                 (with-no-warnings (or pred read-file-name-predicate))
+                 action)))
 
       (cond
        ((stringp comp)
@@ -1259,13 +1489,40 @@ such as making the current buffer visit no file in the case of
 (declare-function x-file-dialog "xfns.c"
                   (prompt dir &optional default-filename mustmatch only-dir-p))
 
+(defun read-file-name-defaults (&optional dir initial)
+  (let ((default
+         (cond
+          ;; With non-nil `initial', use `dir' as the first default.
+          ;; Essentially, this mean reversing the normal order of the
+          ;; current directory name and the current file name, i.e.
+          ;; 1. with normal file reading:
+          ;; 1.1. initial input is the current directory
+          ;; 1.2. the first default is the current file name
+          ;; 2. with non-nil `initial' (e.g. for `find-alternate-file'):
+          ;; 2.2. initial input is the current file name
+          ;; 2.1. the first default is the current directory
+          (initial (abbreviate-file-name dir))
+          ;; In file buffers, try to get the current file name
+          (buffer-file-name
+           (abbreviate-file-name buffer-file-name))))
+       (file-name-at-point
+        (run-hook-with-args-until-success 'file-name-at-point-functions)))
+    (when file-name-at-point
+      (setq default (delete-dups
+                    (delete "" (delq nil (list file-name-at-point default))))))
+    ;; Append new defaults to the end of existing `minibuffer-default'.
+    (append
+     (if (listp minibuffer-default) minibuffer-default (list minibuffer-default))
+     (if (listp default) default (list default)))))
+
 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
   "Read file name, prompting with PROMPT and completing in directory DIR.
 Value is not expanded---you must call `expand-file-name' yourself.
 Default name to DEFAULT-FILENAME if user exits the minibuffer with
 the same non-empty string that was inserted by this function.
  (If DEFAULT-FILENAME is omitted, the visited file name is used,
-  except that if INITIAL is specified, that combined with DIR is used.)
+  except that if INITIAL is specified, that combined with DIR is used.
+  If DEFAULT-FILENAME is a list of file names, the first file name is used.)
 If the user exits with an empty minibuffer, this function returns
 an empty string.  (This can only happen if the user erased the
 pre-inserted contents or if `insert-default-directory' is nil.)
@@ -1292,9 +1549,10 @@ DIR should be an absolute directory name.  It defaults to the value of
 
 If this command was invoked with the mouse, use a graphical file
 dialog if `use-dialog-box' is non-nil, and the window system or X
-toolkit in use provides a file dialog box.  For graphical file
-dialogs, any the special values of MUSTMATCH; `confirm' and
-`confirm-after-completion' are treated as equivalent to nil.
+toolkit in use provides a file dialog box, and DIR is not a
+remote file.  For graphical file dialogs, any the special values
+of MUSTMATCH; `confirm' and `confirm-after-completion' are
+treated as equivalent to nil.
 
 See also `read-file-name-completion-ignore-case'
 and `read-file-name-function'."
@@ -1307,7 +1565,10 @@ and `read-file-name-function'."
   (setq dir (abbreviate-file-name dir))
   ;; Likewise for default-filename.
   (if default-filename
-      (setq default-filename (abbreviate-file-name default-filename)))
+      (setq default-filename
+           (if (consp default-filename)
+               (mapcar 'abbreviate-file-name default-filename)
+             (abbreviate-file-name default-filename))))
   (let ((insdef (cond
                  ((and insert-default-directory (stringp dir))
                   (if initial
@@ -1325,7 +1586,10 @@ and `read-file-name-function'."
             (add-to-history nil))
 
         (let* ((val
-                (if (not (next-read-file-uses-dialog-p))
+                (if (or (not (next-read-file-uses-dialog-p))
+                       ;; Graphical file dialogs can't handle remote
+                       ;; files (Bug#99).
+                       (file-remote-p dir))
                     ;; We used to pass `dir' to `read-file-name-internal' by
                     ;; abusing the `predicate' argument.  It's better to
                     ;; just use `default-directory', but in order to avoid
@@ -1334,7 +1598,24 @@ and `read-file-name-function'."
                     (lexical-let ((dir (file-name-as-directory
                                         (expand-file-name dir))))
                       (minibuffer-with-setup-hook
-                          (lambda () (setq default-directory dir))
+                          (lambda ()
+                           (setq default-directory dir)
+                           ;; When the first default in `minibuffer-default'
+                           ;; duplicates initial input `insdef',
+                           ;; reset `minibuffer-default' to nil.
+                           (when (equal (or (car-safe insdef) insdef)
+                                        (or (car-safe minibuffer-default)
+                                            minibuffer-default))
+                             (setq minibuffer-default
+                                   (cdr-safe minibuffer-default)))
+                           ;; On the first request on `M-n' fill
+                           ;; `minibuffer-default' with a list of defaults
+                           ;; relevant for file-name reading.
+                           (set (make-local-variable 'minibuffer-default-add-function)
+                                (lambda ()
+                                  (with-current-buffer
+                                      (window-buffer (minibuffer-selected-window))
+                                    (read-file-name-defaults dir initial)))))
                         (completing-read prompt 'read-file-name-internal
                                          pred mustmatch insdef
                                          'file-name-history default-filename)))
@@ -1353,9 +1634,12 @@ and `read-file-name-function'."
                               (not (zerop (length file))))
                       (setq default-filename file)
                       (setq dir (file-name-directory dir)))
-                    (if default-filename
-                        (setq default-filename
-                              (expand-file-name default-filename dir)))
+                    (when default-filename
+                     (setq default-filename
+                           (expand-file-name (if (consp default-filename)
+                                                 (car default-filename)
+                                               default-filename)
+                                             dir)))
                     (setq add-to-history t)
                     (x-file-dialog prompt dir default-filename
                                   dialog-mustmatch
@@ -1367,6 +1651,8 @@ and `read-file-name-function'."
           ;; it has to mean that the user typed RET with the minibuffer empty.
           ;; In that case, we really want to return ""
           ;; so that commands such as set-visited-file-name can distinguish.
+         (when (consp default-filename)
+           (setq default-filename (car default-filename)))
           (when (eq val default-filename)
             ;; In this case, completing-read has not added an element
             ;; to the history.  Maybe we should.
@@ -1474,6 +1760,12 @@ Return the new suffix."
     ;; Nothing to merge.
     suffix))
 
+(defun completion-basic--pattern (beforepoint afterpoint bounds)
+  (delete
+   "" (list (substring beforepoint (car bounds))
+            'point
+            (substring afterpoint 0 (cdr bounds)))))
+
 (defun completion-basic-try-completion (string table pred point)
   (let* ((beforepoint (substring string 0 point))
          (afterpoint (substring string point))
@@ -1490,10 +1782,8 @@ Return the new suffix."
              (length completion))))
       (let* ((suffix (substring afterpoint (cdr bounds)))
              (prefix (substring beforepoint 0 (car bounds)))
-             (pattern (delete
-                       "" (list (substring beforepoint (car bounds))
-                                'point
-                                (substring afterpoint 0 (cdr bounds)))))
+             (pattern (completion-basic--pattern
+                       beforepoint afterpoint bounds))
              (all (completion-pcm--all-completions prefix pattern table pred)))
         (if minibuffer-completing-file-name
             (setq all (completion-pcm--filename-try-filter all)))
@@ -1503,12 +1793,8 @@ Return the new suffix."
   (let* ((beforepoint (substring string 0 point))
          (afterpoint (substring string point))
          (bounds (completion-boundaries beforepoint table pred afterpoint))
-         (suffix (substring afterpoint (cdr bounds)))
          (prefix (substring beforepoint 0 (car bounds)))
-         (pattern (delete
-                   "" (list (substring beforepoint (car bounds))
-                            'point
-                            (substring afterpoint 0 (cdr bounds)))))
+         (pattern (completion-basic--pattern beforepoint afterpoint bounds))
          (all (completion-pcm--all-completions prefix pattern table pred)))
     (completion-hilit-commonality all point (car bounds))))
 
@@ -1525,7 +1811,7 @@ from lowercase to uppercase characters).")
 (defun completion-pcm--prepare-delim-re (delims)
   (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
 
-(defcustom completion-pcm-word-delimiters "-_. "
+(defcustom completion-pcm-word-delimiters "-_./: "
   "A string of characters treated as word delimiters for completion.
 Some arcane rules:
 If `]' is in this string, it must come first.
@@ -1541,6 +1827,14 @@ expression (not containing character ranges like `a-z')."
   :group 'minibuffer
   :type 'string)
 
+(defcustom completion-pcm-complete-word-inserts-delimiters nil
+  "Treat the SPC or - inserted by `minibuffer-complete-word' as delimiters.
+Those chars are treated as delimiters iff this variable is non-nil.
+I.e. if non-nil, M-x SPC will just insert a \"-\" in the minibuffer, whereas
+if nil, it will list all possible commands in *Completions* because none of
+the commands start with a \"-\" or a SPC."
+  :type 'boolean)
+
 (defun completion-pcm--pattern-trivial-p (pattern)
   (and (stringp (car pattern))
        ;; It can be followed by `point' and "" and still be trivial.
@@ -1553,7 +1847,7 @@ expression (not containing character ranges like `a-z')."
 (defun completion-pcm--string->pattern (string &optional point)
   "Split STRING into a pattern.
 A pattern is a list where each element is either a string
-or a symbol chosen among `any', `star', `point'."
+or a symbol chosen among `any', `star', `point', `prefix'."
   (if (and point (< point (length string)))
       (let ((prefix (substring string 0 point))
             (suffix (substring string point)))
@@ -1566,11 +1860,12 @@ or a symbol chosen among `any', `star', `point'."
 
       (while (and (setq p (string-match completion-pcm--delim-wild-regex
                                         string p))
-                  ;; If the char was added by minibuffer-complete-word, then
-                  ;; don't treat it as a delimiter, otherwise "M-x SPC"
-                  ;; ends up inserting a "-" rather than listing
-                  ;; all completions.
-                  (not (get-text-property p 'completion-try-word string)))
+                  (or completion-pcm-complete-word-inserts-delimiters
+                      ;; If the char was added by minibuffer-complete-word,
+                      ;; then don't treat it as a delimiter, otherwise
+                      ;; "M-x SPC" ends up inserting a "-" rather than listing
+                      ;; all completions.
+                      (not (get-text-property p 'completion-try-word string))))
         ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
         ;; meaning that something can be added *before* it, but it can also
         ;; match a prefix and postfix, in which case something can be added
@@ -1596,11 +1891,10 @@ or a symbol chosen among `any', `star', `point'."
          (concat "\\`"
                  (mapconcat
                   (lambda (x)
-                    (case x
-                      ((star any point)
-                       (if (if (consp group) (memq x group) group)
-                           "\\(.*?\\)" ".*?"))
-                      (t (regexp-quote x))))
+                    (cond
+                     ((stringp x) (regexp-quote x))
+                     ((if (consp group) (memq x group) group) "\\(.*?\\)")
+                    (t ".*?")))
                   pattern
                   ""))))
     ;; Avoid pathological backtracking.
@@ -1640,7 +1934,6 @@ PATTERN is as returned by `completion-pcm--string->pattern'."
   (when completions
     (let* ((re (completion-pcm--pattern->regex pattern '(point)))
            (case-fold-search completion-ignore-case))
-      ;; Remove base-size during mapcar, and add it back later.
       (mapcar
        (lambda (str)
         ;; Don't modify the string itself.
@@ -1756,6 +2049,17 @@ filter out additional entries (because TABLE migth not obey PRED)."
       (nconc (completion-pcm--hilit-commonality pattern all)
              (length prefix)))))
 
+(defun completion--sreverse (str)
+  "Like `reverse' but for a string STR rather than a list."
+  (apply 'string (nreverse (mapcar 'identity str))))
+
+(defun completion--common-suffix (strs)
+  "Return the common suffix of the strings STRS."
+  (completion--sreverse
+   (try-completion
+    ""
+    (mapcar 'completion--sreverse strs))))
+
 (defun completion-pcm--merge-completions (strs pattern)
   "Extract the commonality in STRS, with the help of PATTERN."
   ;; When completing while ignoring case, we want to try and avoid
@@ -1817,7 +2121,17 @@ filter out additional entries (because TABLE migth not obey PRED)."
                 ;; `any' into a `star' because the surrounding context has
                 ;; changed such that string->pattern wouldn't add an `any'
                 ;; here any more.
-                (unless unique (push elem res))
+                (unless unique
+                  (push elem res)
+                  (when (memq elem '(star point prefix))
+                    ;; Extract common suffix additionally to common prefix.
+                    ;; Only do it for `point', `star', and `prefix' since for
+                    ;; `any' it could lead to a merged completion that
+                    ;; doesn't itself match the candidates.
+                    (let ((suffix (completion--common-suffix comps)))
+                      (assert (stringp suffix))
+                      (unless (equal suffix "")
+                        (push suffix res)))))
                 (setq fixed "")))))
         ;; We return it in reverse order.
         res)))))
@@ -1826,8 +2140,7 @@ filter out additional entries (because TABLE migth not obey PRED)."
   (mapconcat (lambda (x) (cond
                      ((stringp x) x)
                      ((eq x 'star) "*")
-                     ((eq x 'any) "")
-                     ((eq x 'point) "")))
+                     (t "")))           ;any, point, prefix.
              pattern
              ""))
 
@@ -1866,7 +2179,10 @@ filter out additional entries (because TABLE migth not obey PRED)."
             ;; order of preference) either at the old point, or at
             ;; the last place where there's something to choose, or
             ;; at the very end.
-             (pointpat (or (memq 'point mergedpat) (memq 'any mergedpat)
+             (pointpat (or (memq 'point mergedpat)
+                           (memq 'any   mergedpat)
+                           (memq 'star  mergedpat)
+                           ;; Not `prefix'.
                           mergedpat))
              ;; New pos from the start.
              (newpos (length (completion-pcm--pattern->string pointpat)))
@@ -1884,13 +2200,47 @@ filter out additional entries (because TABLE migth not obey PRED)."
            'completion-pcm--filename-try-filter))
     (completion-pcm--merge-try pattern all prefix suffix)))
 
-;;; Initials completion
+;;; Substring completion
+;; Mostly derived from the code of `basic' completion.
+
+(defun completion-substring--all-completions (string table pred point)
+  (let* ((beforepoint (substring string 0 point))
+         (afterpoint (substring string point))
+         (bounds (completion-boundaries beforepoint table pred afterpoint))
+         (suffix (substring afterpoint (cdr bounds)))
+         (prefix (substring beforepoint 0 (car bounds)))
+         (basic-pattern (completion-basic--pattern
+                         beforepoint afterpoint bounds))
+         (pattern (if (not (stringp (car basic-pattern)))
+                      basic-pattern
+                    (cons 'prefix basic-pattern)))
+         (all (completion-pcm--all-completions prefix pattern table pred)))
+    (list all pattern prefix suffix (car bounds))))
+
+(defun completion-substring-try-completion (string table pred point)
+  (destructuring-bind (all pattern prefix suffix carbounds)
+      (completion-substring--all-completions string table pred point)
+    (if minibuffer-completing-file-name
+        (setq all (completion-pcm--filename-try-filter all)))
+    (completion-pcm--merge-try pattern all prefix suffix)))
+
+(defun completion-substring-all-completions (string table pred point)
+  (destructuring-bind (all pattern prefix suffix carbounds)
+      (completion-substring--all-completions string table pred point)
+    (when all
+      (nconc (completion-pcm--hilit-commonality pattern all)
+             (length prefix)))))
+
+;; Initials completion
 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
 
 (defun completion-initials-expand (str table pred)
-  (unless (or (zerop (length str))
-              (string-match completion-pcm--delim-wild-regex str))
-    (let ((bounds (completion-boundaries str table pred "")))
+  (let ((bounds (completion-boundaries str table pred "")))
+    (unless (or (zerop (length str))
+                ;; Only check within the boundaries, since the
+                ;; boundary char (e.g. /) might be in delim-regexp.
+                (string-match completion-pcm--delim-wild-regex str
+                              (car bounds)))
       (if (zerop (car bounds))
           (mapconcat 'string str "-")
         ;; If there's a boundary, it's trickier.  The main use-case
@@ -1922,6 +2272,17 @@ filter out additional entries (because TABLE migth not obey PRED)."
     (when newstr
       (completion-pcm-try-completion newstr table pred (length newstr)))))
 
+\f
+;; Miscellaneous
+
+(defun minibuffer-insert-file-name-at-point ()
+  "Get a file name at point in original buffer and insert it to minibuffer."
+  (interactive)
+  (let ((file-name-at-point
+        (with-current-buffer (window-buffer (minibuffer-selected-window))
+          (run-hook-with-args-until-success 'file-name-at-point-functions))))
+    (when file-name-at-point
+      (insert file-name-at-point))))
 
 (provide 'minibuffer)