├── .elpaignore
├── .gitignore
├── .github
└── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── config.yml
├── cape-char.el
├── CHANGELOG.org
├── README.org
├── cape-keyword.el
├── LICENSE
└── cape.el
/.elpaignore:
--------------------------------------------------------------------------------
1 | LICENSE
2 | .elpaignore
3 | .github
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *-autoloads.el
2 | *-pkg.el
3 | *.elc
4 | *.info
5 | *.texi
6 | *~
7 | \#*\#
8 | /README-elpa
9 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | title:
3 | name: 🐞 Bug report
4 | about: Report a bug. Do not use this for questions, support or feature requests.
5 | ---
6 | Thank you for reporting a bug.
7 |
8 | Please use the latest stable release of Emacs 30.1 and start with `emacs -Q` or
9 | `package-isolate` in order to only load a minimal set of packages. This way your
10 | Emacs configuration is not loaded.
11 |
12 | Make sure that you install the newest versions of the involved packages. Please
13 | also reinstall and recompile the involved packages, ideally remove all and
14 | reinstall all packages, to exclude compilation issues due to outdated
15 | dependencies.
16 |
17 | Please provide precise information, stack traces and the exact steps to
18 | reproduce the issue. This is important to ensure that your problem can be
19 | reproduced on a different machine.
20 |
21 | If you are not really sure if your issue is a bug, please open a discussion
22 | instead.
23 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/config.yml:
--------------------------------------------------------------------------------
1 | blank_issues_enabled: false
2 | contact_links:
3 | - name: "🙏 Please support my work on Cape and my other Emacs packages"
4 | url: https://github.com/sponsors/minad
5 | about: Thanks! Your support helps dedicating time to project maintenance and development.
6 | - name: "💡 Suggest a feature ➞ Please create a discussion"
7 | url: https://github.com/minad/cape/discussions/categories/ideas
8 | about: Start a new discussion suggesting an improvement or a feature.
9 | - name: "🧑🤝🧑 Ask the community for support"
10 | url: https://www.reddit.com/r/emacs
11 | about: Please be kind and support others.
12 | - name: "🤓 Ask the maintainer for support ➞ Please create a discussion"
13 | url: https://github.com/minad/cape/discussions/categories/q-a
14 | about: Please keep in mind that my bandwidth is limited.
15 | - name: "🔍 Search through old issues or discussions"
16 | url: https://github.com/search?q=repo%3Aminad%2Fcape&type=issues
17 | about: The same question may have been asked before.
18 | # - name: "📝 Cape wiki"
19 | # url: https://github.com/minad/cape/wiki
20 | # about: Additional configuration tips are covered there. Feel free to edit!
21 | - name: "📝 Corfu wiki"
22 | url: https://github.com/minad/corfu/wiki
23 | about: Additional configuration tips are covered there. Feel free to edit!
24 | - name: "📖 Cape manual"
25 | url: https://github.com/minad/cape/blob/main/README.org
26 | about: The manual covers the basic setup and workflow.
27 |
--------------------------------------------------------------------------------
/cape-char.el:
--------------------------------------------------------------------------------
1 | ;;; cape-char.el --- Character completion functions -*- lexical-binding: t -*-
2 |
3 | ;; Copyright (C) 2021-2025 Free Software Foundation, Inc.
4 |
5 | ;; This file is part of GNU Emacs.
6 |
7 | ;; This program is free software: you can redistribute it and/or modify
8 | ;; it under the terms of the GNU General Public License as published by
9 | ;; the Free Software Foundation, either version 3 of the License, or
10 | ;; (at your option) any later version.
11 |
12 | ;; This program is distributed in the hope that it will be useful,
13 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | ;; GNU General Public License for more details.
16 |
17 | ;; You should have received a copy of the GNU General Public License
18 | ;; along with this program. If not, see .
19 |
20 | ;;; Commentary:
21 |
22 | ;; This package provides the `cape-emoji', `cape-tex', `cape-sgml' and
23 | ;; `cape-rfc1345' completion functions.
24 |
25 | ;;; Code:
26 |
27 | (require 'cape)
28 |
29 | (declare-function quail-deactivate "quail")
30 | (declare-function quail-build-decode-map "quail")
31 | (declare-function quail-map "quail")
32 |
33 | (eval-and-compile
34 | (defun cape-char--translation (method prefix)
35 | "Return character translation hash for input method METHOD.
36 | PREFIX are the prefix characters. Names (hash keys) that map to
37 | multiple candidates (hash values) in the quail translation map
38 | are not included. Hash values are either char or strings."
39 | (when-let ((im (assoc method input-method-alist))
40 | ((eq #'quail-use-package (nth 2 im))))
41 | (let ((hash (make-hash-table :test #'equal))
42 | (dm (list 'decode-map)))
43 | (require 'quail)
44 | (apply #'quail-use-package method (nthcdr 5 im))
45 | (quail-build-decode-map (list (quail-map)) "" dm 0)
46 | (pcase-dolist (`(,name . ,val) (cdr dm))
47 | (when (equal method "emoji")
48 | (setq name (replace-regexp-in-string
49 | ": " "-"
50 | (replace-regexp-in-string
51 | "[’“”!()]" ""
52 | (replace-regexp-in-string
53 | "[_ &.]+" "-" name))))
54 | (when (string-match-p "\\`[[:alnum:]-]*\\'" name)
55 | (setq name (format ":%s:" name))))
56 | (when (memq (aref name 0) prefix)
57 | (puthash name (if (vectorp val) (aref val 0) val) hash)))
58 | (quail-deactivate)
59 | hash))))
60 |
61 | (defun cape-char--annotation (hash name)
62 | "Lookup NAME in HASH and return annotation."
63 | (when-let ((char (gethash name hash)))
64 | (format (if (stringp char) " %s " " %c ") char)))
65 |
66 | (defun cape-char--signature (hash name)
67 | "Lookup NAME in HASH and return signature."
68 | (when-let ((val (gethash name hash)))
69 | (concat
70 | (and (stringp val) (concat val " = "))
71 | (mapconcat
72 | (lambda (char)
73 | (format "%c %s (%s)"
74 | char
75 | (get-char-code-property char 'name)
76 | (char-code-property-description
77 | 'general-category
78 | (get-char-code-property char 'general-category))))
79 | (if (stringp val) val (list val))
80 | " + "))))
81 |
82 | (defun cape-char--exit (hash name status)
83 | "Exit function given completion STATUS, looks-up NAME in HASH."
84 | (when-let (((not (eq status 'exact)))
85 | (char (gethash name hash)))
86 | (delete-region (max (point-min) (- (point) (length name))) (point))
87 | (insert char)))
88 |
89 | (defmacro cape-char--define (name method &rest prefix)
90 | "Define character translation Capf.
91 | NAME is the name of the Capf.
92 | METHOD is the input method.
93 | PREFIX are the prefix characters."
94 | (when-let ((capf (intern (format "cape-%s" name)))
95 | (pre-req (intern (format "cape-%s-prefix-required" name)))
96 | (props (intern (format "cape--%s-properties" name)))
97 | (pre-rx (concat (regexp-opt (mapcar #'char-to-string prefix)) "[^ \n\t]*" ))
98 | (hash (intern (format "cape--%s-hash" name)))
99 | (hash-val (cape-char--translation method prefix)))
100 | `(progn
101 | (defvar ,hash ,hash-val)
102 | (defcustom ,pre-req t
103 | ,(format "Initial prefix is required for `%s' to trigger." capf)
104 | :type 'boolean
105 | :group 'cape)
106 | (defvar ,props
107 | (list :annotation-function (apply-partially #'cape-char--annotation ,hash)
108 | :company-docsig (apply-partially #'cape-char--signature ,hash)
109 | :exit-function (apply-partially #'cape-char--exit ,hash)
110 | :company-kind (lambda (_) 'text)
111 | :category ',capf
112 | :exclusive 'no)
113 | ,(format "Completion extra properties for `%s'." capf))
114 | (defun ,capf (&optional interactive)
115 | ,(format "Complete Unicode character at point.
116 | Uses the input format of the %s input method,
117 | see (describe-input-method %S). If INTERACTIVE is nil the
118 | function acts like a Capf." method method)
119 | (interactive (list t))
120 | (if interactive
121 | ;; No cycling since it breaks the :exit-function.
122 | (let (completion-cycle-threshold ,pre-req)
123 | (when (and (memq last-input-event ',prefix)
124 | (not (looking-back ,pre-rx (pos-bol))))
125 | (self-insert-command 1 last-input-event))
126 | (cape-interactive #',capf))
127 | (when-let ((bounds
128 | (cond
129 | ((looking-back ,pre-rx (pos-bol))
130 | (cons (match-beginning 0) (point)))
131 | ((not ,pre-req) (cons (point) (point))))))
132 | (append (list (car bounds) (cdr bounds) ,hash) ,props)))))))
133 |
134 | ;;;###autoload (autoload 'cape-tex "cape-char" nil t)
135 | (cape-char--define tex "TeX" ?\\ ?^ ?_)
136 |
137 | ;;;###autoload (autoload 'cape-sgml "cape-char" nil t)
138 | (cape-char--define sgml "sgml" ?&)
139 |
140 | ;;;###autoload (autoload 'cape-rfc1345 "cape-char" nil t)
141 | (cape-char--define rfc1345 "rfc1345" ?&)
142 |
143 | ;;;###autoload (autoload 'cape-emoji "cape-char" nil t)
144 | (cape-char--define emoji "emoji" ?:)
145 |
146 | (provide 'cape-char)
147 | ;;; cape-char.el ends here
148 |
--------------------------------------------------------------------------------
/CHANGELOG.org:
--------------------------------------------------------------------------------
1 | #+title: cape.el - Changelog
2 | #+author: Daniel Mendler
3 | #+language: en
4 |
5 | * Version 2.4 (2025-12-21)
6 |
7 | - ~cape-file~: Add location metadata for file preview via ~corfu-popupinfo-mode~.
8 |
9 | * Version 2.3 (2025-11-15)
10 |
11 | - Mark ~cape-capf-purify~ and ~cape-wrap-purify~ as obsolete.
12 | - ~cape-capf-sort~: Make ~SORT~ function argument optional. If the ~SORT~ argument is
13 | nil or not given, the completion UI sorting will take over.
14 | - ~cape-capf-trigger~, ~cape-wrap-trigger~: New Capf transformer for trigger
15 | characters. The Capf will only complete if the trigger character occurs before
16 | point. See also ~corfu-auto-trigger~.
17 | - ~cape-capf-choose~, ~cape-wrap-choose~: New Capf transformer to choose from
18 | multiple Capfs.
19 |
20 | * Version 2.2 (2025-10-13)
21 |
22 | - Minor improvements.
23 | - Require Emacs 29.
24 |
25 | * Version 2.1 (2025-05-21)
26 |
27 | - Simplify ~cape-dabbrev~ configuration.
28 | - ~cape-dabbrev-buffer-function~: New variable to configure the buffers searched
29 | by ~cape-dabbrev~.
30 | - ~cape-dabbrev-check-other-buffers~: Removed in favor of ~cape-dabbrev-buffer-function~.
31 | - ~cape-dabbrev-min-length~: Remove variable, since it leads to confusion due to
32 | missing completion candidates.
33 | - ~cape-same-mode-buffers~: New public function, renamed from
34 | ~cape--buffers-major-mode~.
35 | - ~cape-text-buffers~: New function.
36 | - ~cape-dabbrev-buffer-function~, ~cape-line-buffer-function~: Use
37 | ~cape-same-mode-buffers~.
38 |
39 | * Version 2.0 (2025-03-11)
40 |
41 | - ~cape-file~: Improve handling of environment variables as part of the path,
42 | e.g., ~$HOME~.
43 | - ~cape-company-to-capf~: Handle updated return value convention of the ~prefix~
44 | action of Company backends.
45 |
46 | * Version 1.9 (2025-01-28)
47 |
48 | - ~cape-capf-super~: Use extra metadata instead of completion table metadata.
49 | - ~cape-emoji~: Improve emoji name normalization.
50 |
51 | * Version 1.8 (2024-12-22)
52 |
53 | - Require Emacs 28.1.
54 | - ~cape-capf-properties~: Add ~:strip~ keyword to strip a Capf of its metadata.
55 | - ~cape-capf-sort~: New function.
56 | - Add ~:display-sort-function~ and ~:cycle-sort-function~ functions to the various
57 | Capf property lists.
58 |
59 | * Version 1.7 (2024-08-26)
60 |
61 | - ~cape-elisp-symbol~: Add wrappers only if not yet there.
62 | - ~cape-elisp-symbol~: Add wrappers in ~emacs-lisp-mode~ inside strings/comments.
63 |
64 | * Version 1.6 (2024-07-23)
65 |
66 | - Add ~cape-prefix-map~ for simplified configuration.
67 | - ~cape-wrap-super~: Bugfix. Ensure that annotation functions are called with
68 | candidates belonging to the originating Capf.
69 | - Disallow ~cape-company-to-capf~ if ~company-mode~ is enabled.
70 | - Bump Compat dependency to Compat 30.
71 |
72 | * Version 1.5 (2024-04-12)
73 |
74 | - ~cape-file-prefix~: New variable to customize file name completion prefix. If
75 | the input matches one of the configured prefixes, file completion is started.
76 | - ~cape-capf-super~: Support Capfs which return different prefix lengths. This
77 | change improves compatibility with Company.
78 | - ~cape-capf-super~: Add support for the ~:with~ keyword. See the docstring of
79 | ~cape-wrap-super~ for details. This change improves compatibility with Company.
80 | - ~cape-capf-super~: The resulting Capf is exclusive if one of the main Capfs (the
81 | Capfs listed before the ~:with~ keyword) is exclusive.
82 | - ~cape-capf-super~: If the resulting Capf is non-exclusive, one of the main Capfs
83 | must have returned candidates, in order for the resulting Capf to return
84 | candidates.
85 | - ~cape-capf-super~: Normalize plists which are attached to candidates. This helps
86 | with deduplication, such that only candidates with different annotations or
87 | icons appear twice.
88 | - ~cape-dabbrev-check-other-buffers~: Support function as customization value. The
89 | function should return the exact list of buffers to search.
90 |
91 | * Version 1.4 (2024-03-08)
92 |
93 | - =cape-char=: Look back from point, instead of using the match at point. This
94 | makes sure that double quotes of a string literal behind point are not
95 | included in the completion.
96 | - =cape-capf-inside-faces=: Use the face before point to handle completion at the
97 | end of comments more gracefully.
98 |
99 | * Version 1.3 (2024-02-14)
100 |
101 | - Add =cape-wrap-inside-code= and =cape-capf-inside-code=.
102 |
103 | * Version 1.2 (2024-01-23)
104 |
105 | - =cape-capf-super=: Bugfixes.
106 |
107 | * Version 1.1 (2023-12-27)
108 |
109 | - =cape-capf-super=, =cape-company-to-capf=: Support duplicate candidates.
110 | - Remove obsolete function aliases ~cape-super-capf~, ~cape-interactive-capf~ and
111 | ~cape-symbol~.
112 |
113 | * Version 1.0 (2023-12-01)
114 |
115 | - =cape-emoji=: New Capf available on Emacs 29 and newer.
116 | - =cape-wrap-debug=, =cape-capf-debug=: New Capf transformers to add debug messages
117 | to a Capf.
118 | - =cape-wrap-passthrough=, =cape-capf-passthrough=: New Capf transformers to defeat
119 | completion style filtering.
120 | - =cape-capf-inside-faces=, =cape-wrap-inside-faces=: New transformer
121 | - Rename =cape-super-capf= to =cape-capf-super=. Add =cape-wrap-super= for consistency
122 | with other Capf combinators.
123 | - Rename =cape-interactive-capf= to =cape-capf-interactive= for consistency with
124 | other Capf combinators.
125 | - Rename =cape-symbol= to =cape-elisp-symbol=.
126 |
127 | * Version 0.17 (2023-08-14)
128 |
129 | - Bugfixes.
130 | - =cape-dict=: Always use grep, remove =cape-dict-use-grep=.
131 | - =cape-dict=: Add =cape-dict-limit=.
132 | - Remove obsolete alias =cape-ispell=.
133 | - Generalize =cape--cached-table=. The candidate computation function must return
134 | a pair of a predicate function and the list of candidates.
135 |
136 | * Version 0.16 (2023-07-02)
137 |
138 | - =cape-dabbrev=: Respect =dabbrev-abbrev-char-regexp= and
139 | =dabbrev-abbrev-skip-leading-regexp=.
140 | - =cape-file=: Quote file names in comint/eshell buffers.
141 |
142 | * Version 0.15 (2023-04-17)
143 |
144 | - Bugfixes
145 |
146 | * Version 0.14 (2023-04-13)
147 |
148 | - =cape-wrap-buster=, =cape-capf-buster= and =cape-company-to-capf=: The argument
149 | VALID must be a function taking two arguments, the old and new input. It
150 | should return nil if the input must be considered invalid such that the
151 | candidates must be recomputed.
152 | - =cape-ispell=: Deprecate in favor of improved =cape-dict=. Note that =cape-ispell=
153 | and =ispell-lookup-words= did not really consult =ispell= or =aspell=, but only grep
154 | through the word list specified by =ispell-alternate-dictionary=.
155 | - =cape-dict-file=: Support multiple dictionary files or a function returning one
156 | or more files.
157 | - =cape-dict=, =cape-dabbrev=: Replace case depending on initial input.
158 | - =cape-dict-case-replace=: New variable to configure case replacement, similar to
159 | =dabbrev-case-replace=.
160 | - =cape-dict-case-fold=: New variable to configure if case is ignored
161 | during search and completion.
162 | - =cape-elisp-block=: Complete Elisp in Org or Markdown code block. This Capf is
163 | particularly useful for literate Emacs configurations.
164 |
165 | * Version 0.13 (2023-02-15)
166 |
167 | - Start of changelog.
168 |
--------------------------------------------------------------------------------
/README.org:
--------------------------------------------------------------------------------
1 | #+title: cape.el - Let your completions fly!
2 | #+author: Daniel Mendler
3 | #+language: en
4 | #+export_file_name: cape.texi
5 | #+texinfo_dir_category: Emacs misc features
6 | #+texinfo_dir_title: Cape: (cape).
7 | #+texinfo_dir_desc: Completion At Point Extensions
8 |
9 | #+html:
10 | #+html:
11 | #+html:
12 | #+html:
13 | #+html:
14 |
15 | Cape provides Completion At Point Extensions which can be used in combination
16 | with [[https://github.com/minad/corfu][Corfu]], [[https://github.com/company-mode/company-mode][Company]] or the default completion UI. The completion backends used
17 | by ~completion-at-point~ are so called ~completion-at-point-functions~ (Capfs).
18 |
19 | #+html:
20 |
21 | You can register the ~cape-*~ functions in the ~completion-at-point-functions~ list.
22 | This makes the backends available for completion, which is usually invoked by
23 | pressing ~TAB~ or ~M-TAB~. The functions can also be invoked interactively to
24 | trigger the respective completion at point. You can bind them directly to a key
25 | in your user configuration. Notable commands/Capfs are ~cape-line~ for completion
26 | of a line from the current buffer, ~cape-history~ for history completion in shell
27 | or Comint modes and ~cape-file~ for completion of file names. The commands
28 | ~cape-elisp-symbol~ and ~cape-elisp-block~ are useful for documentation of Elisp
29 | packages or configurations, since they complete Elisp anywhere.
30 |
31 | Cape has the super power to transform Company backends into Capfs and merge
32 | multiple Capfs into a Super-Capf! These transformers allow you to still take
33 | advantage of Company backends even if you are not using Company as frontend.
34 |
35 | #+toc: headlines 8
36 |
37 | * Available Capfs
38 |
39 | + ~cape-abbrev~: Complete abbreviation (~add-global-abbrev~, ~add-mode-abbrev~).
40 | + ~cape-dabbrev~: Complete word from current buffers. See also ~dabbrev-capf~.
41 | + ~cape-dict~: Complete word from dictionary file.
42 | + ~cape-elisp-block~: Complete Elisp in Org or Markdown code block.
43 | + ~cape-elisp-symbol~: Complete Elisp symbol.
44 | + ~cape-emoji~: Complete Emoji.
45 | + ~cape-file~: Complete file name.
46 | + ~cape-history~: Complete from Eshell, Comint or minibuffer history.
47 | + ~cape-keyword~: Complete programming language keyword.
48 | + ~cape-line~: Complete entire line from current buffer.
49 | + ~cape-rfc1345~: Complete Unicode char using RFC 1345 mnemonics.
50 | + ~cape-sgml~: Complete Unicode char from SGML entity, e.g., ~&alpha~.
51 | + ~cape-tex~: Complete Unicode char from TeX command, e.g. ~\hbar~.
52 |
53 | * Configuration
54 |
55 | Cape is available on GNU ELPA and MELPA. You can install the package with
56 | ~package-install~. In the following we present a sample configuration based on the
57 | popular ~use-package~ macro.
58 |
59 | I recommend to bind the =cape-*= completion commands to keys such that you can
60 | invoke them explicitly. This makes particular sense for special Capfs which you
61 | only want to trigger in rare circumstances. See the =:bind= specification below.
62 |
63 | Furthermore the =cape-*= functions are Capfs which you can add to the
64 | =completion-at-point-functions= list. Take care when adding Capfs to the list
65 | since each of the Capfs adds a small runtime cost. Note that the Capfs which
66 | occur earlier in the list take precedence, such that the first Capf returning a
67 | result will win and the later Capfs may not get a chance to run. In order to
68 | merge Capfs you can try the function =cape-capf-super=.
69 |
70 | One must distinguish the buffer-local and the global value of the
71 | =completion-at-point-functions= variable. The buffer-local value of the list takes
72 | precedence, but if the buffer-local list contains the symbol =t= at the end, it
73 | means that the functions specified in the global list should be executed
74 | afterwards. The special meaning of the value =t= is a feature of the =run-hooks=
75 | function, see the section [[info:elisp#Running Hooks]["Running Hooks" in the Elisp manual]] for further
76 | information.
77 |
78 | #+begin_src emacs-lisp
79 | ;; Enable Corfu completion UI
80 | ;; See the Corfu README for more configuration tips.
81 | (use-package corfu
82 | :init
83 | (global-corfu-mode))
84 |
85 | ;; Add extensions
86 | (use-package cape
87 | ;; Bind prefix keymap providing all Cape commands under a mnemonic key.
88 | ;; Press C-c p ? to for help.
89 | :bind ("C-c p" . cape-prefix-map) ;; Alternative key: M-, M-p, M-+
90 | ;; Alternatively bind Cape commands individually.
91 | ;; :bind (("C-c p d" . cape-dabbrev)
92 | ;; ("C-c p h" . cape-history)
93 | ;; ("C-c p f" . cape-file)
94 | ;; ...)
95 | :init
96 | ;; Add to the global default value of `completion-at-point-functions' which is
97 | ;; used by `completion-at-point'. The order of the functions matters, the
98 | ;; first function returning a result wins. Note that the list of buffer-local
99 | ;; completion functions takes precedence over the global list.
100 | (add-hook 'completion-at-point-functions #'cape-dabbrev)
101 | (add-hook 'completion-at-point-functions #'cape-file)
102 | (add-hook 'completion-at-point-functions #'cape-elisp-block)
103 | ;; (add-hook 'completion-at-point-functions #'cape-history)
104 | ;; ...
105 | )
106 | #+end_src
107 |
108 | * CAPF adapters and transformers
109 | ** Company adapter
110 |
111 | /Wrap your Company backend in a Cape and turn it into a Capf!/
112 |
113 | Cape provides the adapter ~cape-company-to-capf~ for Company backends. The adapter
114 | transforms Company backends to Capfs which are understood by the built-in Emacs
115 | completion mechanism. The function is approximately the inverse of the
116 | ~company-capf~ backend from Company. The adapter can be used as follows:
117 |
118 | #+begin_src emacs-lisp
119 | ;; Use Company backends as Capfs.
120 | (setq-local completion-at-point-functions
121 | (mapcar #'cape-company-to-capf
122 | (list #'company-files #'company-keywords #'company-dabbrev)))
123 | #+end_src
124 |
125 | Note that the adapter does not require Company to be installed or enabled.
126 | Backends implementing the Company specification do not necessarily have to
127 | depend on Company, however in practice most backends do. The following shows a
128 | small example completion backend, which can be used with both
129 | ~completion-at-point~ (Corfu, default completion) and Company.
130 |
131 | #+begin_src emacs-lisp
132 | (defvar demo-alist
133 | '((":-D" . "😀")
134 | (";-)" . "😉")
135 | (":-/" . "😕")
136 | (":-(" . "🙁")
137 | (":-*" . "😙")))
138 |
139 | (defun demo-backend (action &optional arg &rest _)
140 | (pcase action
141 | ('prefix
142 | (when-let (beg (save-excursion
143 | (and (re-search-backward "[;:]" (pos-bol) t) (point))))
144 | (list (buffer-substring-no-properties beg (point)) "" t)))
145 | ('candidates (all-completions arg demo-alist))
146 | ('annotation (concat " " (cdr (assoc arg demo-alist))))
147 | ('post-completion
148 | (let ((str (buffer-substring (- (point) 3) (point))))
149 | (delete-region (- (point) 3) (point))
150 | (insert (cdr (assoc str demo-alist)))))))
151 |
152 | ;; Register demo backend with `completion-at-point'
153 | (setq completion-at-point-functions
154 | (list (cape-company-to-capf #'demo-backend)))
155 |
156 | ;; Register demo backend with Company.
157 | (setq company-backends '(demo-backend))
158 | #+end_src
159 |
160 | It is possible to merge multiple Company backends and use them as a single Capf
161 | using the ~company--multi-backend-adapter~ function from Company. The adapter
162 | transforms multiple Company backends into a single Company backend, which can
163 | then be used as a Capf via ~cape-company-to-capf~. Capfs can be merged directly
164 | with ~cape-capf-super~.
165 |
166 | #+begin_src emacs-lisp
167 | (require 'company)
168 | ;; Use the company-dabbrev and company-elisp backends together.
169 | (setq completion-at-point-functions
170 | (list
171 | (cape-company-to-capf
172 | (apply-partially #'company--multi-backend-adapter
173 | '(company-dabbrev company-elisp)))))
174 | #+end_src
175 |
176 | ** Super-Capf - Merging multiple Capfs
177 |
178 | /Throw multiple Capfs under the Cape and get a Super-Capf!/
179 |
180 | Cape supports merging multiple Capfs using the function ~cape-capf-super~. Due to
181 | technical details, not all Capfs can be merged successfully. Try to merge Capfs
182 | one by one and make sure that you get the desired outcome.
183 |
184 | Note that ~cape-capf-super~ is not needed if multiple Capfs should be tried one
185 | after another, for example you can use ~cape-file~ together with programming mode
186 | Capfs by adding ~cape-file~ to the ~completion-at-point-functions~ list. File
187 | completion will then be available in comments and string literals, but not in
188 | normal code. ~cape-capf-super~ is only necessary if you want to combine multiple
189 | Capfs, such that the candidates from multiple sources appear /together/ in the
190 | completion list at the same time.
191 |
192 | Capf merging requires completion functions which are sufficiently well-behaved
193 | and completion functions which do not define completion boundaries.
194 | ~cape-capf-super~ has the same restrictions as ~completion-table-merge~ and
195 | ~completion-table-in-turn~. As a simple rule of thumb, ~cape-capf-super~ works for
196 | static completion functions like ~cape-dabbrev~, ~cape-keyword~, ~cape-dict~, etc.,
197 | but not for multi-step completions like ~cape-file~.
198 |
199 | The results returned by the individual Capfs are listed after each other, where
200 | the the order of the completion candidates is preserved. In order to override
201 | this sorting behavior use ~cape-capf-sort~, such that the completion UI can apply
202 | its own sorting.
203 |
204 | #+begin_src emacs-lisp
205 | ;; Merge the dabbrev, dict and keyword capfs, display candidates together.
206 | (setq-local completion-at-point-functions
207 | (list (cape-capf-super #'cape-dabbrev #'cape-dict)))
208 |
209 | ;; Let the UI (e.g. Corfu) sort the candidates by overriding the sort function.
210 | (setq-local completion-at-point-functions
211 | (list (cape-capf-sort (cape-capf-super #'cape-dabbrev #'cape-dict))))
212 |
213 | ;; Trigger completion only after trigger character.
214 | (setq-local corfu-auto-trigger "/"
215 | completion-at-point-functions
216 | (list (cape-capf-trigger (cape-capf-super #'cape-abbrev #'tempel-complete) ?/)))
217 |
218 | ;; Define named Capf instead of using the anonymous Capf directly.
219 | (defun cape-dabbrev-dict ()
220 | (cape-wrap-super #'cape-dabbrev #'cape-dict))
221 | (setq-local completion-at-point-functions (list #'cape-dabbrev-dict))
222 | #+end_src
223 |
224 | If you want to merge multiple Company backends, use the aforementioned
225 | ~company--multi-backend-adapter~ from Company. In order to combine multiple Capfs,
226 | such that each of the Capfs is tried one after another, use ~cape-capf-choose~.
227 |
228 | ** Capf-Buster - Cache busting
229 |
230 | /The Capf-Buster ensures that you always get a fresh set of candidates!/
231 |
232 | If a Capf caches the candidates for too long we can use a cache busting
233 | Capf-transformer. For example the Capf merging function ~cape-capf-super~ creates
234 | a Capf, which caches the candidates for the whole lifetime of the Capf.
235 | Therefore you may want to combine a merged Capf with a cache buster under some
236 | circumstances. It is noteworthy that the ~company-capf~ backend from Company
237 | refreshes the completion table frequently. With the ~cape-capf-buster~ we can
238 | achieve a similarly refreshing strategy.
239 |
240 | #+begin_src emacs-lisp
241 | (setq-local completion-at-point-functions
242 | (list (cape-capf-buster #'some-caching-capf)))
243 | #+end_src
244 |
245 | ** Capf transformers
246 |
247 | /Wrap one or multiple Capfs in a Cape to get a Capf of different flavor!/
248 |
249 | Cape provides a set of additional Capf transformation functions, which are
250 | mostly meant to used by experts to fine tune the Capf behavior and Capf
251 | interaction. These can either be used as advices (=cape-wrap-*)= or to create a
252 | new Capf from an existing Capf (=cape-capf-*=). You can bind the Capfs created by
253 | the Capf transformers with =defalias= to a function symbol.
254 |
255 | - ~cape-capf-accept-all~, ~cape-wrap-accept-all~: Create a Capf which accepts every input as valid.
256 | - ~cape-capf-case-fold~, ~cape-wrap-case-fold~: Create a Capf which is case insensitive.
257 | - ~cape-capf-choose~, ~cape-wrap-choose~: Choose from multiple Capfs.
258 | - ~cape-capf-debug~, ~cape-wrap-debug~: Create a Capf which prints debugging messages.
259 | - ~cape-capf-inside-code~, ~cape-wrap-inside-code~: Ensure that Capf triggers only inside code.
260 | - ~cape-capf-inside-comment~, ~cape-wrap-inside-comment~: Ensure that Capf triggers only inside comments.
261 | - ~cape-capf-inside-faces~, ~cape-wrap-inside-faces~: Ensure that Capf triggers only inside text with certain faces.
262 | - ~cape-capf-inside-string~, ~cape-wrap-inside-string~: Ensure that Capf triggers only inside a string literal.
263 | - ~cape-capf-interactive~, ~cape-interactive~: Create a Capf which can be called interactively.
264 | - ~cape-capf-nonexclusive~, ~cape-wrap-nonexclusive~: Mark Capf as non-exclusive.
265 | - ~cape-capf-noninterruptible~, ~cape-wrap-noninterruptible~: Protect a Capf which does not like to be interrupted.
266 | - ~cape-capf-passthrough~, ~cape-wrap-passthrough~: Defeat entire completion style filtering.
267 | - ~cape-capf-predicate~, ~cape-wrap-predicate~: Add candidate predicate to a Capf.
268 | - ~cape-capf-prefix-length~, ~cape-wrap-prefix-length~: Enforce a minimal prefix length.
269 | - ~cape-capf-properties~, ~cape-wrap-properties~: Add completion properties to a Capf.
270 | - ~cape-capf-silent~, ~cape-wrap-silent~: Silence Capf messages and errors.
271 | - ~cape-capf-sort~, ~cape-wrap-sort~: Add sort function to a Capf.
272 | - ~cape-capf-super~, ~cape-wrap-super~: Merge multiple Capfs into a Super-Capf.
273 | - ~cape-capf-trigger~, ~cape-wrap-trigger~: Create a Capf with a trigger prefix character.
274 |
275 | In the following we show a few example configurations, which have come up on the
276 | [[https://github.com/minad/cape/issues][Cape]] or [[https://github.com/minad/corfu/issues][Corfu issue tracker]] or the [[https://github.com/minad/corfu/wiki][Corfu wiki.]] I use some of these tweaks in my
277 | personal configuration.
278 |
279 | #+begin_src emacs-lisp
280 | ;; Example 1: Configure a merged Capf with a trigger prefix character.
281 | (setq-local corfu-auto-trigger "/"
282 | completion-at-point-functions
283 | (list (cape-capf-trigger (cape-capf-super #'cape-abbrev #'tempel-complete) ?/)))
284 |
285 | ;; Example 2: Configure a Capf with a specific auto completion prefix length.
286 | (setq-local completion-at-point-functions
287 | (list (cape-capf-prefix-length #'cape-dabbrev 2)))
288 |
289 | ;; Example 3: Create a Capf with debugging messages.
290 | (setq-local completion-at-point-functions (list (cape-capf-debug #'cape-dict)))
291 |
292 | ;; Example 4: Named Capf.
293 | (defalias 'cape-dabbrev-min-2 (cape-capf-prefix-length #'cape-dabbrev 2))
294 | (setq-local completion-at-point-functions (list #'cape-dabbrev-min-2))
295 |
296 | ;; Example 5: Define a defensive Dabbrev Capf, which accepts all inputs. If you
297 | ;; use Corfu and `corfu-auto=t', the first candidate won't be auto selected if
298 | ;; `corfu-preselect=valid', such that it cannot be accidentally committed when
299 | ;; pressing RET.
300 | (defun my-cape-dabbrev-accept-all ()
301 | (cape-wrap-accept-all #'cape-dabbrev))
302 | (add-hook 'completion-at-point-functions #'my-cape-dabbrev-accept-all)
303 |
304 | ;; Example 6: Define interactive Capf which can be bound to a key. Here we wrap
305 | ;; the `elisp-completion-at-point' such that we can complete Elisp code
306 | ;; explicitly in arbitrary buffers.
307 | (keymap-global-set "C-c p e" (cape-capf-interactive #'elisp-completion-at-point))
308 |
309 | ;; Example 7: Ignore :keywords in Elisp completion.
310 | (defun ignore-elisp-keywords (sym)
311 | (not (keywordp sym)))
312 | (setq-local completion-at-point-functions
313 | (list (cape-capf-predicate #'elisp-completion-at-point
314 | #'ignore-elisp-keywords)))
315 |
316 | ;; Example 8: Catch errors with `cape-wrap-silent'.
317 | (advice-add 'dabbrev-capf :around #'cape-wrap-silent)
318 | (advice-add 'pcomplete-completions-at-point :around #'cape-wrap-silent) ;; Was necessary on Emacs 28
319 | #+end_src
320 |
321 | * Contributions
322 |
323 | Since this package is part of [[https://elpa.gnu.org/packages/cape.html][GNU ELPA]] contributions require a copyright
324 | assignment to the FSF.
325 |
--------------------------------------------------------------------------------
/cape-keyword.el:
--------------------------------------------------------------------------------
1 | ;;; cape-keyword.el --- Keyword completion function -*- lexical-binding: t -*-
2 |
3 | ;; Copyright (C) 2021-2025 Free Software Foundation, Inc.
4 |
5 | ;; This file is part of GNU Emacs.
6 |
7 | ;; This program is free software: you can redistribute it and/or modify
8 | ;; it under the terms of the GNU General Public License as published by
9 | ;; the Free Software Foundation, either version 3 of the License, or
10 | ;; (at your option) any later version.
11 |
12 | ;; This program is distributed in the hope that it will be useful,
13 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | ;; GNU General Public License for more details.
16 |
17 | ;; You should have received a copy of the GNU General Public License
18 | ;; along with this program. If not, see .
19 |
20 | ;;; Commentary:
21 |
22 | ;; This package provides the `cape-keyword' completion function.
23 |
24 | ;;; Code:
25 |
26 | (require 'cape)
27 |
28 | (defcustom cape-keyword-list
29 | ;; This variable was taken from company-keywords.el.
30 | ;; Please contribute corrections or additions to both Cape and Company.
31 | '((c++-mode ;; https://en.cppreference.com/w/cpp/keyword
32 | "alignas" "alignof" "and" "and_eq" "asm" "atomic_cancel" "atomic_commit"
33 | "atomic_noexcept" "auto" "bitand" "bitor" "bool" "break" "case" "catch"
34 | "char" "char16_t" "char32_t" "char8_t" "class" "co_await" "co_return"
35 | "co_yield" "compl" "concept" "const" "const_cast" "consteval" "constexpr"
36 | "constinit" "continue" "decltype" "default" "delete" "do" "double"
37 | "dynamic_cast" "else" "enum" "explicit" "export" "extern" "false" "final"
38 | "float" "for" "friend" "goto" "if" "import" "inline" "int" "long" "module"
39 | "mutable" "namespace" "new" "noexcept" "not" "not_eq" "nullptr" "operator"
40 | "or" "or_eq" "override" "private" "protected" "public" "reflexpr"
41 | "register" "reinterpret_cast" "requires" "return" "short" "signed" "sizeof"
42 | "static" "static_assert" "static_cast" "struct" "switch" "synchronized"
43 | "template" "this" "thread_local" "throw" "true" "try" "typedef" "typeid"
44 | "typename" "union" "unsigned" "using" "virtual" "void" "volatile" "wchar_t"
45 | "while" "xor" "xor_eq")
46 | (c-mode ;; https://en.cppreference.com/w/c/keyword
47 | "_Alignas" "_Alignof" "_Atomic" "_Bool" "_Complex" "_Decimal128"
48 | "_Decimal32" "_Decimal64" "_Generic" "_Imaginary" "_Noreturn"
49 | "_Static_assert" "_Thread_local" "__asm__" "asm" "auto" "break" "case"
50 | "char" "const" "continue" "default" "do" "double" "else" "enum" "extern"
51 | "float" "for" "goto" "if" "inline" "int" "long" "register" "restrict"
52 | "return" "short" "signed" "sizeof" "static" "struct" "switch" "typedef"
53 | "union" "unsigned" "void" "volatile" "while")
54 | (caml-mode ;; ocaml, from https://v2.ocaml.org/manual/lex.html#sss:keywords
55 | "and" "as" "asr" "assert" "begin" "class" "constraint" "do" "done" "downto"
56 | "else" "end" "exception" "external" "false" "for" "fun" "function"
57 | "functor" "if" "in" "include" "inherit" "initializer" "land" "lazy" "let"
58 | "lor" "lsl" "lsr" "lxor" "match" "method" "mod" "module" "mutable" "new"
59 | "nonrec" "object" "of" "open" "or" "private" "rec" "sig" "struct" "then"
60 | "to" "true" "try" "type" "val" "virtual" "when" "while" "with")
61 | (crystal-mode ;; https://github.com/crystal-lang/crystal-book "abstract"
62 | "alias" "annotation" "as" "as?" "asm" "begin" "break" "case" "class" "def"
63 | "do" "else" "elsif" "end" "ensure" "enum" "extend" "false" "for" "fun" "if"
64 | "in" "include" "instance_sizeof" "is_a?" "lib" "macro" "module" "next"
65 | "nil" "nil?" "of" "offsetof" "out" "pointerof" "private" "protected"
66 | "require" "rescue" "responds_to?" "return" "select" "self" "sizeof"
67 | "struct" "super" "then" "true" "type" "typeof" "uninitialized" "union"
68 | "unless" "until" "verbatim" "when" "while" "with" "yield")
69 | (csharp-mode
70 | "abstract" "add" "alias" "as" "base" "bool" "break" "byte" "case" "catch"
71 | "char" "checked" "class" "const" "continue" "decimal" "default" "delegate"
72 | "do" "double" "else" "enum" "event" "explicit" "extern" "false" "finally"
73 | "fixed" "float" "for" "foreach" "get" "global" "goto" "if" "implicit" "in"
74 | "int" "interface" "internal" "is" "lock" "long" "namespace" "new" "null"
75 | "object" "operator" "out" "override" "params" "partial" "private"
76 | "protected" "public" "readonly" "ref" "remove" "return" "sbyte" "sealed"
77 | "set" "short" "sizeof" "stackalloc" "static" "string" "struct" "switch"
78 | "this" "throw" "true" "try" "typeof" "uint" "ulong" "unchecked" "unsafe"
79 | "ushort" "using" "value" "var" "virtual" "void" "volatile" "where" "while"
80 | "yield")
81 | (d-mode ;; https://www.digitalmars.com/d/2.0/lex.html
82 | "abstract" "alias" "align" "asm"
83 | "assert" "auto" "body" "bool" "break" "byte" "case" "cast" "catch"
84 | "cdouble" "cent" "cfloat" "char" "class" "const" "continue" "creal"
85 | "dchar" "debug" "default" "delegate" "delete" "deprecated" "do"
86 | "double" "else" "enum" "export" "extern" "false" "final" "finally"
87 | "float" "for" "foreach" "foreach_reverse" "function" "goto" "idouble"
88 | "if" "ifloat" "import" "in" "inout" "int" "interface" "invariant"
89 | "ireal" "is" "lazy" "long" "macro" "mixin" "module" "new" "nothrow"
90 | "null" "out" "override" "package" "pragma" "private" "protected"
91 | "public" "pure" "real" "ref" "return" "scope" "short" "static" "struct"
92 | "super" "switch" "synchronized" "template" "this" "throw" "true" "try"
93 | "typedef" "typeid" "typeof" "ubyte" "ucent" "uint" "ulong" "union"
94 | "unittest" "ushort" "version" "void" "volatile" "wchar" "while" "with")
95 | (elixir-mode ;; https://hexdocs.pm/elixir/Kernel.html
96 | "__CALLER__" "__DIR__" "__ENV__" "__MODULE__" "__STACKTRACE__"
97 | "__aliases__" "__block__" "abs" "alias" "alias!" "and" "apply"
98 | "binary_part" "binary_slice" "binding" "bit_size" "byte_size" "case" "ceil"
99 | "cond" "dbg" "def" "defdelegate" "defexception" "defguard" "defguardp"
100 | "defimpl" "defmacro" "defmacrop" "defmodule" "defoverridable" "defp"
101 | "defprotocol" "defstruct" "destructure" "div" "elem" "exit" "floor" "fn"
102 | "for" "function_exported?" "get_and_update_in" "get_in" "hd" "if" "import"
103 | "in" "inspect" "is_atom" "is_binary" "is_bitstring" "is_boolean"
104 | "is_exception" "is_float" "is_function" "is_integer" "is_list" "is_map"
105 | "is_map_key" "is_nil" "is_number" "is_pid" "is_port" "is_reference"
106 | "is_struct" "is_tuple" "length" "macro_exported?" "make_ref" "map_size"
107 | "match?" "max" "min" "node" "not" "or" "pop_in" "put_elem" "put_in" "quote"
108 | "raise" "receive" "rem" "require" "reraise" "round" "self" "send" "spawn"
109 | "spawn_link" "spawn_monitor" "struct" "struct!" "super" "tap" "then"
110 | "throw" "tl" "to_charlist" "to_string" "trunc" "try" "tuple_size" "unless"
111 | "unquote" "unquote_splicing" "update_in" "use" "var!" "with")
112 | (erlang-mode ;; https://www.erlang.org/docs/20/reference_manual/introduction.html
113 | "after" "and" "andalso" "band" "begin" "bnot" "bor" "bsl" "bsr" "bxor"
114 | "case" "catch" "cond" "div" "end" "fun" "if" "let" "not" "of" "or" "orelse"
115 | "receive" "rem" "try" "when" "xor")
116 | (f90-mode ;; f90.el
117 | "abs" "abstract" "achar" "acos" "adjustl" "adjustr" "aimag" "aint" "align"
118 | "all" "all_prefix" "all_scatter" "all_suffix" "allocatable" "allocate"
119 | "allocated" "and" "anint" "any" "any_prefix" "any_scatter" "any_suffix"
120 | "asin" "assign" "assignment" "associate" "associated" "asynchronous" "atan"
121 | "atan2" "backspace" "bind" "bit_size" "block" "btest" "c_alert"
122 | "c_associated" "c_backspace" "c_bool" "c_carriage_return" "c_char"
123 | "c_double" "c_double_complex" "c_f_pointer" "c_f_procpointer" "c_float"
124 | "c_float_complex" "c_form_feed" "c_funloc" "c_funptr" "c_horizontal_tab"
125 | "c_int" "c_int16_t" "c_int32_t" "c_int64_t" "c_int8_t" "c_int_fast16_t"
126 | "c_int_fast32_t" "c_int_fast64_t" "c_int_fast8_t" "c_int_least16_t"
127 | "c_int_least32_t" "c_int_least64_t" "c_int_least8_t" "c_intmax_t"
128 | "c_intptr_t" "c_loc" "c_long" "c_long_double" "c_long_double_complex"
129 | "c_long_long" "c_new_line" "c_null_char" "c_null_funptr" "c_null_ptr"
130 | "c_ptr" "c_short" "c_signed_char" "c_size_t" "c_vertical_tab" "call" "case"
131 | "ceiling" "char" "character" "character_storage_size" "class" "close"
132 | "cmplx" "command_argument_count" "common" "complex" "conjg" "contains"
133 | "continue" "copy_prefix" "copy_scatter" "copy_suffix" "cos" "cosh" "count"
134 | "count_prefix" "count_scatter" "count_suffix" "cpu_time" "cshift" "cycle"
135 | "cyclic" "data" "date_and_time" "dble" "deallocate" "deferred" "digits"
136 | "dim" "dimension" "distribute" "do" "dot_product" "double" "dprod"
137 | "dynamic" "elemental" "else" "elseif" "elsewhere" "end" "enddo" "endfile"
138 | "endif" "entry" "enum" "enumerator" "eoshift" "epsilon" "eq" "equivalence"
139 | "eqv" "error_unit" "exit" "exp" "exponent" "extends" "extends_type_of"
140 | "external" "extrinsic" "false" "file_storage_size" "final" "floor" "flush"
141 | "forall" "format" "fraction" "function" "ge" "generic" "get_command"
142 | "get_command_argument" "get_environment_variable" "goto" "grade_down"
143 | "grade_up" "gt" "hpf_alignment" "hpf_distribution" "hpf_template" "huge"
144 | "iachar" "iall" "iall_prefix" "iall_scatter" "iall_suffix" "iand" "iany"
145 | "iany_prefix" "iany_scatter" "iany_suffix" "ibclr" "ibits" "ibset" "ichar"
146 | "ieee_arithmetic" "ieee_exceptions" "ieee_features"
147 | "ieee_get_underflow_mode" "ieee_set_underflow_mode"
148 | "ieee_support_underflow_control" "ieor" "if" "ilen" "implicit" "import"
149 | "include" "independent" "index" "inherit" "input_unit" "inquire" "int"
150 | "integer" "intent" "interface" "intrinsic" "ior" "iostat_end" "iostat_eor"
151 | "iparity" "iparity_prefix" "iparity_scatter" "iparity_suffix" "ishft"
152 | "ishftc" "iso_c_binding" "iso_fortran_env" "kind" "lbound" "le" "leadz"
153 | "len" "len_trim" "lge" "lgt" "lle" "llt" "log" "log10" "logical" "lt"
154 | "matmul" "max" "maxexponent" "maxloc" "maxval" "maxval_prefix"
155 | "maxval_scatter" "maxval_suffix" "merge" "min" "minexponent" "minloc"
156 | "minval" "minval_prefix" "minval_scatter" "minval_suffix" "mod" "module"
157 | "modulo" "move_alloc" "mvbits" "namelist" "ne" "nearest" "neqv" "new"
158 | "new_line" "nint" "non_intrinsic" "non_overridable" "none" "nopass" "not"
159 | "null" "nullify" "number_of_processors" "numeric_storage_size" "only"
160 | "onto" "open" "operator" "optional" "or" "output_unit" "pack" "parameter"
161 | "parity" "parity_prefix" "parity_scatter" "parity_suffix" "pass" "pause"
162 | "pointer" "popcnt" "poppar" "precision" "present" "print" "private"
163 | "procedure" "processors" "processors_shape" "product" "product_prefix"
164 | "product_scatter" "product_suffix" "program" "protected" "public" "pure"
165 | "radix" "random_number" "random_seed" "range" "read" "real" "realign"
166 | "recursive" "redistribute" "repeat" "reshape" "result" "return" "rewind"
167 | "rrspacing" "same_type_as" "save" "scale" "scan" "select"
168 | "selected_char_kind" "selected_int_kind" "selected_real_kind" "sequence"
169 | "set_exponent" "shape" "sign" "sin" "sinh" "size" "spacing" "spread" "sqrt"
170 | "stop" "subroutine" "sum" "sum_prefix" "sum_scatter" "sum_suffix"
171 | "system_clock" "tan" "tanh" "target" "template" "then" "tiny" "transfer"
172 | "transpose" "trim" "true" "type" "ubound" "unpack" "use" "value" "verify"
173 | "volatile" "wait" "where" "while" "with" "write")
174 | (go-mode ;; https://golang.org/ref/spec#Keywords, https://golang.org/pkg/builtin/
175 | "append" "bool" "break" "byte" "cap" "case" "chan" "close" "complex"
176 | "complex128" "complex64" "const" "continue" "copy" "default" "defer"
177 | "delete" "else" "error" "fallthrough" "false" "float32" "float64" "for"
178 | "func" "go" "goto" "if" "imag" "import" "int" "int16" "int32" "int64"
179 | "int8" "interface" "len" "make" "map" "new" "nil" "package" "panic" "print"
180 | "println" "range" "real" "recover" "return" "rune" "select" "string"
181 | "struct" "switch" "true" "type" "uint" "uint16" "uint32" "uint64" "uint8"
182 | "uintptr" "var")
183 | (java-mode
184 | "abstract" "assert" "boolean" "break" "byte" "case" "catch" "char" "class"
185 | "continue" "default" "do" "double" "else" "enum" "extends" "final"
186 | "finally" "float" "for" "if" "implements" "import" "instanceof" "int"
187 | "interface" "long" "native" "new" "package" "private" "protected" "public"
188 | "return" "short" "static" "strictfp" "super" "switch" "synchronized" "this"
189 | "throw" "throws" "transient" "try" "void" "volatile" "while")
190 | (javascript-mode ;; https://tc39.github.io/ecma262/
191 | "async" "await" "break" "case" "catch" "class" "const" "continue"
192 | "debugger" "default" "delete" "do" "else" "enum" "export" "extends" "false"
193 | "finally" "for" "function" "if" "import" "in" "instanceof" "let" "new"
194 | "null" "return" "static" "super" "switch" "this" "throw" "true" "try"
195 | "typeof" "undefined" "var" "void" "while" "with" "yield")
196 | (kotlin-mode
197 | "abstract" "annotation" "as" "break" "by" "catch" "class" "companion"
198 | "const" "constructor" "continue" "data" "do" "else" "enum" "false" "final"
199 | "finally" "for" "fun" "if" "import" "in" "init" "inner" "interface"
200 | "internal" "is" "lateinit" "nested" "null" "object" "open" "out" "override"
201 | "package" "private" "protected" "public" "return" "super" "this" "throw"
202 | "trait" "true" "try" "typealias" "val" "var" "when" "while")
203 | (lua-mode ;; https://www.lua.org/manual/5.3/manual.html
204 | "and" "break" "do" "else" "elseif" "end" "false" "for" "function" "goto"
205 | "if" "in" "local" "nil" "not" "or" "repeat" "return" "then" "true" "until"
206 | "while")
207 | (nim-mode ;; https://nim-lang.org/docs/manual.html#lexical-analysis-identifiers-amp-keywords
208 | "addr" "and" "as" "asm" "bind" "block" "break" "case" "cast" "concept"
209 | "const" "continue" "converter" "defer" "discard" "distinct" "div" "do"
210 | "elif" "else" "end" "enum" "except" "export" "finally" "for" "from" "func"
211 | "if" "import" "in" "include" "interface" "is" "isnot" "iterator" "let"
212 | "macro" "method" "mixin" "mod" "nil" "not" "notin" "object" "of" "or" "out"
213 | "proc" "ptr" "raise" "ref" "return" "shl" "shr" "static" "template" "try"
214 | "tuple" "type" "using" "var" "when" "while" "xor" "yield")
215 | (objc-mode
216 | "@catch" "@class" "@encode" "@end" "@finally" "@implementation"
217 | "@interface" "@private" "@protected" "@protocol" "@public" "@selector"
218 | "@synchronized" "@throw" "@try" "alloc" "autorelease" "bycopy" "byref" "in"
219 | "inout" "oneway" "out" "release" "retain")
220 | (perl-mode ;; cperl.el
221 | "AUTOLOAD" "BEGIN" "CHECK" "CORE" "DESTROY" "END" "INIT" "__END__"
222 | "__FILE__" "__LINE__" "abs" "accept" "alarm" "and" "atan2" "bind" "binmode"
223 | "bless" "caller" "chdir" "chmod" "chomp" "chop" "chown" "chr" "chroot"
224 | "close" "closedir" "cmp" "connect" "continue" "cos" "crypt" "dbmclose"
225 | "dbmopen" "defined" "delete" "die" "do" "dump" "each" "else" "elsif"
226 | "endgrent" "endhostent" "endnetent" "endprotoent" "endpwent" "endservent"
227 | "eof" "eq" "eval" "exec" "exists" "exit" "exp" "fcntl" "fileno" "flock"
228 | "for" "foreach" "fork" "format" "formline" "ge" "getc" "getgrent"
229 | "getgrgid" "getgrnam" "gethostbyaddr" "gethostbyname" "gethostent"
230 | "getlogin" "getnetbyaddr" "getnetbyname" "getnetent" "getpeername"
231 | "getpgrp" "getppid" "getpriority" "getprotobyname" "getprotobynumber"
232 | "getprotoent" "getpwent" "getpwnam" "getpwuid" "getservbyname"
233 | "getservbyport" "getservent" "getsockname" "getsockopt" "glob" "gmtime"
234 | "goto" "grep" "gt" "hex" "if" "index" "int" "ioctl" "join" "keys" "kill"
235 | "last" "lc" "lcfirst" "le" "length" "link" "listen" "local" "localtime"
236 | "lock" "log" "lstat" "lt" "map" "mkdir" "msgctl" "msgget" "msgrcv" "msgsnd"
237 | "my" "ne" "next" "no" "not" "oct" "open" "opendir" "or" "ord" "our" "pack"
238 | "package" "pipe" "pop" "pos" "print" "printf" "push" "q" "qq" "quotemeta"
239 | "qw" "qx" "rand" "read" "readdir" "readline" "readlink" "readpipe" "recv"
240 | "redo" "ref" "rename" "require" "reset" "return" "reverse" "rewinddir"
241 | "rindex" "rmdir" "scalar" "seek" "seekdir" "select" "semctl" "semget"
242 | "semop" "send" "setgrent" "sethostent" "setnetent" "setpgrp" "setpriority"
243 | "setprotoent" "setpwent" "setservent" "setsockopt" "shift" "shmctl"
244 | "shmget" "shmread" "shmwrite" "shutdown" "sin" "sleep" "socket"
245 | "socketpair" "sort" "splice" "split" "sprintf" "sqrt" "srand" "stat"
246 | "study" "sub" "substr" "symlink" "syscall" "sysopen" "sysread" "system"
247 | "syswrite" "tell" "telldir" "tie" "time" "times" "tr" "truncate" "uc"
248 | "ucfirst" "umask" "undef" "unless" "unlink" "unpack" "unshift" "untie"
249 | "until" "use" "utime" "values" "vec" "wait" "waitpid" "wantarray" "warn"
250 | "while" "write" "x" "xor" "y")
251 | (php-mode ;; https://www.php.net/manual/reserved.php
252 | "Closure" "Error" "Exception" "Generator" "Throwable" "__CLASS__" "__DIR__"
253 | "__FILE__" "__FUNCTION__" "__LINE__" "__METHOD__" "__NAMESPACE__"
254 | "__TRAIT__" "abstract" "and" "array" "as" "bool" "break" "callable" "case"
255 | "catch" "class" "clone" "const" "continue" "declare" "default" "die" "do"
256 | "echo" "else" "elseif" "empty" "enddeclare" "endfor" "endforeach" "endif"
257 | "endswitch" "endwhile" "enum" "eval" "exit" "extends" "false" "final"
258 | "finally" "float" "fn" "for" "foreach" "function" "global" "goto" "if"
259 | "implements" "include" "include_once" "instanceof" "insteadof" "interface"
260 | "isset" "iterable" "list" "match" "namespace" "new" "null" "object" "or"
261 | "print" "private" "protected" "public" "readonly" "require" "require_once"
262 | "return" "self" "static" "string" "switch" "this" "throw" "trait" "true"
263 | "try" "unset" "use" "var" "void" "while" "xor" "yield" "yield from")
264 | (purescript-mode ;; purescript-font-lock.el
265 | "ado" "case" "class" "data" "default" "deriving" "do" "else" "if" "import"
266 | "in" "infix" "infixl" "infixr" "instance" "let" "module" "newtype" "of"
267 | "then" "type" "where")
268 | (python-mode ;; https://docs.python.org/3/reference/lexical_analysis.html#keywords
269 | "False" "None" "True" "and" "as" "assert" "async" "await" "break" "case"
270 | "class" "continue" "def" "del" "elif" "else" "except" "exec" "finally"
271 | "for" "from" "global" "if" "import" "in" "is" "lambda" "match" "nonlocal"
272 | "not" "or" "pass" "print" "raise" "return" "try" "while" "with" "yield")
273 | (ruby-mode
274 | "BEGIN" "END" "alias" "and" "begin" "break" "case" "class" "def" "defined?"
275 | "do" "else" "elsif" "end" "ensure" "false" "for" "if" "in" "module" "next"
276 | "nil" "not" "or" "redo" "rescue" "retry" "return" "self" "super" "then"
277 | "true" "undef" "unless" "until" "when" "while" "yield")
278 | (rust-mode ;; https://doc.rust-lang.org/grammar.html#keywords
279 | "Self" "as" "box" "break" "const" "continue" "crate" "else" "enum" "extern"
280 | "false" "fn" "for" "if" "impl" "in" "let" "loop" "macro" "match" "mod"
281 | "move" "mut" "pub" "ref" "return" "self" "static" "struct" "super" "trait"
282 | "true" "type" "unsafe" "use" "where" "while")
283 | (scala-mode
284 | "abstract" "case" "catch" "class" "def" "do" "else" "extends" "false"
285 | "final" "finally" "for" "forSome" "if" "implicit" "import" "lazy" "match"
286 | "new" "null" "object" "override" "package" "private" "protected" "return"
287 | "sealed" "super" "this" "throw" "trait" "true" "try" "type" "val" "var"
288 | "while" "with" "yield")
289 | (scheme-mode ;; R7RS-small: https://small.r7rs.org/
290 | "abs" "acos" "angle" "append" "apply" "asin" "assoc" "assq" "assv" "atan"
291 | "binary-port?" "body" "boolean=?" "boolean?" "bytevector"
292 | "bytevector-append" "bytevector-copy" "bytevector-copy!"
293 | "bytevector-length" "bytevector-u8-ref" "bytevector-u8-set!" "bytevector?"
294 | "caaaar" "caaadr" "caaar" "caadar" "caaddr" "caadr" "caar" "cadaar"
295 | "cadadr" "cadar" "caddar" "cadddr" "caddr" "cadr" "call-with-port"
296 | "call-with-values" "car" "car-internal" "cdaaar" "cdaadr" "cdaar" "cdadar"
297 | "cdaddr" "cdadr" "cdar" "cddaar" "cddadr" "cddar" "cdddar" "cddddr" "cdddr"
298 | "cddr" "cdr" "ceiling" "char->integer" "char-alphabetic?" "char-ci<=?"
299 | "char-ci" "char-ci=?" "char-ci>=?" "char-ci>?" "char-downcase"
300 | "char-foldcase" "char-lower-case?" "char-numeric?" "char-ready?"
301 | "char-upcase" "char-upper-case?" "char-whitespace?" "char<=?" "char"
302 | "char=?" "char>=?" "char>?" "char?" "close-input-port" "close-output-port"
303 | "close-port" "command-line" "complex?" "cons" "cos" "current-error-port"
304 | "current-input-port" "current-jiffy" "current-output-port" "current-second"
305 | "delete-file" "denominator" "digit-value" "display" "dynamic-wind"
306 | "emergency-exit" "environment" "eof-object" "eof-object?" "eq?" "equal?"
307 | "eqv?" "error" "error-object-irritants" "error-object-message"
308 | "error-object?" "eval" "even?" "exact" "exact-integer-sqrt"
309 | "exact-integer?" "exact?" "exit" "exp" "expt" "features" "file-error?"
310 | "file-exists?" "finite?" "floor" "floor-quotient" "floor-remainder"
311 | "floor/" "flush-output-port" "gcd" "get-environment-variable"
312 | "get-environment-variables" "get-output-bytevector" "get-output-string"
313 | "imag-part" "inexact" "inexact?" "infinite?" "input-port-open?"
314 | "input-port?" "integer->char" "integer?" "interaction-environment"
315 | "jiffies-per-second" "lcm" "length" "list" "list->string" "list->vector"
316 | "list-copy" "list-ref" "list-set!" "list-tail" "list?" "load" "log"
317 | "magnitude" "make-bytevector" "make-list" "make-parameter" "make-polar"
318 | "make-promise" "make-rectangular" "make-string" "make-vector" "max"
319 | "member" "memq" "memv" "min" "modulo" "nan?" "negative?" "newline" "nil"
320 | "not" "null-environment" "null?" "number->string" "number?" "numerator"
321 | "odd?" "open-binary-input-file" "open-binary-output-file"
322 | "open-input-bytevector" "open-input-file" "open-input-string"
323 | "open-output-bytevector" "open-output-file" "open-output-string"
324 | "output-port-open?" "output-port?" "pair?" "peek-char" "peek-u8" "port?"
325 | "positive?" "procedure?" "promise?" "quasiquote" "quote" "quotient" "raise"
326 | "raise-continuable" "rational?" "rationalize" "read" "read-bytevector"
327 | "read-bytevector!" "read-char" "read-error?" "read-line" "read-string"
328 | "read-u8" "real-part" "real?" "remainder" "reverse" "round"
329 | "scheme-report-environment" "set!" "set-car!" "set-cdr!" "setcar" "sin"
330 | "sqrt" "square" "string" "string->list" "string->number" "string->symbol"
331 | "string->utf" "string->vector" "string-append" "string-ci<=?" "string-ci"
332 | "string-ci=?" "string-ci>=?" "string-ci>?" "string-copy" "string-copy!"
333 | "string-downcase" "string-fill!" "string-foldcase" "string-for-each"
334 | "string-length" "string-map" "string-ref" "string-set!" "string-upcase"
335 | "string<=?" "string" "string=?" "string>=?" "string>?" "string?"
336 | "substring" "symbol->string" "symbol=?" "symbol?" "tan" "textual-port?"
337 | "truncate" "truncate-quotient" "truncate-remainder" "truncate/" "u8-ready?"
338 | "unquote" "unquote-splicing" "utf->string" "values" "vector" "vector->list"
339 | "vector->string" "vector-append" "vector-copy" "vector-copy!"
340 | "vector-fill!" "vector-for-each" "vector-length" "vector-map" "vector-ref"
341 | "vector-set!" "vector?" "with-exception-handler" "with-input-from-file"
342 | "with-output-to-file" "write" "write-bytevector" "write-char"
343 | "write-shared" "write-simple" "write-string" "write-u8" "zero?")
344 | (swift-mode
345 | "Protocol" "Self" "Type" "and" "as" "assignment" "associatedtype"
346 | "associativity" "available" "break" "case" "catch" "class" "column"
347 | "continue" "convenience" "default" "defer" "deinit" "didSet" "do" "dynamic"
348 | "dynamicType" "else" "elseif" "endif" "enum" "extension" "fallthrough"
349 | "false" "file" "fileprivate" "final" "for" "func" "function" "get" "guard"
350 | "higherThan" "if" "import" "in" "indirect" "infix" "init" "inout"
351 | "internal" "is" "lazy" "left" "let" "line" "lowerThan" "mutating" "nil"
352 | "none" "nonmutating" "open" "operator" "optional" "override" "postfix"
353 | "precedence" "precedencegroup" "prefix" "private" "protocol" "public"
354 | "repeat" "required" "rethrows" "return" "right" "selector" "self" "set"
355 | "static" "struct" "subscript" "super" "switch" "throw" "throws" "true"
356 | "try" "typealias" "unowned" "var" "weak" "where" "while" "willSet")
357 | (julia-mode
358 | "abstract" "break" "case" "catch" "const" "continue" "do" "else" "elseif"
359 | "end" "eval" "export" "false" "finally" "for" "function" "global" "if"
360 | "ifelse" "immutable" "import" "importall" "in" "let" "macro" "module"
361 | "otherwise" "quote" "return" "switch" "throw" "true" "try" "type"
362 | "typealias" "using" "while")
363 | (thrift-mode ;; https://github.com/apache/thrift/blob/master/contrib/thrift.el
364 | "binary" "bool" "byte" "const" "double" "enum" "exception" "extends" "i16"
365 | "i32" "i64" "include" "list" "map" "oneway" "optional" "required" "service"
366 | "set" "string" "struct" "throws" "typedef" "void")
367 | (sh-mode
368 | "break" "case" "continue" "do" "done" "elif" "else" "esac" "eval"
369 | "exec" "exit" "export" "false" "fi" "for" "function" "if" "in" "readonly"
370 | "return" "set" "shift" "test" "then" "time" "times" "trap" "true" "unset"
371 | "until" "while")
372 | ;; Aliases
373 | (cperl-mode perl-mode)
374 | (enh-ruby-mode ruby-mode)
375 | (espresso-mode javascript-mode)
376 | (ess-julia-mode julia-mode)
377 | (jde-mode java-mode)
378 | (js-jsx-mode javascript-mode)
379 | (js-mode javascript-mode)
380 | (js2-jsx-mode javascript-mode)
381 | (js2-mode javascript-mode)
382 | (php-ts-mode php-mode)
383 | (phps-mode php-mode)
384 | (rjsx-mode javascript-mode)
385 | (tuareg-mode caml-mode)
386 | ;; Emacs 29 treesitter modes
387 | (c++-ts-mode c++-mode)
388 | (c-ts-mode c-mode)
389 | (csharp-ts-mode csharp-mode)
390 | (css-ts-mode css-mode)
391 | (elixir-ts-mode elixir-mode)
392 | (go-ts-mode go-mode)
393 | (java-ts-mode java-mode)
394 | (js-ts-mode javascript-mode)
395 | (lua-ts-mode lua-mode)
396 | (python-ts-mode python-mode)
397 | (ruby-ts-mode ruby-mode)
398 | (rust-ts-mode rust-mode)
399 | (bash-ts-mode sh-mode))
400 | "Alist of major modes and keywords."
401 | :type 'alist
402 | :group 'cape)
403 |
404 | (defun cape--keyword-list ()
405 | "Return keywords for current major mode."
406 | (when-let ((kw (or (alist-get major-mode cape-keyword-list)
407 | (when-let ((remap (rassq major-mode major-mode-remap-alist)))
408 | (alist-get (car remap) cape-keyword-list)))))
409 | (if (symbolp (car kw)) (alist-get (car kw) cape-keyword-list) kw)))
410 |
411 | (defvar cape--keyword-properties
412 | (list :annotation-function (lambda (_) " Keyword")
413 | :company-kind (lambda (_) 'keyword)
414 | :exclusive 'no
415 | :category 'cape-keyword)
416 | "Completion extra properties for `cape-keyword'.")
417 |
418 | ;;;###autoload
419 | (defun cape-keyword (&optional interactive)
420 | "Complete programming language keyword at point.
421 | See the variable `cape-keyword-list'.
422 | If INTERACTIVE is nil the function acts like a capf."
423 | (interactive (list t))
424 | (if interactive
425 | (cape-interactive #'cape-keyword)
426 | (when-let (keywords (cape--keyword-list))
427 | (let ((bounds (cape--bounds 'symbol)))
428 | `(,(car bounds) ,(cdr bounds) ,keywords ,@cape--keyword-properties)))))
429 |
430 | (provide 'cape-keyword)
431 | ;;; cape-keyword.el ends here
432 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/cape.el:
--------------------------------------------------------------------------------
1 | ;;; cape.el --- Completion At Point Extensions -*- lexical-binding: t -*-
2 |
3 | ;; Copyright (C) 2021-2025 Free Software Foundation, Inc.
4 |
5 | ;; Author: Daniel Mendler
6 | ;; Maintainer: Daniel Mendler
7 | ;; Created: 2021
8 | ;; Version: 2.4
9 | ;; Package-Requires: ((emacs "29.1") (compat "30"))
10 | ;; URL: 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 .
27 |
28 | ;;; Commentary:
29 |
30 | ;; Let your completions fly! This package provides additional completion
31 | ;; backends in the form of Capfs, see `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 "Website" "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 "Disable" nil)
80 | (const :tag "Use `case-replace'" case-replace)
81 | (other :tag "Enable" 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 "Disable" nil)
87 | (const :tag "Use `case-fold-search'" case-fold-search)
88 | (other :tag "Enable" t)))
89 |
90 | (defcustom cape-dabbrev-buffer-function #'cape-same-mode-buffers
91 | "Function which returns list of buffers.
92 | The buffers are scanned for completion candidates by `cape-dabbrev'."
93 | :type `(choice (const :tag "Current buffer" current-buffer)
94 | (const :tag "Text buffers" ,#'cape-text-buffers)
95 | (const :tag "Buffers with same mode" ,#'cape-same-mode-buffers)
96 | (function :tag "Custom function")))
97 |
98 | (defcustom cape-file-directory nil
99 | "Base directory used by `cape-file."
100 | :type '(choice (const nil) string function))
101 |
102 | (defcustom cape-file-prefix "file:"
103 | "File completion trigger prefixes.
104 | The value can be a string or a list of strings. The default
105 | `file:' is the prefix of Org file links which work in arbitrary
106 | buffers via `org-open-at-point-global'."
107 | :type '(choice string (repeat string)))
108 |
109 | (defcustom cape-file-directory-must-exist t
110 | "The parent directory must exist for file completion."
111 | :type 'boolean)
112 |
113 | (defcustom cape-line-buffer-function #'cape-same-mode-buffers
114 | "Function which returns list of buffers.
115 | The buffers are scanned for completion candidates by `cape-line'."
116 | :type `(choice (const :tag "Current buffer" current-buffer)
117 | (const :tag "Text buffers" ,#'cape-text-buffers)
118 | (const :tag "Buffers with same mode" ,#'cape-same-mode-buffers)
119 | (function :tag "Custom function")))
120 |
121 | (defcustom cape-elisp-symbol-wrapper
122 | '((org-mode ?~ ?~)
123 | (markdown-mode ?` ?`)
124 | (emacs-lisp-mode ?` ?')
125 | (rst-mode "``" "``")
126 | (log-edit-mode "`" "'")
127 | (change-log-mode "`" "'")
128 | (message-mode "`" "'")
129 | (rcirc-mode "`" "'"))
130 | "Wrapper characters for symbols."
131 | :type '(alist :key-type symbol :value-type (list (choice character string)
132 | (choice character string))))
133 |
134 | ;;;; Helpers
135 |
136 | (defun cape--buffer-list (pred)
137 | "Return list of buffers satisfying PRED."
138 | (let* ((cur (current-buffer))
139 | (orig (and (minibufferp) (window-buffer (minibuffer-selected-window))))
140 | (list (cl-loop for buf in (buffer-list)
141 | if (and (not (eq buf cur)) (not (eq buf orig))
142 | (funcall pred buf))
143 | collect buf)))
144 | `(,cur ,@(and orig (list orig)) ,@list)))
145 |
146 | (defun cape-same-mode-buffers ()
147 | "Return buffers with same major mode as current buffer."
148 | (cape--buffer-list
149 | (lambda (buf) (eq major-mode (buffer-local-value 'major-mode buf)))))
150 |
151 | (defun cape-text-buffers ()
152 | "Return `text-mode' and `prog-mode' buffers."
153 | (cape--buffer-list
154 | (lambda (buf)
155 | (let ((mode (buffer-local-value 'major-mode buf)))
156 | (or (provided-mode-derived-p mode #'text-mode)
157 | (provided-mode-derived-p mode #'prog-mode))))))
158 |
159 | (defun cape--case-fold-p (fold)
160 | "Return non-nil if case folding is enabled for FOLD."
161 | (if (eq fold 'case-fold-search) case-fold-search fold))
162 |
163 | (defun cape--case-replace-list (flag input strs)
164 | "Replace case of STRS depending on INPUT and FLAG."
165 | (if (and (if (eq flag 'case-replace) case-replace flag)
166 | (let (case-fold-search) (string-match-p "\\`[[:upper:]]" input)))
167 | (mapcar (apply-partially #'cape--case-replace flag input) strs)
168 | strs))
169 |
170 | (defun cape--case-replace (flag input str)
171 | "Replace case of STR depending on INPUT and FLAG."
172 | (or (and (if (eq flag 'case-replace) case-replace flag)
173 | (string-prefix-p input str t)
174 | (let (case-fold-search) (string-match-p "\\`[[:upper:]]" input))
175 | (save-match-data
176 | ;; Ensure that single character uppercase input does not lead to an
177 | ;; all uppercase result.
178 | (when (and (= (length input) 1) (> (length str) 1))
179 | (setq input (concat input (substring str 1 2))))
180 | (and (string-match input input)
181 | (replace-match str nil nil input))))
182 | str))
183 |
184 | (defun cape--separator-p (str)
185 | "Return non-nil if input STR has a separator character.
186 | Separator characters are used by completion styles like Orderless
187 | to split filter words. In Corfu, the separator is configurable
188 | via the variable `corfu-separator'."
189 | (string-search (string ;; Support `corfu-separator' and Orderless
190 | (or (and (bound-and-true-p corfu-mode)
191 | (bound-and-true-p corfu-separator))
192 | ?\s))
193 | str))
194 |
195 | (defmacro cape--silent (&rest body)
196 | "Silence BODY."
197 | (declare (indent 0))
198 | `(cl-letf ((inhibit-message t)
199 | (message-log-max nil)
200 | ((symbol-function #'minibuffer-message) #'ignore))
201 | (ignore-errors ,@body)))
202 |
203 | (defun cape--bounds (thing)
204 | "Return bounds of THING."
205 | (or (bounds-of-thing-at-point thing) (cons (point) (point))))
206 |
207 | (defmacro cape--wrapped-table (wrap body)
208 | "Create wrapped completion table, handle `completion--unquote'.
209 | WRAP is the wrapper function.
210 | BODY is the wrapping expression."
211 | (declare (indent 1))
212 | `(lambda (str pred action)
213 | (,@body
214 | (let ((result (complete-with-action action table str pred)))
215 | (when (and (eq action 'completion--unquote) (functionp (cadr result)))
216 | (cl-callf ,wrap (cadr result)))
217 | result))))
218 |
219 | (defun cape--accept-all-table (table)
220 | "Create completion TABLE which accepts all input."
221 | (cape--wrapped-table cape--accept-all-table
222 | (or (eq action 'lambda))))
223 |
224 | (defun cape--passthrough-table (table)
225 | "Create completion TABLE disabling any filtering."
226 | (cape--wrapped-table cape--passthrough-table
227 | (let (completion-ignore-case completion-regexp-list (_ (setq str ""))))))
228 |
229 | (defun cape--noninterruptible-table (table)
230 | "Create non-interruptible completion TABLE."
231 | (cape--wrapped-table cape--noninterruptible-table
232 | (let (throw-on-input))))
233 |
234 | (defun cape--silent-table (table)
235 | "Create a new completion TABLE which is silent (no messages, no errors)."
236 | (cape--wrapped-table cape--silent-table
237 | (cape--silent)))
238 |
239 | (defun cape--nonessential-table (table)
240 | "Mark completion TABLE as `non-essential'."
241 | (let ((dir default-directory))
242 | (cape--wrapped-table cape--nonessential-table
243 | (let ((default-directory dir)
244 | (non-essential t))))))
245 |
246 | (defvar cape--debug-length 5
247 | "Length of printed lists in `cape--debug-print'.")
248 |
249 | (defvar cape--debug-id 0
250 | "Completion table identifier.")
251 |
252 | (defun cape--debug-message (&rest msg)
253 | "Print debug MSG."
254 | (let ((inhibit-message t))
255 | (apply #'message msg)))
256 |
257 | (defun cape--debug-print (obj &optional full)
258 | "Print OBJ as string, truncate lists if FULL is nil."
259 | (cond
260 | ((symbolp obj) (symbol-name obj))
261 | ((functionp obj) "#")
262 | ((proper-list-p obj)
263 | (concat
264 | "("
265 | (string-join
266 | (mapcar #'cape--debug-print
267 | (if full obj (take cape--debug-length obj)))
268 | " ")
269 | (if (and (not full) (length> obj cape--debug-length)) " ...)" ")")))
270 | (t (let ((print-level 2))
271 | (prin1-to-string obj)))))
272 |
273 | (defun cape--debug-table (table name beg end)
274 | "Create completion TABLE with debug messages.
275 | NAME is the name of the Capf, BEG and END are the input markers."
276 | (lambda (str pred action)
277 | (let ((result (complete-with-action action table str pred)))
278 | (if (and (eq action 'completion--unquote) (functionp (cadr result)))
279 | ;; See `cape--wrapped-table'
280 | (cl-callf cape--debug-table (cadr result) name beg end)
281 | (cape--debug-message
282 | "%s(action=%S input=%s:%s:%S prefix=%S ignore-case=%S%s%s) => %s"
283 | name
284 | (pcase action
285 | ('nil 'try)
286 | ('t 'all)
287 | ('lambda 'test)
288 | (_ action))
289 | (+ beg 0) (+ end 0) (buffer-substring-no-properties beg end)
290 | str completion-ignore-case
291 | (if completion-regexp-list
292 | (concat " regexp=" (cape--debug-print completion-regexp-list t))
293 | "")
294 | (if pred
295 | (concat " predicate=" (cape--debug-print pred))
296 | "")
297 | (cape--debug-print result)))
298 | result)))
299 |
300 | (defun cape--dynamic-table (beg end fun)
301 | "Create dynamic completion table from FUN with caching.
302 | BEG and END are the input bounds. FUN is the function which
303 | computes the candidates. FUN must return a pair of a predicate
304 | function function and the list of candidates. The predicate is
305 | passed new input and must return non-nil if the candidates are
306 | still valid.
307 |
308 | It is only necessary to use this function if the set of
309 | candidates is computed dynamically based on the input and not
310 | statically determined. The behavior is similar but slightly
311 | different to `completion-table-dynamic'.
312 |
313 | The difference to the builtins `completion-table-dynamic' and
314 | `completion-table-with-cache' is that this function does not use
315 | the prefix argument of the completion table to compute the
316 | candidates. Instead it uses the input in the buffer between BEG
317 | and END to FUN to compute the candidates. This way the dynamic
318 | candidate computation is compatible with non-prefix completion
319 | styles like `substring' or `orderless', which pass the empty
320 | string as first argument to the completion table."
321 | (let ((beg (copy-marker beg))
322 | (end (copy-marker end t))
323 | valid table)
324 | (lambda (str pred action)
325 | ;; Bail out early for `metadata' and `boundaries'. This is a pointless
326 | ;; move because of caching, but we do it anyway in the hope that the
327 | ;; profiler report looks less confusing, since the weight of the expensive
328 | ;; FUN computation is moved to the `all-completions' action. Computing
329 | ;; `all-completions' must surely be most expensive, so nobody will suspect
330 | ;; a thing.
331 | (unless (or (eq action 'metadata) (eq (car-safe action) 'boundaries))
332 | (let ((input (buffer-substring-no-properties beg end)))
333 | (unless (and valid
334 | (or (cape--separator-p input)
335 | (funcall valid input)))
336 | (let* (;; Reset in case `all-completions' is used inside FUN
337 | completion-ignore-case completion-regexp-list
338 | ;; Retrieve new state by calling FUN
339 | (new (and (< beg end) (funcall fun input)))
340 | ;; No interrupt during state update
341 | throw-on-input)
342 | (setq valid (car new) table (cdr new)))))
343 | (complete-with-action action table str pred)))))
344 |
345 | ;;;; Capfs
346 |
347 | ;;;;; cape-history
348 |
349 | (declare-function ring-elements "ring")
350 | (declare-function eshell-bol "eshell")
351 | (declare-function comint-line-beginning-position "comint")
352 | (defvar eshell-history-ring)
353 | (defvar comint-input-ring)
354 |
355 | (defvar cape--history-properties
356 | (list :company-kind (lambda (_) 'text)
357 | :exclusive 'no
358 | :display-sort-function #'identity
359 | :cycle-sort-function #'identity
360 | :category 'cape-history)
361 | "Completion extra properties for `cape-history'.")
362 |
363 | ;;;###autoload
364 | (defun cape-history (&optional interactive)
365 | "Complete from Eshell, Comint or minibuffer history.
366 | See also `consult-history' for a more flexible variant based on
367 | `completing-read'. If INTERACTIVE is nil the function acts like a Capf."
368 | (interactive (list t))
369 | (if interactive
370 | (cape-interactive #'cape-history)
371 | (let (history bol)
372 | (cond
373 | ((derived-mode-p 'eshell-mode)
374 | (setq history eshell-history-ring
375 | bol (static-if (< emacs-major-version 30)
376 | (save-excursion (eshell-bol) (point))
377 | (line-beginning-position))))
378 | ((derived-mode-p 'comint-mode)
379 | (setq history comint-input-ring
380 | bol (comint-line-beginning-position)))
381 | ((and (minibufferp) (not (eq minibuffer-history-variable t)))
382 | (setq history (symbol-value minibuffer-history-variable)
383 | bol (line-beginning-position))))
384 | (when (ring-p history)
385 | (setq history (ring-elements history)))
386 | (when history
387 | `(,bol ,(point) ,history ,@cape--history-properties)))))
388 |
389 | ;;;;; cape-file
390 |
391 | (defvar comint-unquote-function)
392 | (defvar comint-requote-function)
393 |
394 | (defvar cape--file-properties
395 | (list :annotation-function (lambda (s) (if (string-suffix-p "/" s) " Dir" " File"))
396 | :company-kind (lambda (s) (if (string-suffix-p "/" s) 'folder 'file))
397 | :exclusive 'no
398 | :category 'file)
399 | "Completion extra properties for `cape-file'.")
400 |
401 | ;;;###autoload
402 | (defun cape-file (&optional interactive)
403 | "Complete file name at point.
404 | See the user option `cape-file-directory-must-exist'.
405 | If INTERACTIVE is nil the function acts like a Capf."
406 | (interactive (list t))
407 | (if interactive
408 | (cape-interactive '(cape-file-directory-must-exist) #'cape-file)
409 | (pcase-let* ((default-directory (pcase cape-file-directory
410 | ('nil default-directory)
411 | ((pred stringp) cape-file-directory)
412 | (_ (funcall cape-file-directory))))
413 | (prefix (and cape-file-prefix
414 | (looking-back
415 | (concat
416 | (regexp-opt (ensure-list cape-file-prefix) t)
417 | "[^ \n\t]*")
418 | (pos-bol))
419 | (match-end 1)))
420 | (`(,beg . ,end) (if prefix
421 | (cons prefix (point))
422 | (cape--bounds 'filename)))
423 | (non-essential t)
424 | (file (buffer-substring-no-properties beg end)))
425 | (when (or prefix
426 | (not cape-file-directory-must-exist)
427 | (and (string-search "/" file)
428 | (file-exists-p (file-name-directory
429 | (substitute-in-file-name file)))))
430 | (unless (boundp 'comint-unquote-function)
431 | (require 'comint))
432 | (let ((table (cape--nonessential-table
433 | (completion-table-with-quoting
434 | #'read-file-name-internal
435 | comint-unquote-function
436 | comint-requote-function))))
437 | `( ,beg ,end ,table
438 | :company-location
439 | ,(lambda (file)
440 | (let* ((str (buffer-substring-no-properties beg (point)))
441 | (pre (car (completion-boundaries str table nil "")))
442 | (file (file-name-concat (substring str 0 pre) file)))
443 | (and (file-exists-p file) (list file))))
444 | ,@(when (or prefix (string-match-p "./" file))
445 | '(:company-prefix-length t))
446 | ,@cape--file-properties))))))
447 |
448 | ;;;;; cape-elisp-symbol
449 |
450 | (autoload 'elisp--company-kind "elisp-mode")
451 | (autoload 'elisp--company-doc-buffer "elisp-mode")
452 | (autoload 'elisp--company-doc-string "elisp-mode")
453 | (autoload 'elisp--company-location "elisp-mode")
454 |
455 | (defvar cape--elisp-symbol-properties
456 | (list :annotation-function #'cape--elisp-symbol-annotation
457 | :exit-function #'cape--elisp-symbol-exit
458 | :predicate #'cape--elisp-symbol-predicate
459 | :company-kind #'elisp--company-kind
460 | :company-doc-buffer #'elisp--company-doc-buffer
461 | :company-docsig #'elisp--company-doc-string
462 | :company-location #'elisp--company-location
463 | :exclusive 'no
464 | :category 'symbol)
465 | "Completion extra properties for `cape-elisp-symbol'.")
466 |
467 | (defun cape--elisp-symbol-predicate (sym)
468 | "Return t if SYM is bound, fbound or propertized."
469 | (or (fboundp sym) (boundp sym) (symbol-plist sym)))
470 |
471 | (defun cape--elisp-symbol-exit (sym status)
472 | "Wrap symbol SYM with `cape-elisp-symbol-wrapper' buffers.
473 | STATUS is the exit status."
474 | (when-let (((not (eq status 'exact)))
475 | (c (cl-loop for (m . c) in cape-elisp-symbol-wrapper
476 | if (derived-mode-p m) return c))
477 | ((or (not (derived-mode-p 'emacs-lisp-mode))
478 | ;; Inside comment or string
479 | (let ((s (syntax-ppss))) (or (nth 3 s) (nth 4 s)))))
480 | (x (if (stringp (car c)) (car c) (string (car c))))
481 | (y (if (stringp (cadr c)) (cadr c) (string (cadr c)))))
482 | (save-excursion
483 | (backward-char (length sym))
484 | (unless (save-excursion
485 | (and (ignore-errors (or (backward-char (length x)) t))
486 | (looking-at-p (regexp-quote x))))
487 | (insert x)))
488 | (unless (looking-at-p (regexp-quote y))
489 | (insert y))))
490 |
491 | (defun cape--elisp-symbol-annotation (sym)
492 | "Return kind of SYM."
493 | (setq sym (intern-soft sym))
494 | (cond
495 | ((special-form-p sym) " Special")
496 | ((macrop sym) " Macro")
497 | ((commandp sym) " Command")
498 | ((fboundp sym) " Function")
499 | ((custom-variable-p sym) " Custom")
500 | ((boundp sym) " Variable")
501 | ((featurep sym) " Feature")
502 | ((facep sym) " Face")
503 | (t " Symbol")))
504 |
505 | ;;;###autoload
506 | (defun cape-elisp-symbol (&optional interactive)
507 | "Complete Elisp symbol at point.
508 | If INTERACTIVE is nil the function acts like a Capf."
509 | (interactive (list t))
510 | (if interactive
511 | ;; No cycling since it breaks the :exit-function.
512 | (let (completion-cycle-threshold)
513 | (cape-interactive #'cape-elisp-symbol))
514 | (pcase-let ((`(,beg . ,end) (cape--bounds 'symbol)))
515 | (when (eq (char-after beg) ?')
516 | (setq beg (1+ beg) end (max beg end)))
517 | `(,beg ,end ,obarray ,@cape--elisp-symbol-properties))))
518 |
519 | ;;;;; cape-elisp-block
520 |
521 | (declare-function org-element-context "org-element")
522 | (declare-function markdown-code-block-lang "ext:markdown-mode")
523 |
524 | (defun cape--inside-block-p (&rest langs)
525 | "Return non-nil if inside LANGS code block."
526 | (when-let ((face (get-text-property (point) 'face))
527 | (lang (or (and (if (listp face)
528 | (memq 'org-block face)
529 | (eq 'org-block face))
530 | (plist-get (cadr (org-element-context)) :language))
531 | (and (if (listp face)
532 | (memq 'markdown-code-face face)
533 | (eq 'markdown-code-face face))
534 | (save-excursion
535 | (markdown-code-block-lang))))))
536 | (member lang langs)))
537 |
538 | ;;;###autoload
539 | (defun cape-elisp-block (&optional interactive)
540 | "Complete Elisp in Org or Markdown code block.
541 | This Capf is particularly useful for literate Emacs configurations.
542 | If INTERACTIVE is nil the function acts like a Capf."
543 | (interactive (list t))
544 | (cond
545 | (interactive
546 | ;; No code block check. Always complete Elisp when command was
547 | ;; explicitly invoked interactively.
548 | (cape-interactive #'elisp-completion-at-point))
549 | ((cape--inside-block-p "elisp" "emacs-lisp")
550 | (elisp-completion-at-point))))
551 |
552 | ;;;;; cape-dabbrev
553 |
554 | (defvar cape--dabbrev-properties
555 | (list :annotation-function (lambda (_) " Dabbrev")
556 | :company-kind (lambda (_) 'text)
557 | :exclusive 'no
558 | :category 'cape-dabbrev)
559 | "Completion extra properties for `cape-dabbrev'.")
560 |
561 | (defvar dabbrev-case-replace)
562 | (defvar dabbrev-case-fold-search)
563 | (defvar dabbrev-abbrev-char-regexp)
564 | (defvar dabbrev-abbrev-skip-leading-regexp)
565 | (declare-function dabbrev--find-all-expansions "dabbrev")
566 | (declare-function dabbrev--reset-global-variables "dabbrev")
567 |
568 | (defun cape--dabbrev-list (input)
569 | "Find all Dabbrev expansions for INPUT."
570 | (cape--silent
571 | (dlet ((dabbrev-check-other-buffers nil)
572 | (dabbrev-check-all-buffers nil)
573 | (dabbrev-backward-only nil)
574 | (dabbrev-limit nil)
575 | (dabbrev-search-these-buffers-only
576 | (ensure-list (funcall cape-dabbrev-buffer-function))))
577 | (dabbrev--reset-global-variables)
578 | (cons
579 | (apply-partially #'string-prefix-p input)
580 | (cl-loop
581 | with ic = (cape--case-fold-p dabbrev-case-fold-search)
582 | for w in (dabbrev--find-all-expansions input ic)
583 | collect (cape--case-replace (and ic dabbrev-case-replace) input w))))))
584 |
585 | (defun cape--dabbrev-bounds ()
586 | "Return bounds of abbreviation."
587 | (unless (boundp 'dabbrev-abbrev-char-regexp)
588 | (require 'dabbrev))
589 | (let ((re (or dabbrev-abbrev-char-regexp "\\sw\\|\\s_"))
590 | (limit (minibuffer-prompt-end)))
591 | (if (or (looking-at re)
592 | (and (> (point) limit)
593 | (save-excursion (forward-char -1) (looking-at re))))
594 | (cons (save-excursion
595 | (while (and (> (point) limit)
596 | (save-excursion (forward-char -1) (looking-at re)))
597 | (forward-char -1))
598 | (when dabbrev-abbrev-skip-leading-regexp
599 | (while (looking-at dabbrev-abbrev-skip-leading-regexp)
600 | (forward-char 1)))
601 | (point))
602 | (save-excursion
603 | (while (looking-at re)
604 | (forward-char 1))
605 | (point)))
606 | (cons (point) (point)))))
607 |
608 | ;;;###autoload
609 | (defun cape-dabbrev (&optional interactive)
610 | "Complete with Dabbrev at point.
611 |
612 | If INTERACTIVE is nil the function acts like a Capf. In case you
613 | observe a performance issue with auto-completion and `cape-dabbrev'
614 | it is strongly recommended to disable scanning in other buffers.
615 | See the user option `cape-dabbrev-buffer-function'."
616 | (interactive (list t))
617 | (if interactive
618 | (cape-interactive #'cape-dabbrev)
619 | (pcase-let ((`(,beg . ,end) (cape--dabbrev-bounds)))
620 | `(,beg ,end
621 | ,(completion-table-case-fold
622 | (cape--dynamic-table beg end #'cape--dabbrev-list)
623 | (not (cape--case-fold-p dabbrev-case-fold-search)))
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 | :display-sort-function #'identity
632 | :cycle-sort-function #'identity
633 | :exclusive 'no
634 | :category 'cape-dict)
635 | "Completion extra properties for `cape-dict'.")
636 |
637 | (defun cape--dict-list (input)
638 | "Return all words from `cape-dict-file' matching INPUT."
639 | (let* ((inhibit-message t)
640 | (message-log-max nil)
641 | (default-directory
642 | (if (and (not (file-remote-p default-directory))
643 | (file-directory-p default-directory))
644 | default-directory
645 | user-emacs-directory))
646 | (files (mapcar #'expand-file-name
647 | (ensure-list
648 | (if (functionp cape-dict-file)
649 | (funcall cape-dict-file)
650 | cape-dict-file))))
651 | (words
652 | (apply #'process-lines-ignore-status
653 | "grep"
654 | (concat "-Fh"
655 | (and (cape--case-fold-p cape-dict-case-fold) "i")
656 | (and cape-dict-limit (format "m%d" cape-dict-limit)))
657 | input files)))
658 | (cons
659 | (apply-partially
660 | (if (and cape-dict-limit (length= words cape-dict-limit))
661 | #'equal #'string-search)
662 | input)
663 | (cape--case-replace-list cape-dict-case-replace input words))))
664 |
665 | ;;;###autoload
666 | (defun cape-dict (&optional interactive)
667 | "Complete word from dictionary at point.
668 | This completion function works best if the dictionary is sorted
669 | by frequency. See the custom option `cape-dict-file'. If
670 | INTERACTIVE is nil the function acts like a Capf."
671 | (interactive (list t))
672 | (if interactive
673 | (cape-interactive #'cape-dict)
674 | (pcase-let ((`(,beg . ,end) (cape--bounds 'word)))
675 | `( ,beg ,end
676 | ,(completion-table-case-fold
677 | (cape--dynamic-table beg end #'cape--dict-list)
678 | (not (cape--case-fold-p cape-dict-case-fold)))
679 | ,@cape--dict-properties))))
680 |
681 | ;;;;; cape-abbrev
682 |
683 | (defun cape--abbrev-list ()
684 | "Abbreviation list."
685 | (delete "" (cl-loop for x in (abbrev--suggest-get-active-tables-including-parents)
686 | nconc (all-completions "" x))))
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 x in (abbrev--suggest-get-active-tables-including-parents)
696 | thereis (abbrev--symbol abbrev x))))
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 | :category 'cape-abbrev)
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) ,abbrevs ,@cape--abbrev-properties)))))
724 |
725 | ;;;;; cape-line
726 |
727 | (defvar cape--line-properties
728 | (list :display-sort-function #'identity
729 | :cycle-sort-function #'identity
730 | :exclusive 'no
731 | :category 'cape-line)
732 | "Completion extra properties for `cape-line'.")
733 |
734 | (defun cape--line-list ()
735 | "Return all lines from buffer."
736 | (let ((ht (make-hash-table :test #'equal))
737 | (curr-buf (current-buffer))
738 | (buffers (funcall cape-line-buffer-function))
739 | lines)
740 | (dolist (buf (ensure-list buffers))
741 | (with-current-buffer buf
742 | (let ((beg (point-min))
743 | (max (point-max))
744 | (pt (if (eq curr-buf buf) (point) -1))
745 | end)
746 | (save-excursion
747 | (while (< beg max)
748 | (goto-char beg)
749 | (setq end (pos-eol))
750 | (unless (<= beg pt end)
751 | (let ((line (buffer-substring-no-properties beg end)))
752 | (unless (or (string-blank-p line) (gethash line ht))
753 | (puthash line t ht)
754 | (push line lines))))
755 | (setq beg (1+ end)))))))
756 | (nreverse lines)))
757 |
758 | ;;;###autoload
759 | (defun cape-line (&optional interactive)
760 | "Complete current line from other lines.
761 | The buffers returned by `cape-line-buffer-function' are scanned for lines.
762 | If INTERACTIVE is nil the function acts like a Capf."
763 | (interactive (list t))
764 | (if interactive
765 | (cape-interactive #'cape-line)
766 | `(,(pos-bol) ,(point) ,(cape--line-list) ,@cape--line-properties)))
767 |
768 | ;;;; Capf combinators
769 |
770 | (defun cape--company-call (&rest app)
771 | "Apply APP and handle future return values."
772 | ;; Backends are non-interruptible. Disable interrupts!
773 | (let ((toi throw-on-input)
774 | (throw-on-input nil))
775 | (pcase (apply app)
776 | ;; Handle async future return values.
777 | (`(:async . ,fetch)
778 | (let ((res 'cape--waiting))
779 | (if toi
780 | (unwind-protect
781 | (progn
782 | (funcall fetch
783 | (lambda (arg)
784 | (when (eq res 'cape--waiting)
785 | (push 'cape--done unread-command-events)
786 | (setq res arg))))
787 | (when (eq res 'cape--waiting)
788 | (let ((ev (let ((input-method-function nil)
789 | (echo-keystrokes 0))
790 | (read-event nil t))))
791 | (unless (eq ev 'cape--done)
792 | (push (cons t ev) unread-command-events)
793 | (setq res 'cape--cancelled)
794 | (throw toi t)))))
795 | (setq unread-command-events
796 | (delq 'cape--done unread-command-events)))
797 | (funcall fetch (lambda (arg) (setq res arg)))
798 | ;; Force synchronization, not interruptible! We use polling
799 | ;; here and ignore pending input since we don't use
800 | ;; `sit-for'. This is the same method used by Company itself.
801 | (while (eq res 'cape--waiting)
802 | (sleep-for 0.01)))
803 | res))
804 | ;; Plain old synchronous return value.
805 | (res res))))
806 |
807 | (defvar-local cape--company-init nil)
808 |
809 | ;;;###autoload
810 | (defun cape-company-to-capf (backend &optional valid)
811 | "Convert Company BACKEND function to Capf.
812 | VALID is a function taking the old and new input string. It should
813 | return nil if the cached candidates became invalid. The default value
814 | for VALID is `string-prefix-p' such that the candidates are only fetched
815 | again if the input prefix changed."
816 | (lambda ()
817 | (when (and (symbolp backend) (not (fboundp backend)))
818 | (ignore-errors (require backend nil t)))
819 | (when (bound-and-true-p company-mode)
820 | (error "`cape-company-to-capf' should not be used with `company-mode', use the Company backend directly instead"))
821 | (when (and (symbolp backend) (not (alist-get backend cape--company-init)))
822 | (funcall backend 'init)
823 | (put backend 'company-init t)
824 | (setf (alist-get backend cape--company-init) t))
825 | (when-let ((pre (pcase (cape--company-call backend 'prefix)
826 | ((or `(,p ,_s) (and (pred stringp) p)) (cons p (length p)))
827 | ((or `(,p ,_s ,l) `(,p . ,l)) (cons p l)))))
828 | (let* ((end (point)) (beg (- end (length (car pre))))
829 | (valid (if (cape--company-call backend 'no-cache (car pre))
830 | #'equal (or valid #'string-prefix-p)))
831 | (sort-fun (and (cape--company-call backend 'sorted) #'identity))
832 | restore-props)
833 | (list beg end
834 | (funcall
835 | (if (cape--company-call backend 'ignore-case)
836 | #'completion-table-case-fold
837 | #'identity)
838 | (cape--dynamic-table
839 | beg end
840 | (lambda (input)
841 | (let ((cands (cape--company-call backend 'candidates input)))
842 | ;; The candidate string including text properties should be
843 | ;; restored in the :exit-function, unless the UI guarantees
844 | ;; this itself, like Corfu.
845 | (unless (bound-and-true-p corfu-mode)
846 | (setq restore-props cands))
847 | (cons (apply-partially valid input) cands)))))
848 | :category backend
849 | :exclusive 'no
850 | :company-prefix-length (cdr pre)
851 | :company-doc-buffer (lambda (x) (cape--company-call backend 'doc-buffer x))
852 | :company-location (lambda (x) (cape--company-call backend 'location x))
853 | :company-docsig (lambda (x) (cape--company-call backend 'meta x))
854 | :company-deprecated (lambda (x) (cape--company-call backend 'deprecated x))
855 | :company-kind (lambda (x) (cape--company-call backend 'kind x))
856 | :display-sort-function sort-fun
857 | :cycle-sort-function sort-fun
858 | :annotation-function (lambda (x)
859 | (when-let (ann (cape--company-call backend 'annotation x))
860 | (concat " " (string-trim ann))))
861 | :exit-function (lambda (x _status)
862 | ;; Restore the candidate string including
863 | ;; properties if restore-props is non-nil. See
864 | ;; the comment above.
865 | (setq x (or (car (member x restore-props)) x))
866 | (cape--company-call backend 'post-completion x)))))))
867 |
868 | ;;;###autoload
869 | (defun cape-interactive (&rest capfs)
870 | "Complete interactively with the given CAPFS."
871 | (let* ((ctx (and (consp (car capfs)) (car capfs)))
872 | (capfs (if ctx (cdr capfs) capfs))
873 | (completion-at-point-functions
874 | (if ctx
875 | (mapcar (lambda (f) `(lambda () (let ,ctx (funcall ',f)))) capfs)
876 | capfs)))
877 | (unless (completion-at-point)
878 | (user-error "%s: No completions"
879 | (mapconcat (lambda (fun)
880 | (if (symbolp fun)
881 | (symbol-name fun)
882 | "anonymous-capf"))
883 | capfs ", ")))))
884 |
885 | ;;;###autoload
886 | (defun cape-capf-interactive (capf)
887 | "Create interactive completion function from CAPF."
888 | (lambda (&optional interactive)
889 | (interactive (list t))
890 | (if interactive (cape-interactive capf) (funcall capf))))
891 |
892 | (defvar cape--super-functions
893 | '( :company-docsig :company-location :company-kind
894 | :company-doc-buffer :company-deprecated
895 | :annotation-function :exit-function)
896 | "List of extra functions which are handled by `cape-wrap-super'.")
897 |
898 | ;;;###autoload
899 | (defun cape-wrap-super (&rest capfs)
900 | "Call CAPFS and return merged completion result.
901 | The CAPFS list can contain the keyword `:with' to mark the Capfs
902 | afterwards as auxiliary. One of the non-auxiliary Capfs before `:with'
903 | must return non-nil for the super Capf to set in and return a non-nil
904 | result. Such behavior is useful when listing multiple super Capfs in
905 | the `completion-at-point-functions':
906 |
907 | (setq completion-at-point-functions
908 | (list (cape-capf-super \\='elisp-completion-at-point
909 | :with \\='tempel-complete)
910 | (cape-capf-super \\='cape-dabbrev
911 | :with \\='tempel-complete)))
912 |
913 | See the dual `cape-wrap-choose' if you want to try multiple Capfs in
914 | turn."
915 | (when-let ((results (cl-loop for capf in capfs until (eq capf :with)
916 | for res = (funcall capf)
917 | if res collect (cons t res))))
918 | (pcase-let* ((results (nconc results
919 | (cl-loop for capf in (cdr (memq :with capfs))
920 | for res = (funcall capf)
921 | if res collect (cons nil res))))
922 | (`((,_main ,beg ,end . ,_)) results)
923 | (cand-ht nil)
924 | (tables nil)
925 | (exclusive nil)
926 | (prefix-len nil))
927 | (cl-loop for (main beg2 end2 table . plist) in results do
928 | ;; Note: `cape-capf-super' currently cannot merge Capfs which
929 | ;; trigger at different beginning positions. In order to support
930 | ;; this, take the smallest BEG value and then normalize all
931 | ;; candidates by prefixing them such that they all start at the
932 | ;; smallest BEG position.
933 | (when (= beg beg2)
934 | (push (list main (plist-get plist :predicate) table
935 | ;; Plist attached to the candidates
936 | (mapcan (lambda (f)
937 | (when-let ((v (plist-get plist f)))
938 | (list f v)))
939 | cape--super-functions))
940 | tables)
941 | ;; The resulting merged Capf is exclusive if one of the main
942 | ;; Capfs is exclusive.
943 | (when (and main (not (eq (plist-get plist :exclusive) 'no)))
944 | (setq exclusive t))
945 | (setq end (max end end2))
946 | (let ((plen (plist-get plist :company-prefix-length)))
947 | (cond
948 | ((eq plen t)
949 | (setq prefix-len t))
950 | ((and (not prefix-len) (integerp plen))
951 | (setq prefix-len plen))
952 | ((and (integerp prefix-len) (integerp plen))
953 | (setq prefix-len (max prefix-len plen)))))))
954 | (setq tables (nreverse tables))
955 | `( ,beg ,end
956 | ,(lambda (str pred action)
957 | (pcase action
958 | ((or `(boundaries . ,_) 'metadata) nil)
959 | ('t ;; all-completions
960 | (let ((ht (make-hash-table :test #'equal))
961 | (candidates nil))
962 | (cl-loop for (main table-pred table cand-plist) in tables do
963 | (let* ((pr (if (and table-pred pred)
964 | (lambda (x) (and (funcall table-pred x) (funcall pred x)))
965 | (or table-pred pred)))
966 | (md (completion-metadata "" table pr))
967 | (sort (or (completion-metadata-get md 'display-sort-function)
968 | #'identity))
969 | ;; Always compute candidates of the main Capf
970 | ;; tables, which come first in the tables
971 | ;; list. For the :with Capfs only compute
972 | ;; candidates if we've already determined that
973 | ;; main candidates are available.
974 | (cands (when (or main (or exclusive cand-ht candidates))
975 | (funcall sort (all-completions str table pr)))))
976 | ;; Handle duplicates with a hash table.
977 | (cl-loop
978 | for cand in-ref cands
979 | for dup = (gethash cand ht t) do
980 | (cond
981 | ((eq dup t)
982 | ;; Candidate does not yet exist.
983 | (puthash cand cand-plist ht))
984 | ((not (equal dup cand-plist))
985 | ;; Duplicate candidate. Candidate plist is
986 | ;; different, therefore disambiguate the
987 | ;; candidates.
988 | (setf cand (propertize cand 'cape-capf-super
989 | (cons cand cand-plist))))))
990 | (when cands (push cands candidates))))
991 | (when (or cand-ht candidates)
992 | (setq candidates (apply #'nconc (nreverse candidates))
993 | cand-ht ht)
994 | candidates)))
995 | (_ ;; try-completion and test-completion
996 | (cl-loop for (_main table-pred table _cand-plist) in tables thereis
997 | (complete-with-action
998 | action table str
999 | (if (and table-pred pred)
1000 | (lambda (x) (and (funcall table-pred x) (funcall pred x)))
1001 | (or table-pred pred)))))))
1002 | :category cape-super
1003 | :company-prefix-length ,prefix-len
1004 | :display-sort-function ,#'identity
1005 | :cycle-sort-function ,#'identity
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 | cape--super-functions)))))
1018 |
1019 | ;;;###autoload
1020 | (defun cape-wrap-choose (&rest capfs)
1021 | "Call each of CAPFS in turn and return first non-nil result.
1022 | Use `cape-wrap-choose' to create a single Capf from multiple Capfs.
1023 | Usually you want to add multiple non-exclusive Capfs to the variable
1024 | `completion-at-point-functions' directly instead. See the dual
1025 | `cape-wrap-super' if you want to merge multiple Capf results."
1026 | (cl-loop
1027 | for capf in capfs thereis
1028 | (pcase (funcall capf)
1029 | ((and result `(,beg ,end ,table . ,plist))
1030 | (let* ((str (buffer-substring-no-properties beg end))
1031 | (pt (- (point) beg))
1032 | (pred (plist-get plist :predicate))
1033 | (md (completion-metadata (substring str 0 pt) table pred)))
1034 | ;; Treat the Capfs always as non-exclusive. Return the first which
1035 | ;; returns non-nil. See also the comment in `corfu--capf-wrapper'.
1036 | (and (completion-try-completion str table pred pt md)
1037 | result))))))
1038 |
1039 | ;;;###autoload
1040 | (defun cape-wrap-debug (capf &optional name)
1041 | "Call CAPF and return a completion table which prints trace messages.
1042 | If CAPF is an anonymous lambda, pass the Capf NAME explicitly for
1043 | meaningful debugging output."
1044 | (unless name
1045 | (setq name (if (symbolp capf) capf "capf")))
1046 | (setq name (format "%s@%s" name (cl-incf cape--debug-id)))
1047 | (pcase (funcall capf)
1048 | (`(,beg ,end ,table . ,plist)
1049 | (let* ((limit (1+ cape--debug-length))
1050 | (pred (plist-get plist :predicate))
1051 | (cands
1052 | ;; Reset regexps for `all-completions'
1053 | (let (completion-ignore-case completion-regexp-list)
1054 | (all-completions
1055 | "" table
1056 | (lambda (&rest args)
1057 | (and (or (not pred) (apply pred args)) (>= (cl-decf limit) 0))))))
1058 | (plist-str "")
1059 | (plist-elt plist))
1060 | (while (cdr plist-elt)
1061 | (setq plist-str (format "%s %s=%s" plist-str
1062 | (substring (symbol-name (car plist-elt)) 1)
1063 | (cape--debug-print (cadr plist-elt)))
1064 | plist-elt (cddr plist-elt)))
1065 | (cape--debug-message
1066 | "%s => input=%s:%s:%S table=%s%s"
1067 | name (+ beg 0) (+ end 0) (buffer-substring-no-properties beg end)
1068 | (cape--debug-print cands)
1069 | plist-str))
1070 | `( ,beg ,end
1071 | ,(cape--debug-table
1072 | table name (copy-marker beg) (copy-marker end t))
1073 | ,@(when-let ((exit (plist-get plist :exit-function)))
1074 | (list :exit-function
1075 | (lambda (str status)
1076 | (cape--debug-message "%s:exit(status=%s string=%S)"
1077 | name status str)
1078 | (funcall exit str status))))
1079 | . ,plist))
1080 | (result
1081 | (cape--debug-message "%s() => %s (No completion)"
1082 | name (cape--debug-print result)))))
1083 |
1084 | ;;;###autoload
1085 | (defun cape-wrap-buster (capf &optional valid)
1086 | "Call CAPF and return a completion table with cache busting.
1087 | This function can be used as an advice around an existing Capf.
1088 | The cache is busted when the input changes. The argument VALID
1089 | can be a function taking the old and new input string. It should
1090 | return nil if the new input requires that the completion table is
1091 | refreshed. The default value for VALID is `equal', such that the
1092 | completion table is refreshed on every input change."
1093 | (setq valid (or valid #'equal))
1094 | (pcase (funcall capf)
1095 | (`(,beg ,end ,table . ,plist)
1096 | (setq plist `(:cape--buster t . ,plist))
1097 | `( ,beg ,end
1098 | ,(let* ((beg (copy-marker beg))
1099 | (end (copy-marker end t))
1100 | (input (buffer-substring-no-properties beg end)))
1101 | (lambda (str pred action)
1102 | (let ((new-input (buffer-substring-no-properties beg end)))
1103 | (unless (or (not (eq action t))
1104 | (cape--separator-p new-input)
1105 | (funcall valid input new-input))
1106 | (pcase
1107 | ;; Reset in case `all-completions' is used inside CAPF
1108 | (let (completion-ignore-case completion-regexp-list)
1109 | (funcall capf))
1110 | ((and `(,new-beg ,new-end ,new-table . ,new-plist)
1111 | (guard (and (= beg new-beg) (= end new-end))))
1112 | (let (throw-on-input) ;; No interrupt during state update
1113 | (setf table new-table
1114 | input new-input
1115 | (cddr plist) new-plist))))))
1116 | (complete-with-action action table str pred)))
1117 | ,@plist))))
1118 |
1119 | ;;;###autoload
1120 | (defun cape-wrap-passthrough (capf)
1121 | "Call CAPF and make sure that no completion style filtering takes place.
1122 | This function can be used as an advice around an existing Capf."
1123 | (pcase (funcall capf)
1124 | (`(,beg ,end ,table . ,plist)
1125 | `(,beg ,end ,(cape--passthrough-table table) ,@plist))))
1126 |
1127 | ;;;###autoload
1128 | (defun cape-wrap-properties (capf &rest properties)
1129 | "Call CAPF and strip or add completion PROPERTIES.
1130 | Completion properties include for example :exclusive, :category,
1131 | :annotation-function, :display-sort-function and various :company-*
1132 | extensions. Strip all properties if PROPERTIES is :strip."
1133 | (pcase (funcall capf)
1134 | (`(,beg ,end ,table . ,plist)
1135 | `( ,beg ,end ,table
1136 | ,@(and (not (eq :strip (car properties))) (append properties plist))))))
1137 |
1138 | ;;;###autoload
1139 | (defun cape-wrap-nonexclusive (capf)
1140 | "Call CAPF and ensure that it is marked as non-exclusive.
1141 | This function can be used as an advice around an existing Capf."
1142 | (cape-wrap-properties capf :exclusive 'no))
1143 |
1144 | ;;;###autoload
1145 | (defun cape-wrap-sort (capf &optional sort)
1146 | "Call CAPF and add SORT function as completion metadata.
1147 | If the SORT argument is nil or not given, the completion UI will use
1148 | its own default sorting algorithm. This function can be used as an
1149 | advice around an existing Capf."
1150 | (cape-wrap-properties
1151 | capf
1152 | :display-sort-function sort
1153 | :cycle-sort-function sort))
1154 |
1155 | ;;;###autoload
1156 | (defun cape-wrap-predicate (capf predicate)
1157 | "Call CAPF and add an additional candidate PREDICATE.
1158 | The PREDICATE is passed the candidate symbol or string."
1159 | (pcase (funcall capf)
1160 | (`(,beg ,end ,table . ,plist)
1161 | `( ,beg ,end ,table
1162 | :predicate
1163 | ,(if-let (pred (plist-get plist :predicate))
1164 | ;; First argument is key, second is value for hash tables.
1165 | ;; The first argument can be a cons cell for alists. Then
1166 | ;; the candidate itself is either a string or a symbol. We
1167 | ;; normalize the calling convention here such that PREDICATE
1168 | ;; always receives a string or a symbol.
1169 | (lambda (&rest args)
1170 | (when (apply pred args)
1171 | (setq args (car args))
1172 | (funcall predicate (if (consp args) (car args) args))))
1173 | (lambda (key &optional _val)
1174 | (funcall predicate (if (consp key) (car key) key))))
1175 | ,@plist))))
1176 |
1177 | ;;;###autoload
1178 | (defun cape-wrap-silent (capf)
1179 | "Call CAPF and silence it (no messages, no errors).
1180 | This function can be used as an advice around an existing Capf."
1181 | (pcase (cape--silent (funcall capf))
1182 | (`(,beg ,end ,table . ,plist)
1183 | `(,beg ,end ,(cape--silent-table table) ,@plist))))
1184 |
1185 | ;;;###autoload
1186 | (defun cape-wrap-case-fold (capf &optional nofold)
1187 | "Call CAPF and return a case-insensitive completion table.
1188 | If NOFOLD is non-nil return a case sensitive table instead. This
1189 | function can be used as an advice around an existing Capf."
1190 | (pcase (funcall capf)
1191 | (`(,beg ,end ,table . ,plist)
1192 | `(,beg ,end ,(completion-table-case-fold table nofold) ,@plist))))
1193 |
1194 | ;;;###autoload
1195 | (defun cape-wrap-noninterruptible (capf)
1196 | "Call CAPF and return a non-interruptible completion table.
1197 | This function can be used as an advice around an existing Capf."
1198 | (pcase (let (throw-on-input) (funcall capf))
1199 | (`(,beg ,end ,table . ,plist)
1200 | `(,beg ,end ,(cape--noninterruptible-table table) ,@plist))))
1201 |
1202 | ;;;###autoload
1203 | (defun cape-wrap-prefix-length (capf length)
1204 | "Call CAPF and ensure that prefix length is greater or equal than LENGTH.
1205 | If the prefix is long enough, enforce auto completion."
1206 | (pcase (funcall capf)
1207 | (`(,beg ,end ,table . ,plist)
1208 | (when (>= (- end beg) length)
1209 | `(,beg ,end ,table :company-prefix-length t ,@plist)))))
1210 |
1211 | ;;;###autoload
1212 | (defun cape-wrap-inside-faces (capf &rest faces)
1213 | "Call CAPF only if inside FACES."
1214 | (when-let (((> (point) (point-min)))
1215 | (fs (get-text-property (1- (point)) 'face))
1216 | ((if (listp fs)
1217 | (cl-loop for f in fs thereis (memq f faces))
1218 | (memq fs faces))))
1219 | (funcall capf)))
1220 |
1221 | ;;;###autoload
1222 | (defun cape-wrap-inside-code (capf)
1223 | "Call CAPF only if inside code, not inside a comment or string.
1224 | This function can be used as an advice around an existing Capf."
1225 | (let ((s (syntax-ppss)))
1226 | (and (not (nth 3 s)) (not (nth 4 s)) (funcall capf))))
1227 |
1228 | ;;;###autoload
1229 | (defun cape-wrap-inside-comment (capf)
1230 | "Call CAPF only if inside comment.
1231 | This function can be used as an advice around an existing Capf."
1232 | (and (nth 4 (syntax-ppss)) (funcall capf)))
1233 |
1234 | ;;;###autoload
1235 | (defun cape-wrap-inside-string (capf)
1236 | "Call CAPF only if inside string.
1237 | This function can be used as an advice around an existing Capf."
1238 | (and (nth 3 (syntax-ppss)) (funcall capf)))
1239 |
1240 | ;;;###autoload
1241 | (defun cape-wrap-accept-all (capf)
1242 | "Call CAPF and return a completion table which accepts every input.
1243 | This function can be used as an advice around an existing Capf."
1244 | (pcase (funcall capf)
1245 | (`(,beg ,end ,table . ,plist)
1246 | `(,beg ,end ,(cape--accept-all-table table) . ,plist))))
1247 |
1248 | (defvar cape--trigger-syntax-table (make-syntax-table (syntax-table))
1249 | "Syntax table used for the trigger character.")
1250 |
1251 | ;;;###autoload
1252 | (defun cape-wrap-trigger (capf trigger)
1253 | "Ensure that TRIGGER character occurs before point and then call CAPF.
1254 | See also `corfu-auto-trigger'.
1255 | Example:
1256 | (setq corfu-auto-trigger \"/\"
1257 | completion-at-point-functions
1258 | (list (cape-capf-trigger \\='cape-abbrev ?/)))"
1259 | (when-let ((pos (save-excursion (search-backward (char-to-string trigger) (pos-bol) 'noerror)))
1260 | ((save-excursion (not (re-search-backward "\\s-" pos 'noerror)))))
1261 | (pcase
1262 | ;; Treat the trigger character as punctuation.
1263 | (with-syntax-table cape--trigger-syntax-table
1264 | (unless (eq (char-syntax trigger) ?.)
1265 | (modify-syntax-entry trigger "."))
1266 | (funcall capf))
1267 | (`(,beg ,end ,table . ,plist)
1268 | (when (<= pos beg (1+ pos))
1269 | `( ,(1+ pos) ,end ,table
1270 | :company-prefix-length t
1271 | :exit-function
1272 | ,(let ((pos (copy-marker pos))
1273 | (end (copy-marker (1+ pos))))
1274 | (lambda (str status)
1275 | (delete-region pos end)
1276 | (when-let ((exit (plist-get plist :exit-function)))
1277 | (funcall exit str status))))
1278 | . ,plist))))))
1279 |
1280 | ;;;###autoload (autoload 'cape-capf-purify "cape")
1281 | ;;;###autoload
1282 | (defun cape-wrap-purify (capf)
1283 | "Obsolete purification wrapper calling CAPF.
1284 | This function can be used as an advice around an existing Capf."
1285 | (warn "`cape-wrap-purify' is obsolete")
1286 | (funcall capf))
1287 | (make-obsolete 'cape-wrap-purify nil "2.2")
1288 | (make-obsolete 'cape-capf-purify nil "2.2")
1289 |
1290 | (dolist (wrapper (list #'cape-wrap-accept-all #'cape-wrap-buster
1291 | #'cape-wrap-case-fold #'cape-wrap-choose
1292 | #'cape-wrap-debug #'cape-wrap-inside-code
1293 | #'cape-wrap-inside-comment #'cape-wrap-inside-faces
1294 | #'cape-wrap-inside-string #'cape-wrap-nonexclusive
1295 | #'cape-wrap-noninterruptible #'cape-wrap-passthrough
1296 | #'cape-wrap-predicate #'cape-wrap-prefix-length
1297 | #'cape-wrap-properties 'cape-wrap-purify
1298 | #'cape-wrap-silent #'cape-wrap-sort
1299 | #'cape-wrap-super #'cape-wrap-trigger))
1300 | (let ((name (string-remove-prefix "cape-wrap-" (symbol-name wrapper))))
1301 | (defalias (intern (format "cape-capf-%s" name))
1302 | (lambda (capf &rest args) (lambda () (apply wrapper capf args)))
1303 | (format "Create a %s Capf from CAPF.
1304 | The Capf calls `%s' with CAPF and ARGS as arguments.
1305 | See `%s' for documentation." name wrapper wrapper))))
1306 |
1307 | ;;;###autoload (autoload 'cape-capf-accept-all "cape")
1308 | ;;;###autoload (autoload 'cape-capf-buster "cape")
1309 | ;;;###autoload (autoload 'cape-capf-case-fold "cape")
1310 | ;;;###autoload (autoload 'cape-capf-choose "cape")
1311 | ;;;###autoload (autoload 'cape-capf-debug "cape")
1312 | ;;;###autoload (autoload 'cape-capf-inside-code "cape")
1313 | ;;;###autoload (autoload 'cape-capf-inside-comment "cape")
1314 | ;;;###autoload (autoload 'cape-capf-inside-faces "cape")
1315 | ;;;###autoload (autoload 'cape-capf-inside-string "cape")
1316 | ;;;###autoload (autoload 'cape-capf-nonexclusive "cape")
1317 | ;;;###autoload (autoload 'cape-capf-noninterruptible "cape")
1318 | ;;;###autoload (autoload 'cape-capf-passthrough "cape")
1319 | ;;;###autoload (autoload 'cape-capf-predicate "cape")
1320 | ;;;###autoload (autoload 'cape-capf-prefix-length "cape")
1321 | ;;;###autoload (autoload 'cape-capf-properties "cape")
1322 | ;;;###autoload (autoload 'cape-capf-silent "cape")
1323 | ;;;###autoload (autoload 'cape-capf-super "cape")
1324 | ;;;###autoload (autoload 'cape-capf-trigger "cape")
1325 |
1326 | (defvar-keymap cape-prefix-map
1327 | :doc "Keymap used as completion entry point.
1328 | The keymap should be installed globally under a prefix."
1329 | "TAB" #'completion-at-point
1330 | "M-TAB" #'completion-at-point
1331 | "p" #'completion-at-point
1332 | "t" #'complete-tag
1333 | "d" #'cape-dabbrev
1334 | "h" #'cape-history
1335 | "f" #'cape-file
1336 | "s" #'cape-elisp-symbol
1337 | "e" #'cape-elisp-block
1338 | "a" #'cape-abbrev
1339 | "l" #'cape-line
1340 | "w" #'cape-dict
1341 | "k" 'cape-keyword
1342 | ":" 'cape-emoji
1343 | "\\" 'cape-tex
1344 | "_" 'cape-tex
1345 | "^" 'cape-tex
1346 | "&" 'cape-sgml
1347 | "r" 'cape-rfc1345)
1348 |
1349 | ;;;###autoload (autoload 'cape-prefix-map "cape" nil t 'keymap)
1350 | (defalias 'cape-prefix-map cape-prefix-map)
1351 |
1352 | (provide 'cape)
1353 | ;;; cape.el ends here
1354 |
--------------------------------------------------------------------------------