config

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

marginalia.el (58177B)


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