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