config

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

marginalia.el (58088B)


      1 ;;; marginalia.el --- Enrich existing commands with completion annotations -*- lexical-binding: t -*-
      2 
      3 ;; Copyright (C) 2021-2024 Free Software Foundation, Inc.
      4 
      5 ;; Author: Omar Antolín Camarena <omar@matem.unam.mx>, Daniel Mendler <mail@daniel-mendler.de>
      6 ;; Maintainer: Omar Antolín Camarena <omar@matem.unam.mx>, Daniel Mendler <mail@daniel-mendler.de>
      7 ;; Created: 2020
      8 ;; Version: 1.5
      9 ;; Package-Requires: ((emacs "27.1") (compat "29.1.4.4"))
     10 ;; Homepage: https://github.com/minad/marginalia
     11 ;; Keywords: docs, help, matching, completion
     12 
     13 ;; This file is part of GNU Emacs.
     14 
     15 ;; This program is free software: you can redistribute it and/or modify
     16 ;; it under the terms of the GNU General Public License as published by
     17 ;; the Free Software Foundation, either version 3 of the License, or
     18 ;; (at your option) any later version.
     19 
     20 ;; This program is distributed in the hope that it will be useful,
     21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
     22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     23 ;; GNU General Public License for more details.
     24 
     25 ;; You should have received a copy of the GNU General Public License
     26 ;; along with this program.  If not, see <https://www.gnu.org/licenses/>.
     27 
     28 ;;; Commentary:
     29 
     30 ;; Enrich existing commands with completion annotations
     31 
     32 ;;; Code:
     33 
     34 (require 'compat)
     35 (eval-when-compile
     36   (require 'subr-x)
     37   (require 'cl-lib))
     38 
     39 ;;;; Customization
     40 
     41 (defgroup marginalia nil
     42   "Enrich existing commands with completion annotations."
     43   :link '(info-link :tag "Info Manual" "(marginalia)")
     44   :link '(url-link :tag "Homepage" "https://github.com/minad/marginalia")
     45   :link '(emacs-library-link :tag "Library Source" "marginalia.el")
     46   :group 'help
     47   :group 'docs
     48   :group 'minibuffer
     49   :prefix "marginalia-")
     50 
     51 (defcustom marginalia-field-width 80
     52   "Maximum truncation width of annotation fields.
     53 
     54 This value is adjusted depending on the `window-width'."
     55   :type 'natnum)
     56 
     57 (defcustom marginalia-separator "  "
     58   "Annotation field separator."
     59   :type 'string)
     60 
     61 (defcustom marginalia-align 'left
     62   "Alignment of the annotations."
     63   :type '(choice (const :tag "Left"   left)
     64                  (const :tag "Center" center)
     65                  (const :tag "Right"  right)))
     66 
     67 (defcustom marginalia-align-offset 0
     68   "Additional offset added to the alignment."
     69   :type 'natnum)
     70 
     71 (defcustom marginalia-max-relative-age (* 60 60 24 14)
     72   "Maximum relative age in seconds displayed by the file annotator.
     73 
     74 Set to `most-positive-fixnum' to always use a relative age, or 0 to never show
     75 a relative age."
     76   :type 'natnum)
     77 
     78 (defcustom marginalia-remote-file-regexps
     79   '("\\`/\\([^/|:]+\\):") ;; Tramp path
     80   "List of remote file regexps where the files should not be annotated.
     81 
     82 The first match group is displayed instead of the detailed file
     83 attribute information.  For Tramp paths, the protocol is
     84 displayed instead."
     85   :type '(repeat regexp))
     86 
     87 (defcustom marginalia-annotator-registry
     88   (mapcar
     89    (lambda (x) (append x '(builtin none)))
     90    `((command ,#'marginalia-annotate-command ,#'marginalia-annotate-binding)
     91      (embark-keybinding ,#'marginalia-annotate-embark-keybinding)
     92      (customize-group ,#'marginalia-annotate-customize-group)
     93      (variable ,#'marginalia-annotate-variable)
     94      (function ,#'marginalia-annotate-function)
     95      (face ,#'marginalia-annotate-face)
     96      (color ,#'marginalia-annotate-color)
     97      (unicode-name ,#'marginalia-annotate-char)
     98      (minor-mode ,#'marginalia-annotate-minor-mode)
     99      (symbol ,#'marginalia-annotate-symbol)
    100      (environment-variable ,#'marginalia-annotate-environment-variable)
    101      (input-method ,#'marginalia-annotate-input-method)
    102      (coding-system ,#'marginalia-annotate-coding-system)
    103      (charset ,#'marginalia-annotate-charset)
    104      (package ,#'marginalia-annotate-package)
    105      (imenu ,#'marginalia-annotate-imenu)
    106      (bookmark ,#'marginalia-annotate-bookmark)
    107      (file ,#'marginalia-annotate-file)
    108      (project-file ,#'marginalia-annotate-project-file)
    109      (buffer ,#'marginalia-annotate-buffer)
    110      (library ,#'marginalia-annotate-library)
    111      (theme ,#'marginalia-annotate-theme)
    112      (tab ,#'marginalia-annotate-tab)
    113      (multi-category ,#'marginalia-annotate-multi-category)))
    114   "Annotator function registry.
    115 Associates completion categories with annotation functions.
    116 Each annotation function must return a string,
    117 which is appended to the completion candidate."
    118   :type '(alist :key-type symbol :value-type (repeat symbol)))
    119 
    120 (defcustom marginalia-classifiers
    121   (list #'marginalia-classify-by-command-name
    122         #'marginalia-classify-original-category
    123         #'marginalia-classify-by-prompt
    124         #'marginalia-classify-symbol)
    125   "List of functions to determine current completion category.
    126 Each function should take no arguments and return a symbol
    127 indicating the category, or nil to indicate it could not
    128 determine it."
    129   :type 'hook)
    130 
    131 (defcustom marginalia-prompt-categories
    132   '(("\\<customize group\\>" . customize-group)
    133     ("\\<M-x\\>" . command)
    134     ("\\<package\\>" . package)
    135     ("\\<bookmark\\>" . bookmark)
    136     ("\\<color\\>" . color)
    137     ("\\<face\\>" . face)
    138     ("\\<environment variable\\>" . environment-variable)
    139     ("\\<function\\|hook to remove\\>" . function)
    140     ("\\<variable\\>" . variable)
    141     ("\\<input method\\>" . input-method)
    142     ("\\<charset\\>" . charset)
    143     ("\\<coding system\\>" . coding-system)
    144     ("\\<minor mode\\>" . minor-mode)
    145     ("\\<kill-ring\\>" . kill-ring)
    146     ("\\<tab by name\\>" . tab)
    147     ("\\<library\\>" . library)
    148     ("\\<theme\\>" . theme))
    149   "Associates regexps to match against minibuffer prompts with categories.
    150 The prompts are matched case-insensitively."
    151   :type '(alist :key-type regexp :value-type symbol))
    152 
    153 (defcustom marginalia-censor-variables
    154   '("pass\\|auth-source-netrc-cache\\|auth-source-.*-nonce\\|api-?key")
    155   "The value of variables matching any of these regular expressions is not shown.
    156 This configuration variable is useful to hide variables which may
    157 hold sensitive data, e.g., passwords.  The variable names are
    158 matched case-sensitively."
    159   :type '(repeat (choice symbol regexp)))
    160 
    161 (defcustom marginalia-command-categories
    162   '((imenu . imenu)
    163     (recentf-open . file)
    164     (where-is . command))
    165   "Associate commands with a completion category.
    166 The value of `this-command' is used as key for the lookup."
    167   :type '(alist :key-type symbol :value-type symbol))
    168 
    169 (defgroup marginalia-faces nil
    170   "Faces used by `marginalia-mode'."
    171   :group 'marginalia
    172   :group 'faces)
    173 
    174 (defface marginalia-key
    175   '((t :inherit font-lock-keyword-face))
    176   "Face used to highlight keys.")
    177 
    178 (defface marginalia-type
    179   '((t :inherit marginalia-key))
    180   "Face used to highlight types.")
    181 
    182 (defface marginalia-char
    183   '((t :inherit marginalia-key))
    184   "Face used to highlight character annotations.")
    185 
    186 (defface marginalia-lighter
    187   '((t :inherit marginalia-size))
    188   "Face used to highlight minor mode lighters.")
    189 
    190 (defface marginalia-on
    191   '((t :inherit success))
    192   "Face used to signal enabled modes.")
    193 
    194 (defface marginalia-off
    195   '((t :inherit error))
    196   "Face used to signal disabled modes.")
    197 
    198 (defface marginalia-documentation
    199   '((t :inherit completions-annotations))
    200   "Face used to highlight documentation strings.")
    201 
    202 (defface marginalia-value
    203   '((t :inherit marginalia-key))
    204   "Face used to highlight general variable values.")
    205 
    206 (defface marginalia-null
    207   '((t :inherit font-lock-comment-face))
    208   "Face used to highlight null or unbound variable values.")
    209 
    210 (defface marginalia-true
    211   '((t :inherit font-lock-builtin-face))
    212   "Face used to highlight true variable values.")
    213 
    214 (defface marginalia-function
    215   '((t :inherit font-lock-function-name-face))
    216   "Face used to highlight function symbols.")
    217 
    218 (defface marginalia-symbol
    219   '((t :inherit font-lock-type-face))
    220   "Face used to highlight general symbols.")
    221 
    222 (defface marginalia-list
    223   '((t :inherit font-lock-constant-face))
    224   "Face used to highlight list expressions.")
    225 
    226 (defface marginalia-mode
    227   '((t :inherit marginalia-key))
    228   "Face used to highlight buffer major modes.")
    229 
    230 (defface marginalia-date
    231   '((t :inherit marginalia-key))
    232   "Face used to highlight dates.")
    233 
    234 (defface marginalia-version
    235   '((t :inherit marginalia-number))
    236   "Face used to highlight package versions.")
    237 
    238 (defface marginalia-archive
    239   '((t :inherit warning))
    240   "Face used to highlight package archives.")
    241 
    242 (defface marginalia-installed
    243   '((t :inherit success))
    244   "Face used to highlight the status of packages.")
    245 
    246 (defface marginalia-size
    247   '((t :inherit marginalia-number))
    248   "Face used to highlight sizes.")
    249 
    250 (defface marginalia-number
    251   '((t :inherit font-lock-constant-face))
    252   "Face used to highlight numeric values.")
    253 
    254 (defface marginalia-string
    255   '((t :inherit font-lock-string-face))
    256   "Face used to highlight string values.")
    257 
    258 (defface marginalia-modified
    259   '((t :inherit font-lock-negation-char-face))
    260   "Face used to highlight buffer modification indicators.")
    261 
    262 (defface marginalia-file-name
    263   '((t :inherit marginalia-documentation))
    264   "Face used to highlight file names.")
    265 
    266 (defface marginalia-file-owner
    267   '((t :inherit font-lock-preprocessor-face))
    268   "Face used to highlight file owner and group names.")
    269 
    270 (defface marginalia-file-priv-no
    271   '((t :inherit shadow))
    272   "Face used to highlight the no file privilege attribute.")
    273 
    274 (defface marginalia-file-priv-dir
    275   '((t :inherit font-lock-keyword-face))
    276   "Face used to highlight the dir file privilege attribute.")
    277 
    278 (defface marginalia-file-priv-link
    279   '((t :inherit font-lock-keyword-face))
    280   "Face used to highlight the link file privilege attribute.")
    281 
    282 (defface marginalia-file-priv-read
    283   '((t :inherit font-lock-type-face))
    284   "Face used to highlight the read file privilege attribute.")
    285 
    286 (defface marginalia-file-priv-write
    287   '((t :inherit font-lock-builtin-face))
    288   "Face used to highlight the write file privilege attribute.")
    289 
    290 (defface marginalia-file-priv-exec
    291   '((t :inherit font-lock-function-name-face))
    292   "Face used to highlight the exec file privilege attribute.")
    293 
    294 (defface marginalia-file-priv-other
    295   '((t :inherit font-lock-constant-face))
    296   "Face used to highlight some other file privilege attribute.")
    297 
    298 (defface marginalia-file-priv-rare
    299   '((t :inherit font-lock-variable-name-face))
    300   "Face used to highlight a rare file privilege attribute.")
    301 
    302 ;;;; Pre-declarations for external packages
    303 
    304 (declare-function bookmark-prop-get "bookmark")
    305 
    306 (declare-function project-current "project")
    307 
    308 (defvar package--builtins)
    309 (defvar package-archive-contents)
    310 (declare-function package--from-builtin "package")
    311 (declare-function package-desc-archive "package")
    312 (declare-function package-desc-status "package")
    313 (declare-function package-desc-summary "package")
    314 (declare-function package-desc-version "package")
    315 (declare-function package-version-join "package")
    316 
    317 (declare-function color-rgb-to-hex "color")
    318 (declare-function color-rgb-to-hsl "color")
    319 (declare-function color-hsl-to-rgb "color")
    320 
    321 ;;;; Marginalia mode
    322 
    323 (defvar marginalia--pangram "Cwm fjord bank glyphs vext quiz.")
    324 
    325 (defvar marginalia--bookmark-type-transforms
    326   (let ((words (regexp-opt '("handle" "handler" "jump" "bookmark"))))
    327     `((,(format "-+%s-+" words) . "-")
    328       (,(format "\\`%s-+" words) . "")
    329       (,(format "-%s\\'" words) . "")
    330       ("\\`default\\'" . "File")
    331       (".*" . ,#'capitalize)))
    332   "List of bookmark type transformers.
    333 Relying on this mechanism is discouraged in favor of the
    334 `bookmark-handler-type' property.  The function names are matched
    335 case-sensitively.")
    336 
    337 (defvar marginalia--cand-width-step 10
    338   "Round candidate width.")
    339 
    340 (defvar-local marginalia--cand-width-max 20
    341   "Maximum width of candidates.")
    342 
    343 (defvar marginalia--fontified-file-modes nil
    344   "List of fontified file modes.")
    345 
    346 (defvar-local marginalia--cache nil
    347   "The cache, pair of list and hashtable.")
    348 
    349 (defvar marginalia--cache-size 100
    350   "Size of the cache, set to 0 to disable the cache.
    351 Disabling the cache is useful on non-incremental UIs like default completion or
    352 for performance profiling of the annotators.")
    353 
    354 (defvar-local marginalia--command nil
    355   "Last command symbol saved in order to allow annotations.")
    356 
    357 (defvar-local marginalia--base-position 0
    358   "Last completion base position saved to get full file paths.")
    359 
    360 (defvar marginalia--metadata nil
    361   "Completion metadata from the current completion.")
    362 
    363 (defvar marginalia--ellipsis nil)
    364 (defun marginalia--ellipsis ()
    365   "Return ellipsis."
    366   (with-memoization marginalia--ellipsis
    367     (cond
    368      ((bound-and-true-p truncate-string-ellipsis))
    369      ((char-displayable-p ?…) "…")
    370      ("..."))))
    371 
    372 (defun marginalia--truncate (str width)
    373   "Truncate string STR to WIDTH."
    374   (when (floatp width) (setq width (round (* width marginalia-field-width))))
    375   (when-let (pos (string-search "\n" str))
    376     (setq str (substring str 0 pos)))
    377   (let* ((face (and (not (equal str ""))
    378                     (get-text-property (1- (length str)) 'face str)))
    379          (ell (if face
    380                   (propertize (marginalia--ellipsis) 'face face)
    381                 (marginalia--ellipsis)))
    382          (trunc
    383           (if (< width 0)
    384               (nreverse (truncate-string-to-width (reverse str) (- width) 0 ?\s ell))
    385             (truncate-string-to-width str width 0 ?\s ell))))
    386     (unless (string-prefix-p str trunc)
    387       (put-text-property 0 (length trunc) 'help-echo str trunc))
    388     trunc))
    389 
    390 (cl-defmacro marginalia--field (field &key truncate face width format)
    391   "Format FIELD as a string according to some options.
    392 TRUNCATE is the truncation width.
    393 WIDTH is the field width.
    394 FORMAT is a format string.
    395 FACE is the name of the face, with which the field should be propertized."
    396   (setq field (if format `(format ,format ,field) `(or ,field "")))
    397   (when width (setq field `(format ,(format "%%%ds" (- width)) ,field)))
    398   (when truncate (setq field `(marginalia--truncate ,field ,truncate)))
    399   (when face (setq field `(propertize ,field 'face ,face)))
    400   field)
    401 
    402 (defmacro marginalia--fields (&rest fields)
    403   "Format annotation FIELDS as a string with separators in between."
    404   (let ((left t))
    405     (cons 'concat
    406           (mapcan
    407            (lambda (field)
    408              (if (not (eq (car field) :left))
    409                  `(,@(when left (setq left nil) `(#(" " 0 1 (marginalia--align t))))
    410                    marginalia-separator (marginalia--field ,@field))
    411                (unless left (error "Left fields must come first"))
    412                `((marginalia--field ,@(cdr field)))))
    413            fields))))
    414 
    415 (defmacro marginalia--in-minibuffer (&rest body)
    416   "Run BODY inside minibuffer if minibuffer is active.
    417 Otherwise stay within current buffer."
    418   (declare (indent 0))
    419   `(with-current-buffer (if-let (win (active-minibuffer-window))
    420                             (window-buffer win)
    421                           (current-buffer))
    422      ,@body))
    423 
    424 (defun marginalia--documentation (str)
    425   "Format documentation string STR."
    426   (when str
    427     (marginalia--fields
    428      (str :truncate 1.0 :face 'marginalia-documentation))))
    429 
    430 (defun marginalia-annotate-binding (cand)
    431   "Annotate command CAND with keybinding."
    432   (when-let ((sym (intern-soft cand))
    433              (key (and (commandp sym) (where-is-internal sym nil 'first-only))))
    434     (format #(" (%s)" 1 5 (face marginalia-key)) (key-description key))))
    435 
    436 (defun marginalia--annotator (cat)
    437   "Return annotation function for category CAT."
    438   (pcase (car (alist-get cat marginalia-annotator-registry))
    439     ('none #'ignore)
    440     ('builtin nil)
    441     (fun fun)))
    442 
    443 (defun marginalia-annotate-multi-category (cand)
    444   "Annotate multi-category CAND with the buffer class."
    445   (if-let ((multi (get-text-property 0 'multi-category cand))
    446            (annotate (marginalia--annotator (car multi))))
    447       ;; Use the Marginalia annotator corresponding to the multi category.
    448       (funcall annotate (cdr multi))
    449     ;; Apply the original annotation function on the original candidate, if
    450     ;; there is one.  Use `alist-get' instead of `completion-metadata-get' to
    451     ;; bypass our `marginalia--completion-metadata-get' advice!
    452     (when-let (annotate (alist-get 'annotation-function marginalia--metadata))
    453       (funcall annotate cand))))
    454 
    455 (defconst marginalia--advice-regexp
    456   (rx bos
    457       (1+ (seq (? "This function has ")
    458                (or ":before" ":after" ":around" ":override"
    459                    ":before-while" ":before-until" ":after-while"
    460                    ":after-until" ":filter-args" ":filter-return")
    461                " advice: " (0+ nonl) "\n"))
    462       "\n")
    463   "Regexp to match lines about advice in function documentation strings.")
    464 
    465 ;; Taken from advice--make-docstring, is this robust?
    466 (defun marginalia--advised (fun)
    467   "Return t if function FUN is advised."
    468   (let ((flist (indirect-function fun)))
    469     (advice--p (if (eq 'macro (car-safe flist)) (cdr flist) flist))))
    470 
    471 (defun marginalia--symbol-class (s)
    472   "Return symbol class characters for symbol S.
    473 
    474 This function is an extension of `help--symbol-class'.  It returns
    475 more fine-grained and more detailed symbol information.
    476 
    477 Function:
    478 f function
    479 c command
    480 C interactive-only command
    481 m macro
    482 F special-form
    483 M module function
    484 P primitive
    485 g cl-generic
    486 p pure
    487 s side-effect-free
    488 @ autoloaded
    489 ! advised
    490 - obsolete
    491 & alias
    492 
    493 Variable:
    494 u custom (U modified compared to global value)
    495 v variable
    496 l local (L modified compared to default value)
    497 - obsolete
    498 & alias
    499 
    500 Other:
    501 a face
    502 t cl-type"
    503   (let ((class
    504          (append
    505           (when (fboundp s)
    506             (list
    507              (cond
    508               ((get s 'pure) '("p" . "pure"))
    509               ((get s 'side-effect-free) '("s" . "side-effect-free")))
    510              (cond
    511               ((commandp s)
    512                (if (get s 'interactive-only)
    513                    '("C" . "interactive-only command")
    514                  '("c" . "command")))
    515               ((cl-generic-p s) '("g" . "cl-generic"))
    516               ((macrop (symbol-function s)) '("m" . "macro"))
    517               ((special-form-p (symbol-function s)) '("F" . "special-form"))
    518               ((subr-primitive-p (symbol-function s)) '("P" . "primitive"))
    519               ((module-function-p (symbol-function s)) '("M" . "module function"))
    520               (t '("f" . "function")))
    521              (and (autoloadp (symbol-function s)) '("@" . "autoload"))
    522              (and (marginalia--advised s) '("!" . "advised"))
    523              (and (symbolp (symbol-function s))
    524                   (cons "&" (format "alias for `%s'" (symbol-function s))))
    525              (and (get s 'byte-obsolete-info) '("-" . "obsolete"))))
    526           (when (boundp s)
    527             (list
    528              (when (local-variable-if-set-p s)
    529                (if (ignore-errors
    530                      (not (equal (symbol-value s)
    531                                  (default-value s))))
    532                    '("L" . "local, modified from global")
    533                  '("l" . "local, unmodified")))
    534              (if (custom-variable-p s)
    535                  (if (ignore-errors
    536                        (not (equal (symbol-value s)
    537                                    (eval (car (get s 'standard-value))))))
    538                      '("U" . "custom, modified from standard")
    539                    '("u" . "custom, unmodified"))
    540                '("v" . "variable"))
    541              (and (not (eq (ignore-errors (indirect-variable s)) s))
    542                   (cons "&" (format "alias for `%s'" (ignore-errors (indirect-variable s)))))
    543              (and (get s 'byte-obsolete-variable) '("-" . "obsolete"))))
    544           (list
    545            (and (facep s) '("a" . "face"))
    546            (and (get s 'cl--class) '("t" . "cl-type")))))) ;; cl-find-class, cl--find-class
    547     (setq class (delq nil class))
    548     (propertize
    549      (format " %-6s" (mapconcat #'car class ""))
    550      'help-echo
    551      (mapconcat (pcase-lambda (`(,x . ,y)) (concat x " " y)) class "\n"))))
    552 
    553 (defun marginalia--function-doc (sym)
    554   "Documentation string of function SYM."
    555   (when-let (str (ignore-errors (documentation sym)))
    556     (save-match-data
    557       (if (string-match marginalia--advice-regexp str)
    558           (substring str (match-end 0))
    559         str))))
    560 
    561 ;; Derived from elisp-get-fnsym-args-string
    562 (defun marginalia--function-args (sym)
    563   "Return function arguments for SYM."
    564   (let ((tmp))
    565     (elisp-function-argstring
    566      (cond
    567       ((listp (setq tmp (gethash (indirect-function sym)
    568                                  advertised-signature-table t)))
    569        tmp)
    570       ((setq tmp (help-split-fundoc
    571                   (ignore-errors (documentation sym t))
    572                   sym))
    573        (substitute-command-keys (car tmp)))
    574       ((setq tmp (help-function-arglist sym))
    575        (and
    576         (if (and (stringp tmp)
    577                  (string-search "Arg list not available" tmp))
    578             ;; A shorter text fits better into the
    579             ;; limited Marginalia space.
    580             "[autoload]"
    581           tmp)))))))
    582 
    583 (defun marginalia-annotate-symbol (cand)
    584   "Annotate symbol CAND with its documentation string."
    585   (when-let (sym (intern-soft cand))
    586     (marginalia--fields
    587      (:left (marginalia-annotate-binding cand))
    588      ((marginalia--symbol-class sym) :face 'marginalia-type)
    589      ((if (fboundp sym) (marginalia--function-doc sym)
    590         (cl-loop
    591          for doc in '(variable-documentation
    592                       face-documentation
    593                       group-documentation)
    594          thereis (ignore-errors (documentation-property sym doc))))
    595       :truncate 1.0 :face 'marginalia-documentation)
    596      ((abbreviate-file-name (or (symbol-file sym) ""))
    597       :truncate -0.5 :face 'marginalia-file-name))))
    598 
    599 (defun marginalia-annotate-command (cand)
    600   "Annotate command CAND with its documentation string.
    601 Similar to `marginalia-annotate-symbol', but does not show symbol class."
    602   (when-let (sym (intern-soft cand))
    603     (concat
    604      (marginalia-annotate-binding cand)
    605      (marginalia--documentation (marginalia--function-doc sym)))))
    606 
    607 (defun marginalia-annotate-embark-keybinding (cand)
    608   "Annotate Embark keybinding CAND with its documentation string.
    609 Similar to `marginalia-annotate-command', but does not show the
    610 keybinding since CAND includes it."
    611   (when-let (cmd (get-text-property 0 'embark-command cand))
    612     (marginalia--documentation (marginalia--function-doc cmd))))
    613 
    614 (defun marginalia-annotate-imenu (cand)
    615   "Annotate imenu CAND with its documentation string."
    616   (when (derived-mode-p 'emacs-lisp-mode)
    617     ;; Strip until the last whitespace in order to support flat imenu
    618     (marginalia-annotate-symbol (replace-regexp-in-string "\\`.* " "" cand))))
    619 
    620 (defun marginalia-annotate-function (cand)
    621   "Annotate function CAND with its documentation string."
    622   (when-let (sym (intern-soft cand))
    623     (when (fboundp sym)
    624       (marginalia--fields
    625        (:left (marginalia-annotate-binding cand))
    626        ((marginalia--symbol-class sym) :face 'marginalia-type)
    627        ((marginalia--function-args sym) :face 'marginalia-value
    628         :truncate 0.5)
    629        ((marginalia--function-doc sym) :truncate 1.0
    630         :face 'marginalia-documentation)))))
    631 
    632 (defun marginalia--variable-value (sym)
    633   "Return the variable value of SYM as string."
    634   (cond
    635    ((not (boundp sym))
    636     (propertize "#<unbound>" 'face 'marginalia-null))
    637    ((and marginalia-censor-variables
    638          (let ((name (symbol-name sym))
    639                case-fold-search)
    640            (cl-loop for r in marginalia-censor-variables
    641                     thereis (if (symbolp r)
    642                                 (eq r sym)
    643                               (string-match-p r name)))))
    644     (propertize "*****"
    645                 'face 'marginalia-null
    646                 'help-echo "Hidden due to `marginalia-censor-variables'"))
    647    (t
    648     (let ((val (symbol-value sym)))
    649       (pcase val
    650         ('nil (propertize "nil" 'face 'marginalia-null))
    651         ('t (propertize "t" 'face 'marginalia-true))
    652         ((pred keymapp) (propertize "#<keymap>" 'face 'marginalia-value))
    653         ((pred bool-vector-p) (propertize "#<bool-vector>" 'face 'marginalia-value))
    654         ((pred hash-table-p) (propertize "#<hash-table>" 'face 'marginalia-value))
    655         ((pred syntax-table-p) (propertize "#<syntax-table>" 'face 'marginalia-value))
    656         ;; Emacs bug#53988: abbrev-table-p throws an error
    657         ((and (pred vectorp) (guard (ignore-errors (abbrev-table-p val))))
    658          (propertize "#<abbrev-table>" 'face 'marginalia-value))
    659         ((pred char-table-p) (propertize "#<char-table>" 'face 'marginalia-value))
    660         ;; Emacs 29 comes with callable objects or object closures (OClosures)
    661         ((guard (and (fboundp 'oclosure-type) (oclosure-type val)))
    662          (format (propertize "#<oclosure %s>" 'face 'marginalia-function)
    663                  (and (fboundp 'oclosure-type) (oclosure-type val))))
    664         ((pred byte-code-function-p) (propertize "#<byte-code-function>" 'face 'marginalia-function))
    665         ((and (pred functionp) (pred symbolp))
    666          ;; We are not consistent here, values are generally printed
    667          ;; unquoted. But we make an exception for function symbols to visually
    668          ;; distinguish them from symbols.  I am not entirely happy with this,
    669          ;; but we should not add quotation to every type.
    670          (format (propertize "#'%s" 'face 'marginalia-function) val))
    671         ((pred recordp) (format (propertize "#<record %s>" 'face 'marginalia-value) (type-of val)))
    672         ((pred symbolp) (propertize (symbol-name val) 'face 'marginalia-symbol))
    673         ((pred numberp) (propertize (number-to-string val) 'face 'marginalia-number))
    674         (_ (let ((print-escape-newlines t)
    675                  (print-escape-control-characters t)
    676                  ;;(print-escape-multibyte t)
    677                  (print-level 3)
    678                  (print-length marginalia-field-width))
    679              (propertize
    680               (replace-regexp-in-string
    681                ;; `print-escape-control-characters' does not escape Unicode control characters.
    682                "[\x0-\x1F\x7f-\x9f\x061c\x200e\x200f\x202a-\x202e\x2066-\x2069]"
    683                (lambda (x) (format "\\x%x" (string-to-char x)))
    684                (prin1-to-string
    685                 (if (stringp val)
    686                     ;; Get rid of string properties to save some of the precious space
    687                     (substring-no-properties
    688                      val 0
    689                      (min (length val) marginalia-field-width))
    690                   val))
    691                'fixedcase 'literal)
    692               'face
    693               (cond
    694                ((listp val) 'marginalia-list)
    695                ((stringp val) 'marginalia-string)
    696                (t 'marginalia-value))))))))))
    697 
    698 (defun marginalia-annotate-variable (cand)
    699   "Annotate variable CAND with its documentation string."
    700   (when-let (sym (intern-soft cand))
    701     (marginalia--fields
    702      ((marginalia--symbol-class sym) :face 'marginalia-type)
    703      ((marginalia--variable-value sym) :truncate 0.5)
    704      ((documentation-property sym 'variable-documentation)
    705       :truncate 1.0 :face 'marginalia-documentation))))
    706 
    707 (defun marginalia-annotate-environment-variable (cand)
    708   "Annotate environment variable CAND with its current value."
    709   (when-let (val (getenv cand))
    710     (marginalia--fields
    711      (val :truncate 1.0 :face 'marginalia-value))))
    712 
    713 (defun marginalia-annotate-face (cand)
    714   "Annotate face CAND with its documentation string and face example."
    715   (when-let (sym (intern-soft cand))
    716     (marginalia--fields
    717      ;; HACK: Manual alignment to fix misalignment due to face
    718      ((concat marginalia--pangram #(" " 0 1 (display (space :align-to center))))
    719       :face sym)
    720      ((documentation-property sym 'face-documentation)
    721       :truncate 1.0 :face 'marginalia-documentation))))
    722 
    723 (defun marginalia-annotate-color (cand)
    724   "Annotate face CAND with its documentation string and face example."
    725   (when-let (rgb (color-name-to-rgb cand))
    726     (pcase-let* ((`(,r ,g ,b) rgb)
    727                  (`(,h ,s ,l) (apply #'color-rgb-to-hsl rgb))
    728                  (cr (color-rgb-to-hex r 0 0))
    729                  (cg (color-rgb-to-hex 0 g 0))
    730                  (cb (color-rgb-to-hex 0 0 b))
    731                  (ch (apply #'color-rgb-to-hex (color-hsl-to-rgb h 1 0.5)))
    732                  (cs (apply #'color-rgb-to-hex (color-hsl-to-rgb h s 0.5)))
    733                  (cl (apply #'color-rgb-to-hex (color-hsl-to-rgb 0 0 l))))
    734       (marginalia--fields
    735        ("      " :face `(:background ,(apply #'color-rgb-to-hex rgb)))
    736        ((format
    737          "%s%s%s %s"
    738          (propertize "r" 'face `(:background ,cr :foreground ,(readable-foreground-color cr)))
    739          (propertize "g" 'face `(:background ,cg :foreground ,(readable-foreground-color cg)))
    740          (propertize "b" 'face `(:background ,cb :foreground ,(readable-foreground-color cb)))
    741          (color-rgb-to-hex r g b 2)))
    742        ((format
    743          "%s%s%s %3s° %3s%% %3s%%"
    744          (propertize "h" 'face `(:background ,ch :foreground ,(readable-foreground-color ch)))
    745          (propertize "s" 'face `(:background ,cs :foreground ,(readable-foreground-color cs)))
    746          (propertize "l" 'face `(:background ,cl :foreground ,(readable-foreground-color cl)))
    747          (round (* 360 h))
    748          (round (* 100 s))
    749          (round (* 100 l))))))))
    750 
    751 (defun marginalia-annotate-char (cand)
    752   "Annotate character CAND with its general character category and character code."
    753   (when-let (char (char-from-name cand t))
    754     (marginalia--fields
    755      (:left char :format" (%c)" :face 'marginalia-char)
    756      (char :format "%06X" :face 'marginalia-number)
    757      ((char-code-property-description
    758        'general-category
    759        (get-char-code-property char 'general-category))
    760       :width 30 :face 'marginalia-documentation))))
    761 
    762 (defun marginalia-annotate-minor-mode (cand)
    763   "Annotate minor-mode CAND with status and documentation string."
    764   (let* ((sym (intern-soft cand))
    765          (message-log-max nil)
    766          (mode (if (and sym (boundp sym))
    767                    sym
    768                  (lookup-minor-mode-from-indicator cand)))
    769          (lighter (cdr (assq mode minor-mode-alist)))
    770          (lighter-str (and lighter (string-trim (format-mode-line (cons t lighter))))))
    771     (marginalia--fields
    772      ((if (and (boundp mode) (symbol-value mode))
    773           (propertize "On" 'face 'marginalia-on)
    774         (propertize "Off" 'face 'marginalia-off)) :width 3)
    775      ((if (local-variable-if-set-p mode) "Local" "Global") :width 6 :face 'marginalia-type)
    776      (lighter-str :width 20 :face 'marginalia-lighter)
    777      ((marginalia--function-doc mode)
    778       :truncate 1.0 :face 'marginalia-documentation))))
    779 
    780 (defun marginalia-annotate-package (cand)
    781   "Annotate package CAND with its description summary."
    782   (when-let ((pkg-alist (bound-and-true-p package-alist))
    783              (name (replace-regexp-in-string "-[0-9\\.-]+\\'" "" cand))
    784              (pkg (intern-soft name))
    785              (desc (or (unless (equal name cand)
    786                          (cl-loop with version = (substring cand (1+ (length name)))
    787                                   for d in (alist-get pkg pkg-alist)
    788                                   if (equal (package-version-join (package-desc-version d)) version)
    789                                   return d))
    790                        ;; taken from `describe-package-1'
    791                        (car (alist-get pkg pkg-alist))
    792                        (if-let (built-in (assq pkg package--builtins))
    793                            (package--from-builtin built-in)
    794                          (car (alist-get pkg package-archive-contents))))))
    795     (marginalia--fields
    796      ((package-version-join (package-desc-version desc)) :truncate 16 :face 'marginalia-version)
    797      ((cond
    798        ((package-desc-archive desc) (propertize (package-desc-archive desc) 'face 'marginalia-archive))
    799        (t (propertize (or (package-desc-status desc) "orphan") 'face 'marginalia-installed))) :truncate 12)
    800      ((package-desc-summary desc) :truncate 1.0 :face 'marginalia-documentation))))
    801 
    802 (defun marginalia--bookmark-type (bm)
    803   "Return bookmark type string of BM.
    804 The string is transformed according to `marginalia--bookmark-type-transforms'."
    805   (let ((handler (or (bookmark-prop-get bm 'handler) 'bookmark-default-handler)))
    806     (and
    807      ;; Some libraries use lambda handlers instead of symbols. For
    808      ;; example the function `xwidget-webkit-bookmark-make-record' is
    809      ;; affected. I consider this bad style since then the lambda is
    810      ;; persisted.
    811      (symbolp handler)
    812      (or (get handler 'bookmark-handler-type)
    813          (let ((str (symbol-name handler))
    814                case-fold-search)
    815            (dolist (transformer marginalia--bookmark-type-transforms str)
    816              (when (string-match-p (car transformer) str)
    817                (setq str
    818                      (if (stringp (cdr transformer))
    819                          (replace-regexp-in-string (car transformer) (cdr transformer) str)
    820                        (funcall (cdr transformer) str))))))))))
    821 
    822 (defun marginalia-annotate-bookmark (cand)
    823   "Annotate bookmark CAND with its file name and front context string."
    824   (when-let ((bm (assoc cand (bound-and-true-p bookmark-alist))))
    825     (marginalia--fields
    826      ((marginalia--bookmark-type bm) :width 10 :face 'marginalia-type)
    827      ((or (bookmark-prop-get bm 'filename)
    828           (bookmark-prop-get bm 'location))
    829       :truncate (if (bookmark-prop-get bm 'filename) -0.5 0.5)
    830       :face 'marginalia-file-name)
    831      ((let ((front (or (bookmark-prop-get bm 'front-context-string) ""))
    832             (rear (or (bookmark-prop-get bm 'rear-context-string) "")))
    833         (unless (and (string-blank-p front) (string-blank-p rear))
    834           (string-clean-whitespace
    835            (concat front (marginalia--ellipsis) rear))))
    836       :truncate 0.5 :face 'marginalia-documentation))))
    837 
    838 (defun marginalia-annotate-customize-group (cand)
    839   "Annotate customization group CAND with its documentation string."
    840   (marginalia--documentation (documentation-property (intern cand) 'group-documentation)))
    841 
    842 (defun marginalia-annotate-input-method (cand)
    843   "Annotate input method CAND with its description."
    844   (marginalia--documentation (nth 4 (assoc cand input-method-alist))))
    845 
    846 (defun marginalia-annotate-charset (cand)
    847   "Annotate charset CAND with its description."
    848   (marginalia--documentation (charset-description (intern cand))))
    849 
    850 (defun marginalia-annotate-coding-system (cand)
    851   "Annotate coding system CAND with its description."
    852   (marginalia--documentation (coding-system-doc-string (intern cand))))
    853 
    854 (defun marginalia--buffer-status (buffer)
    855   "Return the status of BUFFER as a string."
    856   (format-mode-line '((:propertize "%1*%1+%1@" face marginalia-modified)
    857                       marginalia-separator
    858                       (7 (:propertize "%I" face marginalia-size))
    859                       marginalia-separator
    860                       ;; InactiveMinibuffer has 18 letters, but there are longer names.
    861                       ;; For example Org-Agenda produces very long mode names.
    862                       ;; Therefore we have to truncate.
    863                       (20 (-20 (:propertize mode-name face marginalia-mode))))
    864                     nil nil buffer))
    865 
    866 (defun marginalia--buffer-file (buffer)
    867   "Return the file or process name of BUFFER."
    868   (if-let (proc (get-buffer-process buffer))
    869       (format "(%s %s) %s"
    870               proc (process-status proc)
    871               (abbreviate-file-name (buffer-local-value 'default-directory buffer)))
    872     (abbreviate-file-name
    873      (or (cond
    874           ;; see ibuffer-buffer-file-name
    875           ((buffer-file-name buffer))
    876           ((when-let (dir (and (local-variable-p 'dired-directory buffer)
    877                                (buffer-local-value 'dired-directory buffer)))
    878              (expand-file-name (if (stringp dir) dir (car dir))
    879                                (buffer-local-value 'default-directory buffer))))
    880           ((local-variable-p 'list-buffers-directory buffer)
    881            (buffer-local-value 'list-buffers-directory buffer)))
    882          ""))))
    883 
    884 (defun marginalia-annotate-buffer (cand)
    885   "Annotate buffer CAND with modification status, file name and major mode."
    886   (when-let ((buffer (get-buffer cand)))
    887     (if (buffer-live-p buffer)
    888         (marginalia--fields
    889          ((marginalia--buffer-status buffer))
    890          ((marginalia--buffer-file buffer)
    891           :truncate -0.5 :face 'marginalia-file-name))
    892       (marginalia--fields ("(dead buffer)" :face 'error)))))
    893 
    894 (defun marginalia--full-candidate (cand)
    895   "Return completion candidate CAND in full.
    896 For some completion tables, the completion candidates offered are
    897 meant to be only a part of the full minibuffer contents.  For
    898 example, during file name completion the candidates are one path
    899 component of a full file path."
    900   (if-let (win (active-minibuffer-window))
    901       (with-current-buffer (window-buffer win)
    902         (concat (let ((end (minibuffer-prompt-end)))
    903                   (buffer-substring-no-properties
    904                    end (+ end marginalia--base-position)))
    905                 cand))
    906     ;; no minibuffer is active, trust that cand already conveys all
    907     ;; necessary information (there's not much else we can do)
    908     cand))
    909 
    910 (defun marginalia--remote-file-p (file)
    911   "Return non-nil if FILE is remote.
    912 The return value is a string describing the remote location,
    913 e.g., the protocol."
    914   (save-match-data
    915     (setq file (substitute-in-file-name file))
    916     (cl-loop for r in marginalia-remote-file-regexps
    917              if (string-match r file)
    918              return (or (match-string 1 file) "remote"))))
    919 
    920 (defun marginalia--annotate-local-file (cand)
    921   "Annotate local file CAND."
    922   (marginalia--in-minibuffer
    923     (when-let (attrs (ignore-errors
    924                        ;; may throw permission denied errors
    925                        (file-attributes (substitute-in-file-name
    926                                          (marginalia--full-candidate cand))
    927                                         'integer)))
    928       ;; HACK: Format differently accordingly to alignment, since the file owner
    929       ;; is usually not displayed. Otherwise we will see an excessive amount of
    930       ;; whitespace in front of the file permissions. Furthermore the alignment
    931       ;; in `consult-buffer' will look ugly. Find a better solution!
    932       (if (eq marginalia-align 'right)
    933           (marginalia--fields
    934            ;; File owner at the left
    935            ((marginalia--file-owner attrs) :face 'marginalia-file-owner)
    936            ((marginalia--file-modes attrs))
    937            ((marginalia--file-size attrs) :face 'marginalia-size :width -7)
    938            ((marginalia--time (file-attribute-modification-time attrs))
    939             :face 'marginalia-date :width -12))
    940         (marginalia--fields
    941          ((marginalia--file-modes attrs))
    942          ((marginalia--file-size attrs) :face 'marginalia-size :width -7)
    943          ((marginalia--time (file-attribute-modification-time attrs))
    944           :face 'marginalia-date :width -12)
    945          ;; File owner at the right
    946          ((marginalia--file-owner attrs) :face 'marginalia-file-owner))))))
    947 
    948 (defun marginalia-annotate-file (cand)
    949   "Annotate file CAND with its size, modification time and other attributes.
    950 These annotations are skipped for remote paths."
    951   (if-let (remote (or (marginalia--remote-file-p cand)
    952                       (when-let (win (active-minibuffer-window))
    953                         (with-current-buffer (window-buffer win)
    954                           (marginalia--remote-file-p (minibuffer-contents-no-properties))))))
    955       (marginalia--fields (remote :format "*%s*" :face 'marginalia-documentation))
    956     (marginalia--annotate-local-file cand)))
    957 
    958 (defun marginalia--file-owner (attrs)
    959   "Return file owner given ATTRS."
    960   (let ((uid (file-attribute-user-id attrs))
    961         (gid (file-attribute-group-id attrs)))
    962     (when (or (/= (user-uid) uid) (/= (group-gid) gid))
    963       (format "%s:%s"
    964               (or (user-login-name uid) uid)
    965               (or (group-name gid) gid)))))
    966 
    967 (defun marginalia--file-size (attrs)
    968   "Return formatted file size given ATTRS."
    969   (propertize (file-size-human-readable (file-attribute-size attrs))
    970               'help-echo (number-to-string (file-attribute-size attrs))))
    971 
    972 (defun marginalia--file-modes (attrs)
    973   "Return fontified file modes given the ATTRS."
    974   ;; Without caching this can a be significant portion of the time
    975   ;; `marginalia-annotate-file' takes to execute. Caching improves performance
    976   ;; by about a factor of 20.
    977   (setq attrs (file-attribute-modes attrs))
    978   (or (car (member attrs marginalia--fontified-file-modes))
    979       (progn
    980         (setq attrs (substring attrs)) ;; copy because attrs is about to be modified
    981         (dotimes (i (length attrs))
    982           (put-text-property
    983            i (1+ i) 'face
    984            (pcase (aref attrs i)
    985              (?- 'marginalia-file-priv-no)
    986              (?d 'marginalia-file-priv-dir)
    987              (?l 'marginalia-file-priv-link)
    988              (?r 'marginalia-file-priv-read)
    989              (?w 'marginalia-file-priv-write)
    990              (?x 'marginalia-file-priv-exec)
    991              ((or ?s ?S ?t ?T) 'marginalia-file-priv-other)
    992              (_ 'marginalia-file-priv-rare))
    993            attrs))
    994         (push attrs marginalia--fontified-file-modes)
    995         attrs)))
    996 
    997 (defconst marginalia--time-relative
    998   `((100 "sec" 1)
    999     (,(* 60 100) "min" 60.0)
   1000     (,(* 3600 30) "hour" 3600.0)
   1001     (,(* 3600 24 400) "day" ,(* 3600.0 24.0))
   1002     (nil "year" ,(* 365.25 24 3600)))
   1003   "Formatting used by the function `marginalia--time-relative'.")
   1004 
   1005 ;; Taken from `seconds-to-string'.
   1006 (defun marginalia--time-relative (time)
   1007   "Format TIME as a relative age."
   1008   (setq time (max 0 (float-time (time-since time))))
   1009   (let ((sts marginalia--time-relative) here)
   1010     (while (and (car (setq here (pop sts))) (<= (car here) time)))
   1011     (setq time (round time (caddr here)))
   1012     (format "%s %s%s ago" time (cadr here) (if (= time 1) "" "s"))))
   1013 
   1014 (defun marginalia--time-absolute (time)
   1015   "Format TIME as an absolute age."
   1016   (let ((system-time-locale "C"))
   1017     (format-time-string
   1018      (if (> (decoded-time-year (decode-time (current-time)))
   1019             (decoded-time-year (decode-time time)))
   1020          " %Y %b %d"
   1021        "%b %d %H:%M")
   1022      time)))
   1023 
   1024 (defun marginalia--time (time)
   1025   "Format file age TIME, suitably for use in annotations."
   1026   (propertize
   1027    (if (< (float-time (time-since time)) marginalia-max-relative-age)
   1028        (marginalia--time-relative time)
   1029      (marginalia--time-absolute time))
   1030    'help-echo (format-time-string "%Y-%m-%d %T" time)))
   1031 
   1032 (defvar-local marginalia--project-root 'unset)
   1033 (defun marginalia--project-root ()
   1034   "Return project root."
   1035   (marginalia--in-minibuffer
   1036     (when (eq marginalia--project-root 'unset)
   1037       (setq marginalia--project-root
   1038             (or (let ((prompt (minibuffer-prompt))
   1039                       case-fold-search)
   1040                   (and (string-match
   1041                         "\\`\\(?:Dired\\|Find file\\) in \\(.*\\): \\'"
   1042                         prompt)
   1043                        (match-string 1 prompt)))
   1044                 (when-let (proj (project-current))
   1045                   (cond
   1046                    ((fboundp 'project-root) (project-root proj))
   1047                    ((fboundp 'project-roots) (car (project-roots proj))))))))
   1048     marginalia--project-root))
   1049 
   1050 (defun marginalia-annotate-project-file (cand)
   1051   "Annotate file CAND with its size, modification time and other attributes."
   1052   ;; Absolute project directories also report project-file category
   1053   (if (file-name-absolute-p cand)
   1054       (marginalia-annotate-file cand)
   1055     (when-let (root (marginalia--project-root))
   1056       (marginalia-annotate-file (expand-file-name cand root)))))
   1057 
   1058 (defvar-local marginalia--library-cache nil)
   1059 (defun marginalia--library-cache ()
   1060   "Return hash table from library name to library file."
   1061   (marginalia--in-minibuffer
   1062     ;; `locate-file' and `locate-library' are bottlenecks for the
   1063     ;; annotator. Therefore we compute all the library paths first.
   1064     (unless marginalia--library-cache
   1065       (setq marginalia--library-cache (make-hash-table :test #'equal))
   1066       (dolist (dir (delete-dups
   1067                     (reverse ;; Reverse because of shadowing
   1068                      (append load-path (custom-theme--load-path))))) ;; Include themes
   1069         (dolist (file (ignore-errors
   1070                         (directory-files dir 'full
   1071                                          "\\.el\\(?:\\.gz\\)?\\'")))
   1072           (puthash (marginalia--library-name file)
   1073                    file marginalia--library-cache))))
   1074     marginalia--library-cache))
   1075 
   1076 (defun marginalia--library-name (file)
   1077   "Get name of library FILE."
   1078   (replace-regexp-in-string "\\(\\.gz\\|\\.elc?\\)+\\'" ""
   1079                             (file-name-nondirectory file)))
   1080 
   1081 (defun marginalia--library-doc (file)
   1082   "Return library documentation string for FILE."
   1083   (let ((doc (get-text-property 0 'marginalia--library-doc file)))
   1084     (unless doc
   1085       ;; Extract documentation string. We cannot use `lm-summary' here,
   1086       ;; since it decompresses the whole file, which is slower.
   1087       (setq doc (or (ignore-errors
   1088                       (let ((shell-file-name "sh")
   1089                             (shell-command-switch "-c"))
   1090                         (shell-command-to-string
   1091                          (format (if (string-suffix-p ".gz" file)
   1092                                      "gzip -c -q -d %s | head -n1"
   1093                                    "head -n1 %s")
   1094                                  (shell-quote-argument file)))))
   1095                     ""))
   1096       (cond
   1097        ((string-match "\\`(define-package\\s-+\"\\([^\"]+\\)\"" doc)
   1098         (setq doc (format "Generated package description from %s.el"
   1099                           (match-string 1 doc))))
   1100        ((string-match "\\`;+\\s-*" doc)
   1101         (setq doc (substring doc (match-end 0)))
   1102         (when (string-match "\\`[^ \t]+\\s-+-+\\s-+" doc)
   1103           (setq doc (substring doc (match-end 0))))
   1104         (when (string-match "\\s-*-\\*-" doc)
   1105           (setq doc (substring doc 0 (match-beginning 0)))))
   1106        (t (setq doc "")))
   1107       ;; Add the documentation string to the cache
   1108       (put-text-property 0 1 'marginalia--library-doc doc file))
   1109     doc))
   1110 
   1111 (defun marginalia-annotate-theme (cand)
   1112   "Annotate theme CAND with documentation and path."
   1113   (marginalia-annotate-library (concat cand "-theme")))
   1114 
   1115 (defun marginalia-annotate-library (cand)
   1116   "Annotate library CAND with documentation and path."
   1117   (setq cand (marginalia--library-name cand))
   1118   (when-let (file (gethash cand (marginalia--library-cache)))
   1119     (marginalia--fields
   1120      ;; Display if the corresponding feature is loaded.
   1121      ;; feature/=library file, but better than nothing.
   1122      ((when-let (sym (intern-soft cand))
   1123         (when (memq sym features)
   1124           (propertize "Loaded" 'face 'marginalia-on)))
   1125       :width 8)
   1126      ((marginalia--library-doc file)
   1127       :truncate 1.0 :face 'marginalia-documentation)
   1128      ((abbreviate-file-name (file-name-directory file))
   1129       :truncate -0.5 :face 'marginalia-file-name))))
   1130 
   1131 (defun marginalia-annotate-tab (cand)
   1132   "Annotate named tab CAND with tab index, window and buffer information."
   1133   (when-let ((tabs (funcall tab-bar-tabs-function))
   1134              (index (seq-position
   1135                      tabs nil
   1136                      (lambda (tab _) (equal (alist-get 'name tab) cand)))))
   1137     (let* ((tab (nth index tabs))
   1138            (ws (alist-get 'ws tab))
   1139            (bufs (window-state-buffers ws)))
   1140       ;; When the buffer key is present in the window state it is added in front
   1141       ;; of the window buffer list and gets duplicated.
   1142       (when (cadr (assq 'buffer ws)) (pop bufs))
   1143       (marginalia--fields
   1144        (:left (1+ index) :format " (%s)" :face 'marginalia-key)
   1145        ((if (eq (car tab) 'current-tab)
   1146             (length (window-list nil 'no-minibuf))
   1147           (length bufs))
   1148         :format "win:%s" :face 'marginalia-size)
   1149        ((or (alist-get 'group tab) 'none)
   1150         :format "group:%s" :face 'marginalia-type :truncate 20)
   1151        ((if (eq (car tab) 'current-tab)
   1152             "(current tab)"
   1153           (string-join bufs " "))
   1154         :face 'marginalia-documentation)))))
   1155 
   1156 (defun marginalia-classify-by-command-name ()
   1157   "Lookup category for current command."
   1158   (and marginalia--command
   1159        (or (alist-get marginalia--command marginalia-command-categories)
   1160            ;; The command can be an alias, e.g., `recentf' -> `recentf-open'.
   1161            (when-let ((chain (function-alias-p marginalia--command)))
   1162              (alist-get (car (last chain)) marginalia-command-categories)))))
   1163 
   1164 (defun marginalia-classify-original-category ()
   1165   "Return original category reported by completion metadata."
   1166   ;; Use `alist-get' instead of `completion-metadata-get' to bypass our
   1167   ;; `marginalia--completion-metadata-get' advice!
   1168   (when-let (cat (alist-get 'category marginalia--metadata))
   1169     ;; Ignore Emacs 28 symbol-help category in order to ensure that the
   1170     ;; categories are refined to our categories function and variable.
   1171     (and (not (eq cat 'symbol-help)) cat)))
   1172 
   1173 (defun marginalia-classify-symbol ()
   1174   "Determine if currently completing symbols."
   1175   (when-let (mct minibuffer-completion-table)
   1176     (when (or (eq mct 'help--symbol-completion-table)
   1177               (obarrayp mct)
   1178               (and (not (functionp mct)) (consp mct) (symbolp (car mct)))) ; assume list of symbols
   1179       'symbol)))
   1180 
   1181 (defun marginalia-classify-by-prompt ()
   1182   "Determine category by matching regexps against the minibuffer prompt.
   1183 This runs through the `marginalia-prompt-categories' alist
   1184 looking for a regexp that matches the prompt."
   1185   (when-let (prompt (minibuffer-prompt))
   1186     (setq prompt
   1187           (replace-regexp-in-string "(.*?default.*?)\\|\\[.*?\\]" "" prompt))
   1188     (cl-loop with case-fold-search = t
   1189              for (regexp . category) in marginalia-prompt-categories
   1190              when (string-match-p regexp prompt)
   1191              return category)))
   1192 
   1193 (defun marginalia--cache-reset (&rest _)
   1194   "Reset the cache."
   1195   (setq marginalia--cache (and marginalia--cache (> marginalia--cache-size 0)
   1196                                (cons nil (make-hash-table :test #'equal
   1197                                                           :size marginalia--cache-size)))))
   1198 
   1199 (defun marginalia--cached (cache fun key)
   1200   "Cached application of function FUN with KEY.
   1201 The CACHE keeps around the last `marginalia--cache-size' computed
   1202 annotations.  The cache is mainly useful when scrolling in
   1203 completion UIs like Vertico or Icomplete."
   1204   (if cache
   1205       (let ((ht (cdr cache)))
   1206         (or (gethash key ht)
   1207             (let ((val (funcall fun key)))
   1208               (push key (car cache))
   1209               (puthash key val ht)
   1210               (when (>= (hash-table-count ht) marginalia--cache-size)
   1211                 (let ((end (last (car cache) 2)))
   1212                   (remhash (cadr end) ht)
   1213                   (setcdr end nil)))
   1214               val)))
   1215     (funcall fun key)))
   1216 
   1217 (defun marginalia--align (cands)
   1218   "Align annotations of CANDS according to `marginalia-align'."
   1219   (cl-loop
   1220    for (cand . ann) in cands do
   1221    (when-let (align (text-property-any 0 (length ann) 'marginalia--align t ann))
   1222      (setq marginalia--cand-width-max
   1223            (max marginalia--cand-width-max
   1224                 (* (ceiling (+ (string-width cand)
   1225                                (compat-call string-width ann 0 align))
   1226                             marginalia--cand-width-step)
   1227                    marginalia--cand-width-step)))))
   1228   (cl-loop
   1229    for (cand . ann) in cands collect
   1230    (progn
   1231      (when-let (align (text-property-any 0 (length ann) 'marginalia--align t ann))
   1232        (put-text-property
   1233         align (1+ align) 'display
   1234         `(space :align-to
   1235                 ,(pcase-exhaustive marginalia-align
   1236                    ('center `(+ center ,marginalia-align-offset))
   1237                    ('left `(+ left ,(+ marginalia-align-offset marginalia--cand-width-max)))
   1238                    ('right `(+ right ,(+ marginalia-align-offset 1
   1239                                          (- (compat-call string-width ann 0 align)
   1240                                             (string-width ann)))))))
   1241         ann))
   1242      (list cand "" ann))))
   1243 
   1244 (defun marginalia--affixate (metadata annotator cands)
   1245   "Affixate CANDS given METADATA and Marginalia ANNOTATOR."
   1246   ;; Compute minimum width of windows, which display the minibuffer, including
   1247   ;; the miniwindow.  In general the computed width corresponds to the full
   1248   ;; frame width, since the miniwindow spans the full frame.  For example
   1249   ;; `vertico-buffer' displays the minibuffer in a separate window.  Similarly,
   1250   ;; we could detect other types of completion buffers, e.g., Embark Collect or
   1251   ;; the default completion buffer, and compute smaller widths.
   1252   (let* ((width (cl-loop for win in (get-buffer-window-list) minimize (window-width win)))
   1253          (marginalia-field-width (min (/ width 2) marginalia-field-width))
   1254          (marginalia--metadata metadata)
   1255          (cache marginalia--cache))
   1256     (marginalia--align
   1257      ;; Run the annotators in the original window. `with-selected-window'
   1258      ;; is necessary because of `lookup-minor-mode-from-indicator'.
   1259      ;; Otherwise it would suffice to only change the current buffer. We
   1260      ;; need the `selected-window' fallback for Embark Occur.
   1261      (with-selected-window (or (minibuffer-selected-window) (selected-window))
   1262        (cl-loop for cand in cands collect
   1263                 (let ((ann (or (marginalia--cached cache annotator cand) "")))
   1264                   (cons cand (if (string-blank-p ann) "" ann))))))))
   1265 
   1266 (defun marginalia--completion-metadata-get (metadata prop)
   1267   "Meant as :before-until advice for `completion-metadata-get'.
   1268 METADATA is the metadata.
   1269 PROP is the property which is looked up."
   1270   (pcase prop
   1271     ('annotation-function
   1272      ;; We do want the advice triggered for `completion-metadata-get'.
   1273      (when-let ((cat (completion-metadata-get metadata 'category))
   1274                 (annotator (marginalia--annotator cat)))
   1275        (lambda (cand)
   1276          (let ((ann (caddar (marginalia--affixate metadata annotator (list cand)))))
   1277            (and (not (equal ann "")) ann)))))
   1278     ('affixation-function
   1279      ;; We do want the advice triggered for `completion-metadata-get'.
   1280      (when-let ((cat (completion-metadata-get metadata 'category))
   1281                 (annotator (marginalia--annotator cat)))
   1282        (apply-partially #'marginalia--affixate metadata annotator)))
   1283     ('category
   1284      ;; Find the completion category by trying each of our classifiers.
   1285      ;; Store the metadata for `marginalia-classify-original-category'.
   1286      (let ((marginalia--metadata metadata))
   1287        (run-hook-with-args-until-success 'marginalia-classifiers)))))
   1288 
   1289 (defun marginalia--minibuffer-setup ()
   1290   "Setup the minibuffer for Marginalia.
   1291 Remember `this-command' for `marginalia-classify-by-command-name'."
   1292   (setq marginalia--cache t marginalia--command this-command)
   1293   ;; Reset cache if window size changes, recompute alignment
   1294   (add-hook 'window-state-change-hook #'marginalia--cache-reset nil 'local)
   1295   (marginalia--cache-reset))
   1296 
   1297 (defun marginalia--base-position (completions)
   1298   "Record the base position of COMPLETIONS."
   1299   ;; As a small optimization we track the base position only for file
   1300   ;; completions, since `marginalia--full-candidate' is currently used only by
   1301   ;; the file annotation function.
   1302   (when minibuffer-completing-file-name
   1303     (let ((base (or (cdr (last completions)) 0)))
   1304       (unless (= marginalia--base-position base)
   1305         (marginalia--cache-reset)
   1306         (setq marginalia--base-position base
   1307               marginalia--cand-width-max (default-value 'marginalia--cand-width-max)))))
   1308   completions)
   1309 
   1310 ;;;###autoload
   1311 (define-minor-mode marginalia-mode
   1312   "Annotate completion candidates with richer information."
   1313   :global t :group 'marginalia
   1314   (if marginalia-mode
   1315       (progn
   1316         ;; Remember `this-command' in order to select the annotation function.
   1317         (add-hook 'minibuffer-setup-hook #'marginalia--minibuffer-setup)
   1318         ;; Replace the metadata function.
   1319         (advice-add #'completion-metadata-get :before-until #'marginalia--completion-metadata-get)
   1320         ;; Record completion base position, for `marginalia--full-candidate'
   1321         (advice-add #'completion-all-completions :filter-return #'marginalia--base-position))
   1322     (advice-remove #'completion-all-completions #'marginalia--base-position)
   1323     (advice-remove #'completion-metadata-get #'marginalia--completion-metadata-get)
   1324     (remove-hook 'minibuffer-setup-hook #'marginalia--minibuffer-setup)))
   1325 
   1326 ;;;###autoload
   1327 (defun marginalia-cycle ()
   1328   "Cycle between annotators in `marginalia-annotator-registry'."
   1329   (interactive)
   1330   (with-current-buffer (window-buffer
   1331                         (or (active-minibuffer-window)
   1332                             (user-error "Marginalia: No active minibuffer")))
   1333     (let* ((end (minibuffer-prompt-end))
   1334            (pt (max 0 (- (point) end)))
   1335            (metadata (completion-metadata (buffer-substring-no-properties end (+ end pt))
   1336                                           minibuffer-completion-table
   1337                                           minibuffer-completion-predicate))
   1338            (cat (or (completion-metadata-get metadata 'category)
   1339                     (user-error "Marginalia: Unknown completion category")))
   1340            (ann (or (assq cat marginalia-annotator-registry)
   1341                     (user-error "Marginalia: No annotators found for category `%s'" cat))))
   1342       (marginalia--cache-reset)
   1343       (setcdr ann (append (cddr ann) (list (cadr ann))))
   1344       ;; When the builtin annotator is selected and no builtin function is
   1345       ;; available, skip to the next annotator. Note that we cannot use
   1346       ;; `completion-metadata-get' to access the metadata since we must
   1347       ;; bypass the `marginalia--completion-metadata-get' advice.
   1348       (when (and (eq (cadr ann) 'builtin)
   1349                  (not (assq 'annotation-function metadata))
   1350                  (not (assq 'affixation-function metadata))
   1351                  (not (plist-get completion-extra-properties :annotation-function))
   1352                  (not (plist-get completion-extra-properties :affixation-function)))
   1353         (setcdr ann (append (cddr ann) (list (cadr ann)))))
   1354       (message "Marginalia: Use annotator `%s' for category `%s'" (cadr ann) (car ann)))))
   1355 
   1356 ;; Emacs 28: Only show `marginalia-cycle' in M-x in recursive minibuffers
   1357 (put #'marginalia-cycle 'completion-predicate
   1358      (lambda (&rest _) (> (minibuffer-depth) 1)))
   1359 
   1360 (provide 'marginalia)
   1361 ;;; marginalia.el ends here