corfu.el - COmpletion in Region FUnction

Next:   [Contents]

corfu.el - COmpletion in Region FUnction

Corfu enhances in-buffer completion with a small completion popup. The current candidates are shown in a popup below or above the point. The candidates can be selected by moving up and down. Corfu is the minimalistic in-buffer completion counterpart of the Vertico minibuffer UI.

Corfu is a small package, which relies on the Emacs completion facilities and concentrates on providing a polished completion UI. In-buffer completion UIs in Emacs can hook into completion-in-region, which implements the interaction with the user. Completions at point are either provided by commands like dabbrev-completion or by pluggable backends (completion-at-point-functions, Capfs) and are then passed to completion-in-region. Many programming, text and shell major modes implement a Capf. Corfu does not include its own completion backends. The Emacs built-in Capfs and the Capfs provided by third-party programming language packages are often sufficient. Additional Capfs and completion utilities are provided by the Cape package.

NOTE: Corfu uses child frames to show the popup and falls back to the default setting of the completion-in-region-function on non-graphical displays. If you want to use Corfu in the terminal, install the package corfu-terminal, which provides an alternative overlay-based display.

Table of Contents


1 Features


2 Installation

Corfu is available from GNU ELPA. You can install it directly via ‘M-x package-install RET corfu RET’. After installation, activate the global minor mode with ‘M-x global-corfu-mode RET’. Set the variable corfu-auto to t in order to enable auto completion. For manual completion press ‘M-TAB’ (or ‘TAB’) within a buffer.


3 Key bindings

Corfu uses a transient keymap corfu-map which is active while the popup is shown. The keymap defines the following remappings of fundamental commands and bindings:

Binding/RemappingCorfu command
move-beginning-of-linecorfu-prompt-beginning
move-end-of-linecorfu-prompt-end
beginning-of-buffercorfu-first
end-of-buffercorfu-last
scroll-down-commandcorfu-scroll-down
scroll-up-commandcorfu-scroll-up
next-line, ‘down’, ‘M-ncorfu-next
previous-line, ‘up’, ‘M-pcorfu-previous
completion-at-point, ‘TABcorfu-complete
M-TABcorfu-expand
RETcorfu-insert
M-gcorfu-info-location
M-hcorfu-info-documentation
M-SPCcorfu-insert-separator
C-gcorfu-quit
keyboard-escape-quitcorfu-reset

4 Configuration

In order to configure Corfu and other packages in your init.el, you may want to use use-package. Corfu is flexibly customizable via corfu-* customization variables, such that you can adapt it precisely to your requirements. However in order to quickly try out the Corfu completion package, it should be sufficient to activate global-corfu-mode. You can experiment with manual completion for example in an Elisp buffer or in an Eshell or Shell buffer. For auto completion, set corfu-auto to t before turning on global-corfu-mode.

Here is an example configuration:

(use-package corfu
  ;; Optional customizations
  ;; :custom
  ;; (corfu-cycle t)                ;; Enable cycling for `corfu-next/previous'
  ;; (corfu-auto t)                 ;; Enable auto completion
  ;; (corfu-separator ?\s)          ;; Orderless field separator
  ;; (corfu-quit-at-boundary nil)   ;; Never quit at completion boundary
  ;; (corfu-quit-no-match nil)      ;; Never quit, even if there is no match
  ;; (corfu-preview-current nil)    ;; Disable current candidate preview
  ;; (corfu-preselect 'prompt)      ;; Preselect the prompt
  ;; (corfu-on-exact-match nil)     ;; Configure handling of exact matches
  ;; (corfu-scroll-margin 5)        ;; Use scroll margin

  ;; Enable Corfu only for certain modes. See also `global-corfu-modes'.
  ;; :hook ((prog-mode . corfu-mode)
  ;;        (shell-mode . corfu-mode)
  ;;        (eshell-mode . corfu-mode))

  ;; Recommended: Enable Corfu globally.  This is recommended since Dabbrev can
  ;; be used globally (M-/).  See also the customization variable
  ;; `global-corfu-modes' to exclude certain modes.
  :init
  (global-corfu-mode))

;; A few more useful configurations...
(use-package emacs
  :custom
  ;; TAB cycle if there are only few candidates
  ;; (completion-cycle-threshold 3)

  ;; Enable indentation+completion using the TAB key.
  ;; `completion-at-point' is often bound to M-TAB.
  (tab-always-indent 'complete)

  ;; Emacs 30 and newer: Disable Ispell completion function. As an alternative,
  ;; try `cape-dict'.
  (text-mode-ispell-word-completion nil)

  ;; Emacs 28 and newer: Hide commands in M-x which do not apply to the current
  ;; mode.  Corfu commands are hidden, since they are not used via M-x. This
  ;; setting is useful beyond Corfu.
  (read-extended-command-predicate #'command-completion-default-include-p))

Dabbrev completion is based on ‘completion-in-region’ and can be used with Corfu. You may want to swap the ‘dabbrev-completion’ with the ‘dabbrev-expand’ key for easier access, if you prefer completion. Also take a look at the ‘cape-dabbrev’ completion at point function provided by my Cape package.

;; Use Dabbrev with Corfu!
(use-package dabbrev
  ;; Swap M-/ and C-M-/
  :bind (("M-/" . dabbrev-completion)
         ("C-M-/" . dabbrev-expand))
  :config
  (add-to-list 'dabbrev-ignored-buffer-regexps "\\` ")
  ;; Since 29.1, use `dabbrev-ignored-buffer-regexps' on older.
  (add-to-list 'dabbrev-ignored-buffer-modes 'doc-view-mode)
  (add-to-list 'dabbrev-ignored-buffer-modes 'pdf-view-mode)
  (add-to-list 'dabbrev-ignored-buffer-modes 'tags-table-mode))

If you start to configure the package more deeply, I recommend to give the Orderless completion style a try for filtering. Orderless completion is different from the familiar prefix TAB completion. Corfu can be used with the default completion styles. The use of Orderless is not a necessity.

;; Optionally use the `orderless' completion style.
(use-package orderless
  :custom
  ;; Configure a custom style dispatcher (see the Consult wiki)
  ;; (orderless-style-dispatchers '(+orderless-dispatch))
  ;; (orderless-component-separator #'orderless-escapable-split-on-space)
  (completion-styles '(orderless basic))
  (completion-category-defaults nil)
  (completion-category-overrides '((file (styles partial-completion)))))

The ‘basic’ completion style is specified as fallback in addition to ‘orderless’ in order to ensure that completion commands which rely on dynamic completion tables, e.g., completion-table-dynamic or completion-table-in-turn, work correctly. See ‘+orderless-dispatch’ in the Consult wiki for an advanced Orderless style dispatcher. Additionally enable ‘partial-completion’ for file path expansion. ‘partial-completion’ is important for file wildcard support. Multiple files can be opened at once with ‘find-file’ if you enter a wildcard. You may also give the ‘initials’ completion style a try.

See also the Corfu Wiki and the Cape manual for additional Capf configuration tips. For more general documentation read the chapter about completion in the Emacs manual. If you want to create your own Capfs, you can find documentation about completion in the Elisp manual.


4.1 Auto completion

Auto completion is disabled by default, but can be enabled by setting corfu-auto to t. Furthermore you may want to configure Corfu to quit completion eagerly, such that the completion popup stays out of your way when it appeared unexpectedly.

;; Enable auto completion and configure quitting
(setq corfu-auto t
      corfu-quit-no-match 'separator) ;; or t

I suggest to experiment with the various settings and key bindings to find a configuration which works for you. There is no one perfect configuration which fits all. Some people like auto completion, some like manual completion, some want to cycle with TAB and some with the arrow keys.

In case you like auto completion settings, where the completion popup appears immediately, better use a cheap completion style like ‘basic’, which performs prefix filtering. In this case Corfu completion should still be fast in buffers with efficient completion backends. You can try the following settings in an Elisp buffer or the Emacs scratch buffer. Note that such settings can slow down Emacs due to the high load on the Lisp runtime and garbage collector.

(setq-local corfu-auto        t
            corfu-auto-delay  0 ;; TOO SMALL - NOT RECOMMENDED
            corfu-auto-prefix 1 ;; TOO SMALL - NOT RECOMMENDED
            completion-styles '(basic))

If you want to combine fast prefix filtering and Orderless filtering you can still do that by defining a custom Orderless completion style via ‘orderless-define-completion-style’. We use a custom style dispatcher, which enables efficient prefix filtering for input shorter than 4 characters. Note that such a setup is advanced. Please refer to the Orderless documentation and source code for further details.

(defun orderless-fast-dispatch (word index total)
  (and (= index 0) (= total 1) (length< word 4)
       (cons 'orderless-literal-prefix word)))

(orderless-define-completion-style orderless-fast
  (orderless-style-dispatchers '(orderless-fast-dispatch))
  (orderless-matching-styles '(orderless-literal orderless-regexp)))

(setq-local corfu-auto        t
            corfu-auto-delay  0 ;; TOO SMALL - NOT RECOMMENDED
            corfu-auto-prefix 1 ;; TOO SMALL - NOT RECOMMENDED
            completion-styles '(orderless-fast basic))

4.2 Completing in the minibuffer

Corfu can be used for completion in the minibuffer, since it relies on child frames to display the candidates. The Corfu popup can be shown even if it doesn’t fully fit inside the minibuffer.

global-corfu-mode activates corfu-mode in the minibuffer if the variable global-corfu-minibuffer is non-nil. In order to avoid interference with specialised minibuffer completion UIs like Vertico or Mct, Corfu is only enabled if the minibuffer sets the variable completion-at-point-functions locally. This way minibuffers with completion can be detected, such that minibuffer commands like M-: (eval-expression) or M-! (shell-command) are enhanced with Corfu completion.

If needed, one can also enable Corfu more generally in all minibuffers, as long as no completion UI is active. In the following example we set global-corfu-minibuffer to a predicate function, which checks for Mct and Vertico. Furthermore we ensure that Corfu is not enabled if a password is read from the minibuffer.

(setq global-corfu-minibuffer
      (lambda ()
        (not (or (bound-and-true-p mct--active)
                 (bound-and-true-p vertico--input)
                 (eq (current-local-map) read-passwd-map)))))

4.3 Completing in the Eshell or Shell

When completing in the Eshell I recommend conservative local settings without auto completion, such that the completion behavior is similar to widely used shells like Bash, Zsh or Fish.

(add-hook 'eshell-mode-hook
          (lambda ()
            (setq-local corfu-auto nil)
            (corfu-mode)))

When pressing ‘RET’ while the Corfu popup is visible, the corfu-insert command will be invoked. This command does inserts the currently selected candidate, but it does not send the prompt input to Eshell or the Comint process. Therefore you often have to press ‘RET’ twice which feels like an unnecessary double confirmation. Fortunately it is easy to improve this by using the command corfu-send instead.

(keymap-set corfu-map "RET" #'corfu-send)

Shell completion uses the flexible Pcomplete mechanism internally, which allows you to program the completions per shell command. If you want to know more, look into this blog post, which shows how to configure Pcomplete for git commands. Since Emacs 29, Pcomplete offers the ‘pcomplete-from-help’ function which parses the --help output of a command and produces completions for command line options.

Pcomplete has a few bugs on Emacs 28 and older. We can work around the issues with the Cape library (Completion at point extensions). Cape provides wrappers which sanitize the Pcomplete function. On Emacs 29 the advices should not be necessary anymore, since most relevant bugs have been fixed. In case you discover any remaining Pcomplete issues, please report them upstream.

;; Sanitize the `pcomplete-completions-at-point' Capf.  The Capf has undesired
;; side effects on Emacs 28 and earlier.  These advices are not needed on Emacs
;; 29 and newer.
(when (< emacs-major-version 29)
  (advice-add 'pcomplete-completions-at-point :around #'cape-wrap-silent)
  (advice-add 'pcomplete-completions-at-point :around #'cape-wrap-purify))

4.4 Orderless completion

Orderless is an advanced completion style that supports multi-component search filters separated by a configurable character (space, by default). Normally, entering characters like space which lie outside the completion region boundaries (words, typically) causes Corfu to quit. This behavior is helpful with auto-completion, which may pop-up when not desired, e.g. on entering a new variable name. Just keep typing and Corfu will get out of the way.

But orderless search terms can contain arbitrary characters; they are also interpreted as regular expressions. To use orderless, set corfu-separator (a space, by default) to the primary character of your orderless component separator.

Then, when a new orderless component is desired, use ‘M-SPC’ (corfu-insert-separator) to enter the first component separator in the input, and arbitrary orderless search terms and new separators can be entered thereafter.

To treat the entire input as Orderless input, you can set the customization option corfu-quit-at-boundary to nil. This disables the predicate which checks if the current completion boundary has been left. In contrast, if you always want to quit at the boundary, set corfu-quit-at-boundary to t. By default corfu-quit-at-boundary is set to separator which quits at completion boundaries as long as no separator has been inserted with corfu-insert-separator.

Finally, there exists the user option corfu-quit-no-match which is set to ‘separator’ by default. With this setting Corfu stays alive as soon as you start advanced filtering with a corfu-separator even if there are no matches, for example due to a typo. As long as no separator character has been inserted with corfu-insert-separator, Corfu will still quit if there are no matches. This ensures that the Corfu popup goes away quickly if completion is not possible.

In the following we show two configurations, one which works best with auto completion and one which may work better with manual completion if you prefer to always use ‘SPC’ to separate the Orderless components.

;; Auto completion example
(use-package corfu
  :custom
  (corfu-auto t)          ;; Enable auto completion
  ;; (corfu-separator ?_) ;; Set to orderless separator, if not using space
  :bind
  ;; Another key binding can be used, such as S-SPC.
  ;; (:map corfu-map ("M-SPC" . corfu-insert-separator))
  :init
  (global-corfu-mode))

;; Manual completion example
(use-package corfu
  :custom
  ;; (corfu-separator ?_) ;; Set to orderless separator, if not using space
  :bind
  ;; Configure SPC for separator insertion
  (:map corfu-map ("SPC" . corfu-insert-separator))
  :init
  (global-corfu-mode))

4.5 TAB-only completion

By default, Corfu steals both the RET and TAB keys, when the Corfu popup is open. This can feel intrusive, in particular in combination with auto completion. RET may accidentally commit an automatically selected candidate, while you actually wanted to start a new line. As an alternative we can unbind the RET key completely from corfu-map or reserve the RET key only in shell modes using a menu-item filter.

;; TAB-only configuration
(use-package corfu
  :custom
  (corfu-auto t)               ;; Enable auto completion
  (corfu-preselect 'directory) ;; Select the first candidate, except for directories

  ;; Free the RET key for less intrusive behavior.
  :bind
  (:map corfu-map
        ;; Option 1: Unbind RET completely
        ;;; ("RET" . nil)
        ;; Option 2: Use RET only in shell modes
        ("RET" . (menu-item
                  "" nil :filter
                  (lambda (&optional _)
                    (and (or (derived-mode-p 'eshell-mode) (derived-mode-p 'comint-mode))
                         #'corfu-send)))))

  :init
  (global-corfu-mode))

4.6 TAB-and-Go completion

You may be interested in configuring Corfu in TAB-and-Go style. Pressing TAB moves to the next candidate and further input will then commit the selection. Note that further input will not expand snippets or templates, which may not be desired but which leads overall to a more predictable behavior. In order to force snippet expansion, confirm a candidate explicitly with RET.

(use-package corfu
  ;; TAB-and-Go customizations
  :custom
  (corfu-cycle t)           ;; Enable cycling for `corfu-next/previous'
  (corfu-preselect 'prompt) ;; Always preselect the prompt

  ;; Use TAB for cycling, default is `corfu-complete'.
  :bind
  (:map corfu-map
        ("TAB" . corfu-next)
        ([tab] . corfu-next)
        ("S-TAB" . corfu-previous)
        ([backtab] . corfu-previous))

  :init
  (global-corfu-mode))

4.7 Expanding to the common candidate prefix with TAB

If you leave the default configuration of the completion styles, such that the basic completion style is still present, then pressing M-TAB (corfu-expand) will expand the current input to the common prefix of all completion candidates. In contrast, TAB (corfu-complete) behaves differently and expands input to the currently selected candidate.

If you use the orderless completion style, then expansion works differently by default. Orderless only expands to single matching candidates, since due to its multi-component input, there does not necessarily exist an expansion to a common candidate prefix. However it is possible to define a separate tab completion style. The tab completion style will only take over TAB completion (if prefix expansion is possible), but besides that won’t affect Orderless candidate filtering.

(add-to-list 'completion-styles-alist
             '(tab completion-basic-try-completion ignore
               "Completion style which provides TAB completion only."))
(setq completion-styles '(tab orderless basic)))

4.8 Transfer completion to the minibuffer

Sometimes it is useful to transfer the Corfu completion session to the minibuffer, since the minibuffer offers richer interaction features. In particular, Embark is available in the minibuffer, such that you can act on the candidates or export/collect the candidates to a separate buffer. We could add Corfu support to Embark in the future, such that export or collect is possible directly from Corfu. Nevertheless, the ability to transfer the Corfu completion to the minibuffer is even more powerful, since further completion is possible.

The command corfu-move-to-minibuffer is defined here in terms of consult-completion-in-region, which uses the minibuffer completion UI via completing-read.

(defun corfu-move-to-minibuffer ()
  (interactive)
  (pcase completion-in-region--data
    (`(,beg ,end ,table ,pred ,extras)
     (let ((completion-extra-properties extras)
           completion-cycle-threshold completion-cycling)
       (consult-completion-in-region beg end table pred)))))
(keymap-set corfu-map "M-m" #'corfu-move-to-minibuffer)
(add-to-list 'corfu-continue-commands #'corfu-move-to-minibuffer)

5 Extensions

We maintain small extension packages to Corfu in this repository in the subdirectory extensions/. The extensions are installed together with Corfu if you pull the package from ELPA. The extensions are inactive by default and can be enabled manually if desired. Furthermore it is possible to install all of the files separately, both corfu.el and the corfu-*.el extensions. Currently the following extensions come with the Corfu ELPA package:

See the Commentary of those files for configuration details.


6 Complementary packages

Corfu works well together with all packages providing code completion via the completion-at-point-functions. Many modes and packages already provide a Capf out of the box. Nevertheless you may want to look into complementary packages to enhance your setup.


7 Alternatives


8 Debugging Corfu

When you observe an error in the ‘corfu--post-command’ post command hook, you should install an advice to enforce debugging. This allows you to obtain a stack trace in order to narrow down the location of the error. The reason is that post command hooks are automatically disabled (and not debugged) by Emacs. Otherwise Emacs would become unusable, given that the hooks are executed after every command.

(setq debug-on-error t)

(defun force-debug (func &rest args)
  (condition-case e
      (apply func args)
    ((debug error) (signal (car e) (cdr e)))))

(advice-add #'corfu--post-command :around #'force-debug)

When Capfs do not yield the expected result you can use cape-capf-debug to add debug messages to a Capf. The Capf will then produce a completion log in the messages buffer.

(setq completion-at-point-functions (list (cape-capf-debug #'cape-dict)))

9 Contributions

Since this package is part of GNU ELPA contributions require a copyright assignment to the FSF.