config

Personal configuration.
git clone git://code.dwrz.net/config
Log | Files | Refs

cape.el (54000B)


      1 ;;; cape.el --- Completion At Point Extensions -*- lexical-binding: t -*-
      2 
      3 ;; Copyright (C) 2021-2024 Free Software Foundation, Inc.
      4 
      5 ;; Author: Daniel Mendler <mail@daniel-mendler.de>
      6 ;; Maintainer: Daniel Mendler <mail@daniel-mendler.de>
      7 ;; Created: 2021
      8 ;; Version: 1.5
      9 ;; Package-Requires: ((emacs "27.1") (compat "29.1.4.4"))
     10 ;; Homepage: https://github.com/minad/cape
     11 ;; Keywords: abbrev, convenience, matching, completion, text
     12 
     13 ;; This file is part of GNU Emacs.
     14 
     15 ;; This program is free software: you can redistribute it and/or modify
     16 ;; it under the terms of the GNU General Public License as published by
     17 ;; the Free Software Foundation, either version 3 of the License, or
     18 ;; (at your option) any later version.
     19 
     20 ;; This program is distributed in the hope that it will be useful,
     21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
     22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     23 ;; GNU General Public License for more details.
     24 
     25 ;; You should have received a copy of the GNU General Public License
     26 ;; along with this program.  If not, see <https://www.gnu.org/licenses/>.
     27 
     28 ;;; Commentary:
     29 
     30 ;; Let your completions fly! This package provides additional completion
     31 ;; backends in the form of Capfs (completion-at-point-functions).
     32 ;;
     33 ;; `cape-abbrev': Complete abbreviation (add-global-abbrev, add-mode-abbrev).
     34 ;; `cape-dabbrev': Complete word from current buffers.
     35 ;; `cape-dict': Complete word from dictionary file.
     36 ;; `cape-elisp-block': Complete Elisp in Org or Markdown code block.
     37 ;; `cape-elisp-symbol': Complete Elisp symbol.
     38 ;; `cape-emoji': Complete Emoji.
     39 ;; `cape-file': Complete file name.
     40 ;; `cape-history': Complete from Eshell, Comint or minibuffer history.
     41 ;; `cape-keyword': Complete programming language keyword.
     42 ;; `cape-line': Complete entire line from file.
     43 ;; `cape-rfc1345': Complete Unicode char using RFC 1345 mnemonics.
     44 ;; `cape-sgml': Complete Unicode char from SGML entity, e.g., &alpha.
     45 ;; `cape-tex': Complete Unicode char from TeX command, e.g. \hbar.
     46 
     47 ;;; Code:
     48 
     49 (require 'compat)
     50 (eval-when-compile
     51   (require 'cl-lib)
     52   (require 'subr-x))
     53 
     54 ;;;; Customization
     55 
     56 (defgroup cape nil
     57   "Completion At Point Extensions."
     58   :link '(info-link :tag "Info Manual" "(cape)")
     59   :link '(url-link :tag "Homepage" "https://github.com/minad/cape")
     60   :link '(emacs-library-link :tag "Library Source" "cape.el")
     61   :group 'convenience
     62   :group 'tools
     63   :group 'matching
     64   :prefix "cape-")
     65 
     66 (defcustom cape-dict-limit 100
     67   "Maximal number of completion candidates returned by `cape-dict'."
     68   :type '(choice (const nil) natnum))
     69 
     70 (defcustom cape-dict-file "/usr/share/dict/words"
     71   "Path to dictionary word list file.
     72 This variable can also be a list of paths or
     73 a function returning a single or more paths."
     74   :type '(choice string (repeat string) function))
     75 
     76 (defcustom cape-dict-case-replace 'case-replace
     77   "Preserve case of input.
     78 See `dabbrev-case-replace' for details."
     79   :type '(choice (const :tag "off" nil)
     80                  (const :tag "use `case-replace'" case-replace)
     81                  (other :tag "on" t)))
     82 
     83 (defcustom cape-dict-case-fold 'case-fold-search
     84   "Case fold search during search.
     85 See `dabbrev-case-fold-search' for details."
     86   :type '(choice (const :tag "off" nil)
     87                  (const :tag "use `case-fold-search'" case-fold-search)
     88                  (other :tag "on" t)))
     89 
     90 (defcustom cape-dabbrev-min-length 4
     91   "Minimum length of Dabbrev expansions.
     92 This setting ensures that words which are too short
     93 are not offered as completion candidates, such that
     94 auto completion does not pop up too aggressively."
     95   :type 'natnum)
     96 
     97 (defcustom cape-dabbrev-check-other-buffers t
     98   "Buffers to check for Dabbrev.
     99 
    100 If t, check all other buffers, subject to Dabbrev ignore rules.
    101 If a function, only search the buffers returned by this function.
    102 Any other non-nil value only checks some other buffers, as per
    103 `dabbrev-select-buffers-function'."
    104   :type `(choice (const :tag "off" nil)
    105                  (const :tag "same-mode buffers" ,#'cape--buffers-major-mode)
    106                  (function :tag "function")
    107                  (const :tag "some" some)
    108                  (other :tag "all" t)))
    109 
    110 (defcustom cape-file-directory nil
    111   "Base directory used by `cape-file."
    112   :type '(choice (const nil) string function))
    113 
    114 (defcustom cape-file-prefix "file:"
    115   "File completion trigger prefixes.
    116 The value can be a string or a list of strings.  The default
    117 `file:' is the prefix of Org file links which work in arbitrary
    118 buffers via `org-open-at-point-global'."
    119   :type '(choice string (repeat string)))
    120 
    121 (defcustom cape-file-directory-must-exist t
    122   "The parent directory must exist for file completion."
    123   :type 'boolean)
    124 
    125 (defcustom cape-line-buffer-function #'cape--buffers-major-mode
    126   "Function which returns list of buffers.
    127 The buffers are scanned for completion candidates by `cape-line'."
    128   :type '(choice (const :tag "Current buffer" current-buffer)
    129                  (const :tag "All buffers" buffer-list)
    130                  (const :tag "Buffers with same major mode" cape--buffers-major-mode)
    131                  (function :tag "Custom function")))
    132 
    133 (defcustom cape-elisp-symbol-wrapper
    134   '((org-mode ?~ ?~)
    135     (markdown-mode ?` ?`)
    136     (rst-mode "``" "``")
    137     (log-edit-mode "`" "'")
    138     (change-log-mode "`" "'")
    139     (message-mode "`" "'")
    140     (rcirc-mode "`" "'"))
    141   "Wrapper characters for symbols."
    142   :type '(alist :key-type symbol :value-type (list (choice character string)
    143                                                    (choice character string))))
    144 
    145 ;;;; Helpers
    146 
    147 (defun cape--case-fold-p (fold)
    148   "Return non-nil if case folding is enabled for FOLD."
    149   (if (eq fold 'case-fold-search) case-fold-search fold))
    150 
    151 (defun cape--case-replace-list (flag input strs)
    152   "Replace case of STRS depending on INPUT and FLAG."
    153   (if (and (if (eq flag 'case-replace) case-replace flag)
    154            (let (case-fold-search) (string-match-p "\\`[[:upper:]]" input)))
    155       (mapcar (apply-partially #'cape--case-replace flag input) strs)
    156     strs))
    157 
    158 (defun cape--case-replace (flag input str)
    159   "Replace case of STR depending on INPUT and FLAG."
    160   (or (and (if (eq flag 'case-replace) case-replace flag)
    161            (string-prefix-p input str t)
    162            (let (case-fold-search) (string-match-p "\\`[[:upper:]]" input))
    163            (save-match-data
    164              ;; Ensure that single character uppercase input does not lead to an
    165              ;; all uppercase result.
    166              (when (and (= (length input) 1) (> (length str) 1))
    167                (setq input (concat input (substring str 1 2))))
    168              (and (string-match input input)
    169                   (replace-match str nil nil input))))
    170       str))
    171 
    172 (defun cape--separator-p (str)
    173   "Return non-nil if input STR has a separator character.
    174 Separator characters are used by completion styles like Orderless
    175 to split filter words.  In Corfu, the separator is configurable
    176 via the variable `corfu-separator'."
    177   (string-search (string ;; Support `corfu-separator' and Orderless
    178                   (or (and (bound-and-true-p corfu-mode)
    179                            (bound-and-true-p corfu-separator))
    180                       ?\s))
    181                  str))
    182 
    183 (defmacro cape--silent (&rest body)
    184   "Silence BODY."
    185   (declare (indent 0))
    186   `(cl-letf ((inhibit-message t)
    187              (message-log-max nil)
    188              ((symbol-function #'minibuffer-message) #'ignore))
    189      (ignore-errors ,@body)))
    190 
    191 (defun cape--bounds (thing)
    192   "Return bounds of THING."
    193   (or (bounds-of-thing-at-point thing) (cons (point) (point))))
    194 
    195 (defmacro cape--wrapped-table (wrap body)
    196   "Create wrapped completion table, handle `completion--unquote'.
    197 WRAP is the wrapper function.
    198 BODY is the wrapping expression."
    199   (declare (indent 1))
    200   `(lambda (str pred action)
    201      (,@body
    202       (let ((result (complete-with-action action table str pred)))
    203         (when (and (eq action 'completion--unquote) (functionp (cadr result)))
    204           (cl-callf ,wrap (cadr result)))
    205         result))))
    206 
    207 (defun cape--accept-all-table (table)
    208   "Create completion TABLE which accepts all input."
    209   (cape--wrapped-table cape--accept-all-table
    210     (or (eq action 'lambda))))
    211 
    212 (defun cape--passthrough-table (table)
    213   "Create completion TABLE disabling any filtering."
    214   (cape--wrapped-table cape--passthrough-table
    215     (let (completion-ignore-case completion-regexp-list (_ (setq str ""))))))
    216 
    217 (defun cape--noninterruptible-table (table)
    218   "Create non-interruptible completion TABLE."
    219   (cape--wrapped-table cape--noninterruptible-table
    220     (let (throw-on-input))))
    221 
    222 (defun cape--silent-table (table)
    223   "Create a new completion TABLE which is silent (no messages, no errors)."
    224   (cape--wrapped-table cape--silent-table
    225     (cape--silent)))
    226 
    227 (defun cape--nonessential-table (table)
    228   "Mark completion TABLE as `non-essential'."
    229   (let ((dir default-directory))
    230     (cape--wrapped-table cape--nonessential-table
    231       (let ((default-directory dir)
    232             (non-essential t))))))
    233 
    234 (defvar cape--debug-length 5
    235   "Length of printed lists in `cape--debug-print'.")
    236 
    237 (defvar cape--debug-id 0
    238   "Completion table identifier.")
    239 
    240 (defun cape--debug-message (&rest msg)
    241   "Print debug MSG."
    242   (let ((inhibit-message t))
    243     (apply #'message msg)))
    244 
    245 (defun cape--debug-print (obj &optional full)
    246   "Print OBJ as string, truncate lists if FULL is nil."
    247   (cond
    248    ((symbolp obj) (symbol-name obj))
    249    ((functionp obj) "#<function>")
    250    ((proper-list-p obj)
    251     (concat
    252      "("
    253      (string-join
    254       (mapcar #'cape--debug-print
    255               (if full obj (take cape--debug-length obj)))
    256       " ")
    257      (if (and (not full) (length> obj cape--debug-length)) " ...)" ")")))
    258    (t (let ((print-level 2))
    259         (prin1-to-string obj)))))
    260 
    261 (defun cape--debug-table (table name beg end)
    262   "Create completion TABLE with debug messages.
    263 NAME is the name of the Capf, BEG and END are the input markers."
    264   (lambda (str pred action)
    265     (let ((result (complete-with-action action table str pred)))
    266       (if (and (eq action 'completion--unquote) (functionp (cadr result)))
    267           ;; See `cape--wrapped-table'
    268           (cl-callf cape--debug-table (cadr result) name beg end)
    269         (cape--debug-message
    270          "%s(action=%S input=%s:%s:%S prefix=%S ignore-case=%S%s%s) => %s"
    271          name
    272          (pcase action
    273            ('nil 'try)
    274            ('t 'all)
    275            ('lambda 'test)
    276            (_ action))
    277          (+ beg 0) (+ end 0) (buffer-substring-no-properties beg end)
    278          str completion-ignore-case
    279          (if completion-regexp-list
    280              (format " regexp=%s" (cape--debug-print completion-regexp-list t))
    281            "")
    282          (if pred
    283              (format " predicate=%s" (cape--debug-print pred))
    284            "")
    285          (cape--debug-print result)))
    286       result)))
    287 
    288 (cl-defun cape--properties-table (table &key category (sort t) &allow-other-keys)
    289   "Create completion TABLE with properties.
    290 CATEGORY is the optional completion category.
    291 SORT should be nil to disable sorting."
    292   ;; The metadata will be overridden if the category is non-nil, if the table is
    293   ;; a function table or if sorting should be disabled for a non-nil
    294   ;; non-function table.
    295   (if (or category (functionp table) (and (not sort) table))
    296       (let ((metadata `(metadata
    297                         ,@(and category `((category . ,category)))
    298                         ,@(and (not sort) '((display-sort-function . identity)
    299                                             (cycle-sort-function . identity))))))
    300         (lambda (str pred action)
    301           (if (eq action 'metadata)
    302               metadata
    303             (complete-with-action action table str pred))))
    304     table))
    305 
    306 (defun cape--dynamic-table (beg end fun)
    307   "Create dynamic completion table from FUN with caching.
    308 BEG and END are the input bounds.  FUN is the function which
    309 computes the candidates.  FUN must return a pair of a predicate
    310 function function and the list of candidates.  The predicate is
    311 passed new input and must return non-nil if the candidates are
    312 still valid.
    313 
    314 It is only necessary to use this function if the set of
    315 candidates is computed dynamically based on the input and not
    316 statically determined.  The behavior is similar but slightly
    317 different to `completion-table-dynamic'.
    318 
    319 The difference to the builtins `completion-table-dynamic' and
    320 `completion-table-with-cache' is that this function does not use
    321 the prefix argument of the completion table to compute the
    322 candidates.  Instead it uses the input in the buffer between BEG
    323 and END to FUN to compute the candidates.  This way the dynamic
    324 candidate computation is compatible with non-prefix completion
    325 styles like `substring' or `orderless', which pass the empty
    326 string as first argument to the completion table."
    327   (let ((beg (copy-marker beg))
    328         (end (copy-marker end t))
    329         valid table)
    330     (lambda (str pred action)
    331       ;; Bail out early for `metadata' and `boundaries'. This is a pointless
    332       ;; move because of caching, but we do it anyway in the hope that the
    333       ;; profiler report looks less confusing, since the weight of the expensive
    334       ;; FUN computation is moved to the `all-completions' action.  Computing
    335       ;; `all-completions' must surely be most expensive, so nobody will suspect
    336       ;; a thing.
    337       (unless (or (eq action 'metadata) (eq (car-safe action) 'boundaries))
    338         (let ((input (buffer-substring-no-properties beg end)))
    339           (unless (and valid
    340                        (or (cape--separator-p input)
    341                            (funcall valid input)))
    342             (let* (;; Reset in case `all-completions' is used inside FUN
    343                    completion-ignore-case completion-regexp-list
    344                    ;; Retrieve new state by calling FUN
    345                    (new (funcall fun input))
    346                    ;; No interrupt during state update
    347                    throw-on-input)
    348               (setq valid (car new) table (cdr new)))))
    349         (complete-with-action action table str pred)))))
    350 
    351 ;;;; Capfs
    352 
    353 ;;;;; cape-history
    354 
    355 (declare-function ring-elements "ring")
    356 (declare-function eshell-bol "eshell")
    357 (declare-function comint-bol "comint")
    358 (defvar eshell-history-ring)
    359 (defvar comint-input-ring)
    360 
    361 (defvar cape--history-properties
    362   (list :company-kind (lambda (_) 'text)
    363         :exclusive 'no)
    364   "Completion extra properties for `cape-history'.")
    365 
    366 ;;;###autoload
    367 (defun cape-history (&optional interactive)
    368   "Complete from Eshell, Comint or minibuffer history.
    369 See also `consult-history' for a more flexible variant based on
    370 `completing-read'.  If INTERACTIVE is nil the function acts like a Capf."
    371   (interactive (list t))
    372   (if interactive
    373       (cape-interactive #'cape-history)
    374     (let (history bol)
    375       (cond
    376        ((derived-mode-p 'eshell-mode)
    377         (setq history eshell-history-ring
    378               bol (save-excursion (eshell-bol) (point))))
    379        ((derived-mode-p 'comint-mode)
    380         (setq history comint-input-ring
    381               bol (save-excursion (comint-bol) (point))))
    382        ((and (minibufferp) (not (eq minibuffer-history-variable t)))
    383         (setq history (symbol-value minibuffer-history-variable)
    384               bol (line-beginning-position))))
    385       (when (ring-p history)
    386         (setq history (ring-elements history)))
    387       (when history
    388         `(,bol ,(point)
    389           ,(cape--properties-table history :sort nil)
    390           ,@cape--history-properties)))))
    391 
    392 ;;;;; cape-file
    393 
    394 (defvar comint-unquote-function)
    395 (defvar comint-requote-function)
    396 
    397 (defvar cape--file-properties
    398   (list :annotation-function (lambda (s) (if (string-suffix-p "/" s) " Dir" " File"))
    399         :company-kind (lambda (s) (if (string-suffix-p "/" s) 'folder 'file))
    400         :exclusive 'no)
    401   "Completion extra properties for `cape-file'.")
    402 
    403 ;;;###autoload
    404 (defun cape-file (&optional interactive)
    405   "Complete file name at point.
    406 See the user option `cape-file-directory-must-exist'.
    407 If INTERACTIVE is nil the function acts like a Capf."
    408   (interactive (list t))
    409   (if interactive
    410       (cape-interactive '(cape-file-directory-must-exist) #'cape-file)
    411     (pcase-let* ((default-directory (pcase cape-file-directory
    412                                       ('nil default-directory)
    413                                       ((pred stringp) cape-file-directory)
    414                                       (_ (funcall cape-file-directory))))
    415                  (prefix (and cape-file-prefix
    416                               (looking-back
    417                                (concat
    418                                 (regexp-opt (ensure-list cape-file-prefix) t)
    419                                 "[^ \n\t]*")
    420                                (pos-bol))
    421                               (match-end 1)))
    422                  (`(,beg . ,end) (if prefix
    423                                      (cons prefix (point))
    424                                    (cape--bounds 'filename)))
    425                  (non-essential t)
    426                  (file (buffer-substring-no-properties beg end)))
    427       (when (or prefix
    428                 (not cape-file-directory-must-exist)
    429                 (and (string-search "/" file)
    430                      (file-exists-p (file-name-directory file))))
    431         `(,beg ,end
    432           ,(cape--nonessential-table
    433             (if (or (derived-mode-p 'comint-mode) (derived-mode-p 'eshell-mode))
    434                 (completion-table-with-quoting
    435                  #'read-file-name-internal
    436                  comint-unquote-function
    437                  comint-requote-function)
    438               #'read-file-name-internal))
    439           ,@(when (or prefix (string-match-p "./" file))
    440               '(:company-prefix-length t))
    441           ,@cape--file-properties)))))
    442 
    443 ;;;;; cape-elisp-symbol
    444 
    445 (defvar cape--symbol-properties
    446   (append
    447    (list :annotation-function #'cape--symbol-annotation
    448          :exit-function #'cape--symbol-exit
    449          :predicate #'cape--symbol-predicate
    450          :exclusive 'no)
    451    (when (eval-when-compile (>= emacs-major-version 28))
    452      (autoload 'elisp--company-kind "elisp-mode")
    453      (autoload 'elisp--company-doc-buffer "elisp-mode")
    454      (autoload 'elisp--company-doc-string "elisp-mode")
    455      (autoload 'elisp--company-location "elisp-mode")
    456      (list :company-kind 'elisp--company-kind
    457            :company-doc-buffer 'elisp--company-doc-buffer
    458            :company-docsig 'elisp--company-doc-string
    459            :company-location 'elisp--company-location)))
    460   "Completion extra properties for `cape-elisp-symbol'.")
    461 
    462 (defun cape--symbol-predicate (sym)
    463   "Return t if SYM is bound, fbound or propertized."
    464   (or (fboundp sym) (boundp sym) (symbol-plist sym)))
    465 
    466 (defun cape--symbol-exit (name status)
    467   "Wrap symbol NAME with `cape-elisp-symbol-wrapper' buffers.
    468 STATUS is the exit status."
    469   (when-let (((not (eq status 'exact)))
    470              (c (cl-loop for (m . c) in cape-elisp-symbol-wrapper
    471                          if (derived-mode-p m) return c)))
    472     (save-excursion
    473       (backward-char (length name))
    474       (insert (car c)))
    475     (insert (cadr c))))
    476 
    477 (defun cape--symbol-annotation (sym)
    478   "Return kind of SYM."
    479   (setq sym (intern-soft sym))
    480   (cond
    481    ((special-form-p sym) " Special")
    482    ((macrop sym) " Macro")
    483    ((commandp sym) " Command")
    484    ((fboundp sym) " Function")
    485    ((custom-variable-p sym) " Custom")
    486    ((boundp sym) " Variable")
    487    ((featurep sym) " Feature")
    488    ((facep sym) " Face")
    489    (t " Symbol")))
    490 
    491 ;;;###autoload
    492 (defun cape-elisp-symbol (&optional interactive)
    493   "Complete Elisp symbol at point.
    494 If INTERACTIVE is nil the function acts like a Capf."
    495   (interactive (list t))
    496   (if interactive
    497       ;; No cycling since it breaks the :exit-function.
    498       (let (completion-cycle-threshold)
    499         (cape-interactive #'cape-elisp-symbol))
    500     (pcase-let ((`(,beg . ,end) (cape--bounds 'symbol)))
    501       (when (eq (char-after beg) ?')
    502         (setq beg (1+ beg) end (max beg end)))
    503       `(,beg ,end
    504         ,(cape--properties-table obarray :category 'symbol)
    505         ,@cape--symbol-properties))))
    506 
    507 ;;;;; cape-elisp-block
    508 
    509 (declare-function org-element-context "org-element")
    510 (declare-function markdown-code-block-lang "ext:markdown-mode")
    511 
    512 (defun cape--inside-block-p (&rest langs)
    513   "Return non-nil if inside LANGS code block."
    514   (when-let ((face (get-text-property (point) 'face))
    515              (lang (or (and (if (listp face)
    516                                 (memq 'org-block face)
    517                               (eq 'org-block face))
    518                             (plist-get (cadr (org-element-context)) :language))
    519                        (and (if (listp face)
    520                                 (memq 'markdown-code-face face)
    521                               (eq 'markdown-code-face face))
    522                             (save-excursion
    523                               (markdown-code-block-lang))))))
    524     (member lang langs)))
    525 
    526 ;;;###autoload
    527 (defun cape-elisp-block (&optional interactive)
    528   "Complete Elisp in Org or Markdown code block.
    529 This Capf is particularly useful for literate Emacs configurations.
    530 If INTERACTIVE is nil the function acts like a Capf."
    531   (interactive (list t))
    532   (cond
    533    (interactive
    534     ;; No code block check. Always complete Elisp when command was
    535     ;; explicitly invoked interactively.
    536     (cape-interactive #'elisp-completion-at-point))
    537    ((cape--inside-block-p "elisp" "emacs-lisp")
    538     (elisp-completion-at-point))))
    539 
    540 ;;;;; cape-dabbrev
    541 
    542 (defvar cape--dabbrev-properties
    543   (list :annotation-function (lambda (_) " Dabbrev")
    544         :company-kind (lambda (_) 'text)
    545         :exclusive 'no)
    546   "Completion extra properties for `cape-dabbrev'.")
    547 
    548 (defvar dabbrev-case-replace)
    549 (defvar dabbrev-case-fold-search)
    550 (defvar dabbrev-abbrev-char-regexp)
    551 (defvar dabbrev-abbrev-skip-leading-regexp)
    552 (declare-function dabbrev--find-all-expansions "dabbrev")
    553 (declare-function dabbrev--reset-global-variables "dabbrev")
    554 
    555 (defun cape--dabbrev-list (input)
    556   "Find all Dabbrev expansions for INPUT."
    557   (cape--silent
    558     (dlet ((dabbrev-check-other-buffers
    559             (and cape-dabbrev-check-other-buffers
    560                  (not (functionp cape-dabbrev-check-other-buffers))))
    561            (dabbrev-check-all-buffers
    562             (eq cape-dabbrev-check-other-buffers t))
    563            (dabbrev-search-these-buffers-only
    564             (and (functionp cape-dabbrev-check-other-buffers)
    565                  (funcall cape-dabbrev-check-other-buffers))))
    566       (dabbrev--reset-global-variables)
    567       (cons
    568        (apply-partially #'string-prefix-p input)
    569        (cl-loop with min-len = (+ cape-dabbrev-min-length (length input))
    570                 with ic = (cape--case-fold-p dabbrev-case-fold-search)
    571                 for w in (dabbrev--find-all-expansions input ic)
    572                 if (>= (length w) min-len) collect
    573                 (cape--case-replace (and ic dabbrev-case-replace) input w))))))
    574 
    575 (defun cape--dabbrev-bounds ()
    576   "Return bounds of abbreviation."
    577   (unless (boundp 'dabbrev-abbrev-char-regexp)
    578     (require 'dabbrev))
    579   (let ((re (or dabbrev-abbrev-char-regexp "\\sw\\|\\s_"))
    580         (limit (minibuffer-prompt-end)))
    581     (when (or (looking-at re)
    582               (and (> (point) limit)
    583                    (save-excursion (forward-char -1) (looking-at re))))
    584       (cons (save-excursion
    585               (while (and (> (point) limit)
    586                           (save-excursion (forward-char -1) (looking-at re)))
    587                 (forward-char -1))
    588               (when dabbrev-abbrev-skip-leading-regexp
    589                 (while (looking-at dabbrev-abbrev-skip-leading-regexp)
    590                   (forward-char 1)))
    591               (point))
    592             (save-excursion
    593               (while (looking-at re)
    594                 (forward-char 1))
    595               (point))))))
    596 
    597 ;;;###autoload
    598 (defun cape-dabbrev (&optional interactive)
    599   "Complete with Dabbrev at point.
    600 
    601 If INTERACTIVE is nil the function acts like a Capf.  In case you
    602 observe a performance issue with auto-completion and `cape-dabbrev'
    603 it is strongly recommended to disable scanning in other buffers.
    604 See the user options `cape-dabbrev-min-length' and
    605 `cape-dabbrev-check-other-buffers'."
    606   (interactive (list t))
    607   (if interactive
    608       (cape-interactive '((cape-dabbrev-min-length 0)) #'cape-dabbrev)
    609     (when-let ((bounds (cape--dabbrev-bounds)))
    610       `(,(car bounds) ,(cdr bounds)
    611         ,(cape--properties-table
    612           (completion-table-case-fold
    613            (cape--dynamic-table (car bounds) (cdr bounds) #'cape--dabbrev-list)
    614            (not (cape--case-fold-p dabbrev-case-fold-search)))
    615           :category 'cape-dabbrev)
    616         ,@cape--dabbrev-properties))))
    617 
    618 ;;;;; cape-dict
    619 
    620 (defvar cape--dict-properties
    621   (list :annotation-function (lambda (_) " Dict")
    622         :company-kind (lambda (_) 'text)
    623         :exclusive 'no)
    624   "Completion extra properties for `cape-dict'.")
    625 
    626 (defun cape--dict-list (input)
    627   "Return all words from `cape-dict-file' matching INPUT."
    628   (unless (equal input "")
    629      (let* ((inhibit-message t)
    630             (message-log-max nil)
    631             (default-directory
    632              (if (and (not (file-remote-p default-directory))
    633                       (file-directory-p default-directory))
    634                  default-directory
    635                user-emacs-directory))
    636             (files (mapcar #'expand-file-name
    637                            (ensure-list
    638                             (if (functionp cape-dict-file)
    639                                 (funcall cape-dict-file)
    640                               cape-dict-file))))
    641             (words
    642              (apply #'process-lines-ignore-status
    643                     "grep"
    644                     (concat "-Fh"
    645                             (and (cape--case-fold-p cape-dict-case-fold) "i")
    646                             (and cape-dict-limit (format "m%d" cape-dict-limit)))
    647                     input files)))
    648        (cons
    649         (apply-partially
    650           (if (and cape-dict-limit (length= words cape-dict-limit))
    651              #'equal #'string-search)
    652          input)
    653         (cape--case-replace-list cape-dict-case-replace input words)))))
    654 
    655 ;;;###autoload
    656 (defun cape-dict (&optional interactive)
    657   "Complete word from dictionary at point.
    658 This completion function works best if the dictionary is sorted
    659 by frequency.  See the custom option `cape-dict-file'.  If
    660 INTERACTIVE is nil the function acts like a Capf."
    661   (interactive (list t))
    662   (if interactive
    663       (cape-interactive #'cape-dict)
    664     (pcase-let ((`(,beg . ,end) (cape--bounds 'word)))
    665       `(,beg ,end
    666         ,(cape--properties-table
    667           (completion-table-case-fold
    668            (cape--dynamic-table beg end #'cape--dict-list)
    669            (not (cape--case-fold-p cape-dict-case-fold)))
    670           :sort nil ;; Presorted word list (by frequency)
    671           :category 'cape-dict)
    672         ,@cape--dict-properties))))
    673 
    674 ;;;;; cape-abbrev
    675 
    676 (defun cape--abbrev-tables ()
    677   "Return list of all active abbrev tables, including parents."
    678   ;; Emacs 28: See abbrev--suggest-get-active-tables-including-parents.
    679   (let ((tables (abbrev--active-tables)))
    680     (append tables (cl-loop for table in tables
    681                             append (abbrev-table-get table :parents)))))
    682 
    683 (defun cape--abbrev-list ()
    684   "Abbreviation list."
    685   (delete "" (cl-loop for table in (cape--abbrev-tables)
    686                       nconc (all-completions "" table))))
    687 
    688 (defun cape--abbrev-annotation (abbrev)
    689   "Annotate ABBREV with expansion."
    690   (concat " "
    691           (truncate-string-to-width
    692            (format
    693             "%s"
    694             (symbol-value
    695              (cl-loop for table in (cape--abbrev-tables)
    696                       thereis (abbrev--symbol abbrev table))))
    697            30 0 nil t)))
    698 
    699 (defun cape--abbrev-exit (_str status)
    700   "Expand expansion if STATUS is not exact."
    701   (unless (eq status 'exact)
    702     (expand-abbrev)))
    703 
    704 (defvar cape--abbrev-properties
    705   (list :annotation-function #'cape--abbrev-annotation
    706         :exit-function #'cape--abbrev-exit
    707         :company-kind (lambda (_) 'snippet)
    708         :exclusive 'no)
    709   "Completion extra properties for `cape-abbrev'.")
    710 
    711 ;;;###autoload
    712 (defun cape-abbrev (&optional interactive)
    713   "Complete abbreviation at point.
    714 If INTERACTIVE is nil the function acts like a Capf."
    715   (interactive (list t))
    716   (if interactive
    717       ;; No cycling since it breaks the :exit-function.
    718       (let (completion-cycle-threshold)
    719         (cape-interactive #'cape-abbrev))
    720     (when-let (abbrevs (cape--abbrev-list))
    721       (let ((bounds (cape--bounds 'symbol)))
    722         `(,(car bounds) ,(cdr bounds)
    723           ,(cape--properties-table abbrevs :category 'cape-abbrev)
    724           ,@cape--abbrev-properties)))))
    725 
    726 ;;;;; cape-line
    727 
    728 (defvar cape--line-properties nil
    729   "Completion extra properties for `cape-line'.")
    730 
    731 (defun cape--buffers-major-mode ()
    732   "Return buffers with same major mode as current buffer."
    733   (cl-loop for buf in (buffer-list)
    734            if (eq major-mode (buffer-local-value 'major-mode buf))
    735            collect buf))
    736 
    737 (defun cape--line-list ()
    738   "Return all lines from buffer."
    739   (let ((ht (make-hash-table :test #'equal))
    740         (curr-buf (current-buffer))
    741         (buffers (funcall cape-line-buffer-function))
    742         lines)
    743     (dolist (buf (ensure-list buffers))
    744       (with-current-buffer buf
    745         (let ((beg (point-min))
    746               (max (point-max))
    747               (pt (if (eq curr-buf buf) (point) -1))
    748               end)
    749           (save-excursion
    750             (while (< beg max)
    751               (goto-char beg)
    752               (setq end (pos-eol))
    753               (unless (<= beg pt end)
    754                 (let ((line (buffer-substring-no-properties beg end)))
    755                   (unless (or (string-blank-p line) (gethash line ht))
    756                     (puthash line t ht)
    757                     (push line lines))))
    758               (setq beg (1+ end)))))))
    759     (nreverse lines)))
    760 
    761 ;;;###autoload
    762 (defun cape-line (&optional interactive)
    763   "Complete current line from other lines.
    764 The buffers returned by `cape-line-buffer-function' are scanned for lines.
    765 If INTERACTIVE is nil the function acts like a Capf."
    766   (interactive (list t))
    767   (if interactive
    768       (cape-interactive #'cape-line)
    769     `(,(pos-bol) ,(point)
    770       ,(cape--properties-table (cape--line-list) :sort nil)
    771       ,@cape--line-properties)))
    772 
    773 ;;;; Capf combinators
    774 
    775 (defun cape--company-call (&rest app)
    776   "Apply APP and handle future return values."
    777   ;; Backends are non-interruptible. Disable interrupts!
    778   (let ((toi throw-on-input)
    779         (throw-on-input nil))
    780     (pcase (apply app)
    781       ;; Handle async future return values.
    782       (`(:async . ,fetch)
    783        (let ((res 'cape--waiting))
    784          (if toi
    785              (unwind-protect
    786                  (progn
    787                    (funcall fetch
    788                             (lambda (arg)
    789                               (when (eq res 'cape--waiting)
    790                                 (push 'cape--done unread-command-events)
    791                                 (setq res arg))))
    792                    (when (eq res 'cape--waiting)
    793                      (let ((ev (let ((input-method-function nil)
    794                                      (echo-keystrokes 0))
    795                                  (read-event nil t))))
    796                        (unless (eq ev 'cape--done)
    797                          (push (cons t ev) unread-command-events)
    798                          (setq res 'cape--cancelled)
    799                          (throw toi t)))))
    800                (setq unread-command-events
    801                      (delq 'cape--done unread-command-events)))
    802            (funcall fetch (lambda (arg) (setq res arg)))
    803            ;; Force synchronization, not interruptible! We use polling
    804            ;; here and ignore pending input since we don't use
    805            ;; `sit-for'. This is the same method used by Company itself.
    806            (while (eq res 'cape--waiting)
    807              (sleep-for 0.01)))
    808          res))
    809       ;; Plain old synchronous return value.
    810       (res res))))
    811 
    812 (defvar-local cape--company-init nil)
    813 
    814 ;;;###autoload
    815 (defun cape-company-to-capf (backend &optional valid)
    816   "Convert Company BACKEND function to Capf.
    817 VALID is a function taking the old and new input string.  It
    818 should return nil if the cached candidates became invalid.  The
    819 default value for VALID is `string-prefix-p' such that the
    820 candidates are only fetched again if the input prefix
    821 changed.  The function `cape-company-to-capf' is experimental."
    822   (lambda ()
    823     (when (and (symbolp backend) (not (fboundp backend)))
    824       (ignore-errors (require backend nil t)))
    825     (when (and (symbolp backend) (not (alist-get backend cape--company-init)))
    826       (funcall backend 'init)
    827       (put backend 'company-init t)
    828       (setf (alist-get backend cape--company-init) t))
    829     (when-let ((prefix (cape--company-call backend 'prefix))
    830                (initial-input (if (stringp prefix) prefix (car-safe prefix))))
    831       (let* ((end (point)) (beg (- end (length initial-input)))
    832              (valid (if (cape--company-call backend 'no-cache initial-input)
    833                         #'equal (or valid #'string-prefix-p)))
    834              restore-props)
    835         (list beg end
    836               (funcall
    837                (if (cape--company-call backend 'ignore-case)
    838                    #'completion-table-case-fold
    839                  #'identity)
    840                (cape--properties-table
    841                 (cape--dynamic-table
    842                  beg end
    843                  (lambda (input)
    844                    (let ((cands (cape--company-call backend 'candidates input)))
    845                      ;; The candidate string including text properties should be
    846                      ;; restored in the :exit-function, if the UI does not
    847                      ;; guarantee this itself.  Restoration is not necessary for
    848                      ;; Corfu since the introduction of `corfu--exit-function'.
    849                      (unless (and (bound-and-true-p corfu-mode) (fboundp 'corfu--exit-function))
    850                        (setq restore-props cands))
    851                      (cons (apply-partially valid input) cands))))
    852                 :category backend
    853                 :sort (not (cape--company-call backend 'sorted))))
    854               :exclusive 'no
    855               :company-prefix-length (cdr-safe prefix)
    856               :company-doc-buffer (lambda (x) (cape--company-call backend 'doc-buffer x))
    857               :company-location (lambda (x) (cape--company-call backend 'location x))
    858               :company-docsig (lambda (x) (cape--company-call backend 'meta x))
    859               :company-deprecated (lambda (x) (cape--company-call backend 'deprecated x))
    860               :company-kind (lambda (x) (cape--company-call backend 'kind x))
    861               :annotation-function (lambda (x)
    862                                      (when-let (ann (cape--company-call backend 'annotation x))
    863                                        (concat " " (string-trim ann))))
    864               :exit-function (lambda (x _status)
    865                                ;; Restore the candidate string including
    866                                ;; properties if restore-props is non-nil.  See
    867                                ;; the comment above.
    868                                (setq x (or (car (member x restore-props)) x))
    869                                (cape--company-call backend 'post-completion x)))))))
    870 
    871 ;;;###autoload
    872 (defun cape-interactive (&rest capfs)
    873   "Complete interactively with the given CAPFS."
    874   (let* ((ctx (and (consp (car capfs)) (car capfs)))
    875          (capfs (if ctx (cdr capfs) capfs))
    876          (completion-at-point-functions
    877           (if ctx
    878               (mapcar (lambda (f) `(lambda () (let ,ctx (funcall ',f)))) capfs)
    879             capfs)))
    880     (unless (completion-at-point)
    881       (user-error "%s: No completions"
    882                   (mapconcat (lambda (fun)
    883                                (if (symbolp fun)
    884                                    (symbol-name fun)
    885                                  "anonymous-capf"))
    886                              capfs ", ")))))
    887 
    888 ;;;###autoload
    889 (defun cape-capf-interactive (capf)
    890   "Create interactive completion function from CAPF."
    891   (lambda (&optional interactive)
    892     (interactive (list t))
    893     (if interactive (cape-interactive capf) (funcall capf))))
    894 
    895 ;;;###autoload
    896 (defun cape-wrap-super (&rest capfs)
    897   "Call CAPFS and return merged completion result.
    898 The CAPFS list can contain the keyword `:with' to mark the Capfs
    899 afterwards as auxiliary One of the non-auxiliary Capfs before
    900 `:with' must return non-nil for the super Capf to set in and
    901 return a non-nil result.  Such behavior is useful when listing
    902 multiple super Capfs in the `completion-at-point-functions':
    903 
    904   (setq completion-at-point-functions
    905         (list (cape-capf-super \\='eglot-completion-at-point
    906                                :with \\='tempel-complete)
    907               (cape-capf-super \\='cape-dabbrev
    908                                :with \\='tempel-complete)))
    909 
    910 The functions `cape-wrap-super' and `cape-capf-super' are
    911 experimental."
    912   (when-let ((results (cl-loop for capf in capfs until (eq capf :with)
    913                                for res = (funcall capf)
    914                                if res collect (cons t res))))
    915     (pcase-let* ((results (nconc results
    916                                  (cl-loop for capf in (cdr (memq :with capfs))
    917                                           for res = (funcall capf)
    918                                           if res collect (cons nil res))))
    919                  (`((,_main ,beg ,end . ,_)) results)
    920                  (cand-ht nil)
    921                  (tables nil)
    922                  (exclusive nil)
    923                  (prefix-len nil)
    924                  (cand-functions
    925                   '(:company-docsig :company-location :company-kind
    926                     :company-doc-buffer :company-deprecated
    927                     :annotation-function :exit-function)))
    928       (cl-loop for (main beg2 end2 table . plist) in results do
    929                ;; TODO `cape-capf-super' currently cannot merge Capfs which
    930                ;; trigger at different beginning positions.  In order to support
    931                ;; this, take the smallest BEG value and then normalize all
    932                ;; candidates by prefixing them such that they all start at the
    933                ;; smallest BEG position.
    934                (when (= beg beg2)
    935                  (push (list main (plist-get plist :predicate) table
    936                              ;; Plist attached to the candidates
    937                              (mapcan (lambda (f)
    938                                        (when-let ((v (plist-get plist f)))
    939                                          (list f v)))
    940                                      cand-functions))
    941                        tables)
    942                  ;; The resulting merged Capf is exclusive if one of the main
    943                  ;; Capfs is exclusive.
    944                  (when (and main (not (eq (plist-get plist :exclusive) 'no)))
    945                    (setq exclusive t))
    946                  (setq end (max end end2))
    947                  (let ((plen (plist-get plist :company-prefix-length)))
    948                    (cond
    949                     ((eq plen t)
    950                      (setq prefix-len t))
    951                     ((and (not prefix-len) (integerp plen))
    952                      (setq prefix-len plen))
    953                     ((and (integerp prefix-len) (integerp plen))
    954                      (setq prefix-len (max prefix-len plen)))))))
    955       (setq tables (nreverse tables))
    956       `(,beg ,end
    957         ,(lambda (str pred action)
    958            (pcase action
    959              (`(boundaries . ,_) nil)
    960              ('metadata
    961               '(metadata (category . cape-super)
    962                          (display-sort-function . identity)
    963                          (cycle-sort-function . identity)))
    964              ('t ;; all-completions
    965               (let ((ht (make-hash-table :test #'equal))
    966                     (candidates nil))
    967                 (cl-loop for (main table-pred table cand-plist) in tables do
    968                          (let* ((pr (if (and table-pred pred)
    969                                         (lambda (x) (and (funcall table-pred x) (funcall pred x)))
    970                                       (or table-pred pred)))
    971                                 (md (completion-metadata "" table pr))
    972                                 (sort (or (completion-metadata-get md 'display-sort-function)
    973                                           #'identity))
    974                                 ;; Always compute candidates of the main Capf
    975                                 ;; tables, which come first in the tables
    976                                 ;; list. For the :with Capfs only compute
    977                                 ;; candidates if we've already determined that
    978                                 ;; main candidates are available.
    979                                 (cands (when (or main (or exclusive cand-ht candidates))
    980                                          (funcall sort (all-completions str table pr)))))
    981                            ;; Handle duplicates with a hash table.
    982                            (cl-loop
    983                             for cand in-ref cands
    984                             for dup = (gethash cand ht t) do
    985                             (cond
    986                              ((eq dup t)
    987                               ;; Candidate does not yet exist.
    988                               (puthash cand cand-plist ht))
    989                              ((not (equal dup cand-plist))
    990                               ;; Duplicate candidate. Candidate plist is
    991                               ;; different, therefore disambiguate the
    992                               ;; candidates.
    993                               (setf cand (propertize cand 'cape-capf-super
    994                                                      (cons cand cand-plist))))))
    995                            (when cands (push cands candidates))))
    996                 (when (or cand-ht candidates)
    997                   (setq candidates (apply #'nconc (nreverse candidates))
    998                         cand-ht ht)
    999                   candidates)))
   1000              (_ ;; try-completion and test-completion
   1001               (cl-loop for (_main table-pred table _cand-plist) in tables thereis
   1002                        (complete-with-action
   1003                         action table str
   1004                         (if (and table-pred pred)
   1005                             (lambda (x) (and (funcall table-pred x) (funcall pred x)))
   1006                           (or table-pred pred)))))))
   1007         :company-prefix-length ,prefix-len
   1008         ,@(and (not exclusive) '(:exclusive no))
   1009         ,@(mapcan
   1010            (lambda (prop)
   1011              (list prop (lambda (cand &rest args)
   1012                           (let ((ref (get-text-property 0 'cape-capf-super cand)))
   1013                             (when-let ((fun (plist-get
   1014                                              (or (cdr ref)
   1015                                                  (and cand-ht (gethash cand cand-ht)))
   1016                                              prop)))
   1017                               (apply fun (or (car ref) cand) args))))))
   1018            cand-functions)))))
   1019 
   1020 ;;;###autoload
   1021 (defun cape-wrap-debug (capf &optional name)
   1022   "Call CAPF and return a completion table which prints trace messages.
   1023 If CAPF is an anonymous lambda, pass the Capf NAME explicitly for
   1024 meaningful debugging output."
   1025   (unless name
   1026     (setq name (if (symbolp capf) capf "capf")))
   1027   (setq name (format "%s@%s" name (cl-incf cape--debug-id)))
   1028   (pcase (funcall capf)
   1029     (`(,beg ,end ,table . ,plist)
   1030      (let* ((limit (1+ cape--debug-length))
   1031             (pred (plist-get plist :predicate))
   1032             (cands
   1033              ;; Reset regexps for `all-completions'
   1034              (let (completion-ignore-case completion-regexp-list)
   1035                (all-completions
   1036                 "" table
   1037                 (lambda (&rest args)
   1038                   (and (or (not pred) (apply pred args)) (>= (cl-decf limit) 0))))))
   1039             (plist-str "")
   1040             (plist-elt plist))
   1041        (while (cdr plist-elt)
   1042          (setq plist-str (format "%s %s=%s" plist-str
   1043                                  (substring (symbol-name (car plist-elt)) 1)
   1044                                  (cape--debug-print (cadr plist-elt)))
   1045                plist-elt (cddr plist-elt)))
   1046        (cape--debug-message
   1047         "%s => input=%s:%s:%S table=%s%s"
   1048         name (+ beg 0) (+ end 0) (buffer-substring-no-properties beg end)
   1049         (cape--debug-print cands)
   1050         plist-str))
   1051      `(,beg ,end ,(cape--debug-table
   1052                    table name (copy-marker beg) (copy-marker end t))
   1053        ,@(when-let ((exit (plist-get plist :exit-function)))
   1054            (list :exit-function
   1055                  (lambda (cand status)
   1056                    (cape--debug-message "%s:exit(candidate=%S status=%s)"
   1057                                         name cand status)
   1058                    (funcall exit cand status))))
   1059        . ,plist))
   1060     (result
   1061      (cape--debug-message "%s() => %s (No completion)"
   1062                           name (cape--debug-print result)))))
   1063 
   1064 ;;;###autoload
   1065 (defun cape-wrap-buster (capf &optional valid)
   1066   "Call CAPF and return a completion table with cache busting.
   1067 This function can be used as an advice around an existing Capf.
   1068 The cache is busted when the input changes.  The argument VALID
   1069 can be a function taking the old and new input string.  It should
   1070 return nil if the new input requires that the completion table is
   1071 refreshed.  The default value for VALID is `equal', such that the
   1072 completion table is refreshed on every input change."
   1073   (setq valid (or valid #'equal))
   1074   (pcase (funcall capf)
   1075     (`(,beg ,end ,table . ,plist)
   1076      (setq plist `(:cape--buster t . ,plist))
   1077      `(,beg ,end
   1078        ,(let* ((beg (copy-marker beg))
   1079                (end (copy-marker end t))
   1080                (input (buffer-substring-no-properties beg end)))
   1081           (lambda (str pred action)
   1082             (let ((new-input (buffer-substring-no-properties beg end)))
   1083               (unless (or (not (eq action t))
   1084                           (cape--separator-p new-input)
   1085                           (funcall valid input new-input))
   1086                 (pcase
   1087                     ;; Reset in case `all-completions' is used inside CAPF
   1088                     (let (completion-ignore-case completion-regexp-list)
   1089                       (funcall capf))
   1090                   ((and `(,new-beg ,new-end ,new-table . ,new-plist)
   1091                         (guard (and (= beg new-beg) (= end new-end))))
   1092                    (let (throw-on-input) ;; No interrupt during state update
   1093                      (setf table new-table
   1094                            input new-input
   1095                            (cddr plist) new-plist))))))
   1096             (complete-with-action action table str pred)))
   1097        ,@plist))))
   1098 
   1099 ;;;###autoload
   1100 (defun cape-wrap-passthrough (capf)
   1101   "Call CAPF and make sure that no completion style filtering takes place."
   1102   (pcase (funcall capf)
   1103     (`(,beg ,end ,table . ,plist)
   1104      `(,beg ,end ,(cape--passthrough-table table) ,@plist))))
   1105 
   1106 ;;;###autoload
   1107 (defun cape-wrap-properties (capf &rest properties)
   1108   "Call CAPF and add additional completion PROPERTIES.
   1109 Completion properties include for example :exclusive, :annotation-function and
   1110 the various :company-* extensions.  Furthermore a boolean :sort flag and a
   1111 completion :category symbol can be specified."
   1112   (pcase (funcall capf)
   1113     (`(,beg ,end ,table . ,plist)
   1114      `(,beg ,end
   1115             ,(apply #'cape--properties-table table properties)
   1116             ,@properties ,@plist))))
   1117 
   1118 ;;;###autoload
   1119 (defun cape-wrap-nonexclusive (capf)
   1120   "Call CAPF and ensure that it is marked as non-exclusive.
   1121 This function can be used as an advice around an existing Capf."
   1122   (cape-wrap-properties capf :exclusive 'no))
   1123 
   1124 ;;;###autoload
   1125 (defun cape-wrap-predicate (capf predicate)
   1126   "Call CAPF and add an additional candidate PREDICATE.
   1127 The PREDICATE is passed the candidate symbol or string."
   1128   (pcase (funcall capf)
   1129     (`(,beg ,end ,table . ,plist)
   1130      `(,beg ,end ,table
   1131             :predicate
   1132             ,(if-let (pred (plist-get plist :predicate))
   1133                  ;; First argument is key, second is value for hash tables.
   1134                  ;; The first argument can be a cons cell for alists. Then
   1135                  ;; the candidate itself is either a string or a symbol. We
   1136                  ;; normalize the calling convention here such that PREDICATE
   1137                  ;; always receives a string or a symbol.
   1138                  (lambda (&rest args)
   1139                    (when (apply pred args)
   1140                      (setq args (car args))
   1141                      (funcall predicate (if (consp args) (car args) args))))
   1142                (lambda (key &optional _val)
   1143                  (funcall predicate (if (consp key) (car key) key))))
   1144             ,@plist))))
   1145 
   1146 ;;;###autoload
   1147 (defun cape-wrap-silent (capf)
   1148   "Call CAPF and silence it (no messages, no errors).
   1149 This function can be used as an advice around an existing Capf."
   1150   (pcase (cape--silent (funcall capf))
   1151     (`(,beg ,end ,table . ,plist)
   1152      `(,beg ,end ,(cape--silent-table table) ,@plist))))
   1153 
   1154 ;;;###autoload
   1155 (defun cape-wrap-case-fold (capf &optional dont-fold)
   1156   "Call CAPF and return a case-insensitive completion table.
   1157 If DONT-FOLD is non-nil return a case sensitive table instead.
   1158 This function can be used as an advice around an existing Capf."
   1159   (pcase (funcall capf)
   1160     (`(,beg ,end ,table . ,plist)
   1161      `(,beg ,end ,(completion-table-case-fold table dont-fold) ,@plist))))
   1162 
   1163 ;;;###autoload
   1164 (defun cape-wrap-noninterruptible (capf)
   1165   "Call CAPF and return a non-interruptible completion table.
   1166 This function can be used as an advice around an existing Capf."
   1167   (pcase (let (throw-on-input) (funcall capf))
   1168     (`(,beg ,end ,table . ,plist)
   1169      `(,beg ,end ,(cape--noninterruptible-table table) ,@plist))))
   1170 
   1171 ;;;###autoload
   1172 (defun cape-wrap-prefix-length (capf length)
   1173   "Call CAPF and ensure that prefix length is greater or equal than LENGTH.
   1174 If the prefix is long enough, enforce auto completion."
   1175   (pcase (funcall capf)
   1176     (`(,beg ,end ,table . ,plist)
   1177      (when (>= (- end beg) length)
   1178        `(,beg ,end ,table
   1179          :company-prefix-length t
   1180          ,@plist)))))
   1181 
   1182 ;;;###autoload
   1183 (defun cape-wrap-inside-faces (capf &rest faces)
   1184   "Call CAPF only if inside FACES.
   1185 This function can be used as an advice around an existing Capf."
   1186   (when-let (((> (point) (point-min)))
   1187              (fs (get-text-property (1- (point)) 'face))
   1188              ((if (listp fs)
   1189                   (cl-loop for f in fs thereis (memq f faces))
   1190                 (memq fs faces))))
   1191     (funcall capf)))
   1192 
   1193 ;;;###autoload
   1194 (defun cape-wrap-inside-code (capf)
   1195   "Call CAPF only if inside code, not inside a comment or string.
   1196 This function can be used as an advice around an existing Capf."
   1197   (let ((s (syntax-ppss)))
   1198     (and (not (nth 3 s)) (not (nth 4 s)) (funcall capf))))
   1199 
   1200 ;;;###autoload
   1201 (defun cape-wrap-inside-comment (capf)
   1202   "Call CAPF only if inside comment.
   1203 This function can be used as an advice around an existing Capf."
   1204   (and (nth 4 (syntax-ppss)) (funcall capf)))
   1205 
   1206 ;;;###autoload
   1207 (defun cape-wrap-inside-string (capf)
   1208   "Call CAPF only if inside string.
   1209 This function can be used as an advice around an existing Capf."
   1210   (and (nth 3 (syntax-ppss)) (funcall capf)))
   1211 
   1212 ;;;###autoload
   1213 (defun cape-wrap-purify (capf)
   1214   "Call CAPF and ensure that it does not illegally modify the buffer.
   1215 This function can be used as an advice around an existing
   1216 Capf.  It has been introduced mainly to fix the broken
   1217 `pcomplete-completions-at-point' function in Emacs versions < 29."
   1218   ;; bug#50470: Fix Capfs which illegally modify the buffer or which illegally
   1219   ;; call `completion-in-region'.  The workaround here was proposed by
   1220   ;; @jakanakaevangeli and is used in his capf-autosuggest package.  In Emacs 29
   1221   ;; the purity bug of Pcomplete has been fixed, such that make
   1222   ;; `cape-wrap-purify' is not necessary anymore.
   1223   (catch 'cape--illegal-completion-in-region
   1224     (condition-case nil
   1225         (let ((buffer-read-only t)
   1226               (inhibit-read-only nil)
   1227               (completion-in-region-function
   1228                (lambda (beg end coll pred)
   1229                  (throw 'cape--illegal-completion-in-region
   1230                         (list beg end coll :predicate pred)))))
   1231           (funcall capf))
   1232       (buffer-read-only nil))))
   1233 
   1234 ;;;###autoload
   1235 (defun cape-wrap-accept-all (capf)
   1236   "Call CAPF and return a completion table which accepts every input.
   1237 This function can be used as an advice around an existing Capf."
   1238   (pcase (funcall capf)
   1239     (`(,beg ,end ,table . ,plist)
   1240      `(,beg ,end ,(cape--accept-all-table table) . ,plist))))
   1241 
   1242 ;;;###autoload (autoload 'cape-capf-accept-all "cape")
   1243 ;;;###autoload (autoload 'cape-capf-buster "cape")
   1244 ;;;###autoload (autoload 'cape-capf-case-fold "cape")
   1245 ;;;###autoload (autoload 'cape-capf-debug "cape")
   1246 ;;;###autoload (autoload 'cape-capf-inside-code "cape")
   1247 ;;;###autoload (autoload 'cape-capf-inside-comment "cape")
   1248 ;;;###autoload (autoload 'cape-capf-inside-faces "cape")
   1249 ;;;###autoload (autoload 'cape-capf-inside-string "cape")
   1250 ;;;###autoload (autoload 'cape-capf-nonexclusive "cape")
   1251 ;;;###autoload (autoload 'cape-capf-noninterruptible "cape")
   1252 ;;;###autoload (autoload 'cape-capf-passthrough "cape")
   1253 ;;;###autoload (autoload 'cape-capf-predicate "cape")
   1254 ;;;###autoload (autoload 'cape-capf-prefix-length "cape")
   1255 ;;;###autoload (autoload 'cape-capf-properties "cape")
   1256 ;;;###autoload (autoload 'cape-capf-purify "cape")
   1257 ;;;###autoload (autoload 'cape-capf-silent "cape")
   1258 ;;;###autoload (autoload 'cape-capf-super "cape")
   1259 
   1260 (dolist (wrapper (list #'cape-wrap-accept-all #'cape-wrap-buster
   1261                        #'cape-wrap-case-fold #'cape-wrap-debug
   1262                        #'cape-wrap-inside-code #'cape-wrap-inside-comment
   1263                        #'cape-wrap-inside-faces #'cape-wrap-inside-string
   1264                        #'cape-wrap-nonexclusive #'cape-wrap-noninterruptible
   1265                        #'cape-wrap-passthrough #'cape-wrap-predicate
   1266                        #'cape-wrap-prefix-length #'cape-wrap-properties
   1267                        #'cape-wrap-purify #'cape-wrap-silent #'cape-wrap-super))
   1268   (let ((name (string-remove-prefix "cape-wrap-" (symbol-name wrapper))))
   1269     (defalias (intern (format "cape-capf-%s" name))
   1270       (lambda (capf &rest args) (lambda () (apply wrapper capf args)))
   1271       (format "Create a %s Capf from CAPF.
   1272 The Capf calls `%s' with CAPF and ARGS as arguments." name wrapper))))
   1273 
   1274 (provide 'cape)
   1275 ;;; cape.el ends here