marginalia.el (57742B)
1 ;;; marginalia.el --- Enrich existing commands with completion annotations -*- lexical-binding: t -*- 2 3 ;; Copyright (C) 2021-2023 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 '(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 ((cond 590 ((fboundp sym) (marginalia--function-doc sym)) 591 ((facep sym) (documentation-property sym 'face-documentation)) 592 (t (documentation-property sym 'variable-documentation))) 593 :truncate 1.0 :face 'marginalia-documentation) 594 ((abbreviate-file-name (or (symbol-file sym) "")) 595 :truncate -0.5 :face 'marginalia-file-name)))) 596 597 (defun marginalia-annotate-command (cand) 598 "Annotate command CAND with its documentation string. 599 Similar to `marginalia-annotate-symbol', but does not show symbol class." 600 (when-let (sym (intern-soft cand)) 601 (concat 602 (marginalia-annotate-binding cand) 603 (marginalia--documentation (marginalia--function-doc sym))))) 604 605 (defun marginalia-annotate-embark-keybinding (cand) 606 "Annotate Embark keybinding CAND with its documentation string. 607 Similar to `marginalia-annotate-command', but does not show the 608 keybinding since CAND includes it." 609 (when-let (cmd (get-text-property 0 'embark-command cand)) 610 (marginalia--documentation (marginalia--function-doc cmd)))) 611 612 (defun marginalia-annotate-imenu (cand) 613 "Annotate imenu CAND with its documentation string." 614 (when (derived-mode-p 'emacs-lisp-mode) 615 ;; Strip until the last whitespace in order to support flat imenu 616 (marginalia-annotate-symbol (replace-regexp-in-string "\\`.* " "" cand)))) 617 618 (defun marginalia-annotate-function (cand) 619 "Annotate function CAND with its documentation string." 620 (when-let (sym (intern-soft cand)) 621 (when (fboundp sym) 622 (marginalia--fields 623 (:left (marginalia-annotate-binding cand)) 624 ((marginalia--symbol-class sym) :face 'marginalia-type) 625 ((marginalia--function-args sym) :face 'marginalia-value 626 :truncate 0.5) 627 ((marginalia--function-doc sym) :truncate 1.0 628 :face 'marginalia-documentation))))) 629 630 (defun marginalia--variable-value (sym) 631 "Return the variable value of SYM as string." 632 (cond 633 ((not (boundp sym)) 634 (propertize "#<unbound>" 'face 'marginalia-null)) 635 ((and marginalia-censor-variables 636 (let ((name (symbol-name sym)) 637 case-fold-search) 638 (cl-loop for r in marginalia-censor-variables 639 thereis (if (symbolp r) 640 (eq r sym) 641 (string-match-p r name))))) 642 (propertize "*****" 643 'face 'marginalia-null 644 'help-echo "Hidden due to `marginalia-censor-variables'")) 645 (t 646 (let ((val (symbol-value sym))) 647 (pcase val 648 ('nil (propertize "nil" 'face 'marginalia-null)) 649 ('t (propertize "t" 'face 'marginalia-true)) 650 ((pred keymapp) (propertize "#<keymap>" 'face 'marginalia-value)) 651 ((pred bool-vector-p) (propertize "#<bool-vector>" 'face 'marginalia-value)) 652 ((pred hash-table-p) (propertize "#<hash-table>" 'face 'marginalia-value)) 653 ((pred syntax-table-p) (propertize "#<syntax-table>" 'face 'marginalia-value)) 654 ;; Emacs bug#53988: abbrev-table-p throws an error 655 ((and (pred vectorp) (guard (ignore-errors (abbrev-table-p val)))) 656 (propertize "#<abbrev-table>" 'face 'marginalia-value)) 657 ((pred char-table-p) (propertize "#<char-table>" 'face 'marginalia-value)) 658 ;; Emacs 29 comes with callable objects or object closures (OClosures) 659 ((guard (and (fboundp 'oclosure-type) (oclosure-type val))) 660 (format (propertize "#<oclosure %s>" 'face 'marginalia-function) 661 (and (fboundp 'oclosure-type) (oclosure-type val)))) 662 ((pred byte-code-function-p) (propertize "#<byte-code-function>" 'face 'marginalia-function)) 663 ((and (pred functionp) (pred symbolp)) 664 ;; We are not consistent here, values are generally printed 665 ;; unquoted. But we make an exception for function symbols to visually 666 ;; distinguish them from symbols. I am not entirely happy with this, 667 ;; but we should not add quotation to every type. 668 (format (propertize "#'%s" 'face 'marginalia-function) val)) 669 ((pred recordp) (format (propertize "#<record %s>" 'face 'marginalia-value) (type-of val))) 670 ((pred symbolp) (propertize (symbol-name val) 'face 'marginalia-symbol)) 671 ((pred numberp) (propertize (number-to-string val) 'face 'marginalia-number)) 672 (_ (let ((print-escape-newlines t) 673 (print-escape-control-characters t) 674 ;;(print-escape-multibyte t) 675 (print-level 3) 676 (print-length marginalia-field-width)) 677 (propertize 678 (replace-regexp-in-string 679 ;; `print-escape-control-characters' does not escape Unicode control characters. 680 "[\x0-\x1F\x7f-\x9f\x061c\x200e\x200f\x202a-\x202e\x2066-\x2069]" 681 (lambda (x) (format "\\x%x" (string-to-char x))) 682 (prin1-to-string 683 (if (stringp val) 684 ;; Get rid of string properties to save some of the precious space 685 (substring-no-properties 686 val 0 687 (min (length val) marginalia-field-width)) 688 val)) 689 'fixedcase 'literal) 690 'face 691 (cond 692 ((listp val) 'marginalia-list) 693 ((stringp val) 'marginalia-string) 694 (t 'marginalia-value)))))))))) 695 696 (defun marginalia-annotate-variable (cand) 697 "Annotate variable CAND with its documentation string." 698 (when-let (sym (intern-soft cand)) 699 (marginalia--fields 700 ((marginalia--symbol-class sym) :face 'marginalia-type) 701 ((marginalia--variable-value sym) :truncate 0.5) 702 ((documentation-property sym 'variable-documentation) 703 :truncate 1.0 :face 'marginalia-documentation)))) 704 705 (defun marginalia-annotate-environment-variable (cand) 706 "Annotate environment variable CAND with its current value." 707 (when-let (val (getenv cand)) 708 (marginalia--fields 709 (val :truncate 1.0 :face 'marginalia-value)))) 710 711 (defun marginalia-annotate-face (cand) 712 "Annotate face CAND with its documentation string and face example." 713 (when-let (sym (intern-soft cand)) 714 (marginalia--fields 715 ;; HACK: Manual alignment to fix misalignment due to face 716 ((concat marginalia--pangram #(" " 0 1 (display (space :align-to center)))) 717 :face sym) 718 ((documentation-property sym 'face-documentation) 719 :truncate 1.0 :face 'marginalia-documentation)))) 720 721 (defun marginalia-annotate-color (cand) 722 "Annotate face CAND with its documentation string and face example." 723 (when-let (rgb (color-name-to-rgb cand)) 724 (pcase-let* ((`(,r ,g ,b) rgb) 725 (`(,h ,s ,l) (apply #'color-rgb-to-hsl rgb)) 726 (cr (color-rgb-to-hex r 0 0)) 727 (cg (color-rgb-to-hex 0 g 0)) 728 (cb (color-rgb-to-hex 0 0 b)) 729 (ch (apply #'color-rgb-to-hex (color-hsl-to-rgb h 1 0.5))) 730 (cs (apply #'color-rgb-to-hex (color-hsl-to-rgb h s 0.5))) 731 (cl (apply #'color-rgb-to-hex (color-hsl-to-rgb 0 0 l)))) 732 (marginalia--fields 733 (" " :face `(:background ,(apply #'color-rgb-to-hex rgb))) 734 ((format 735 "%s%s%s %s" 736 (propertize "r" 'face `(:background ,cr :foreground ,(readable-foreground-color cr))) 737 (propertize "g" 'face `(:background ,cg :foreground ,(readable-foreground-color cg))) 738 (propertize "b" 'face `(:background ,cb :foreground ,(readable-foreground-color cb))) 739 (color-rgb-to-hex r g b 2))) 740 ((format 741 "%s%s%s %3s° %3s%% %3s%%" 742 (propertize "h" 'face `(:background ,ch :foreground ,(readable-foreground-color ch))) 743 (propertize "s" 'face `(:background ,cs :foreground ,(readable-foreground-color cs))) 744 (propertize "l" 'face `(:background ,cl :foreground ,(readable-foreground-color cl))) 745 (round (* 360 h)) 746 (round (* 100 s)) 747 (round (* 100 l)))))))) 748 749 (defun marginalia-annotate-char (cand) 750 "Annotate character CAND with its general character category and character code." 751 (when-let (char (char-from-name cand t)) 752 (marginalia--fields 753 (:left char :format" (%c)" :face 'marginalia-char) 754 (char :format "%06X" :face 'marginalia-number) 755 ((char-code-property-description 756 'general-category 757 (get-char-code-property char 'general-category)) 758 :width 30 :face 'marginalia-documentation)))) 759 760 (defun marginalia-annotate-minor-mode (cand) 761 "Annotate minor-mode CAND with status and documentation string." 762 (let* ((sym (intern-soft cand)) 763 (message-log-max nil) 764 (mode (if (and sym (boundp sym)) 765 sym 766 (lookup-minor-mode-from-indicator cand))) 767 (lighter (cdr (assq mode minor-mode-alist))) 768 (lighter-str (and lighter (string-trim (format-mode-line (cons t lighter)))))) 769 (marginalia--fields 770 ((if (and (boundp mode) (symbol-value mode)) 771 (propertize "On" 'face 'marginalia-on) 772 (propertize "Off" 'face 'marginalia-off)) :width 3) 773 ((if (local-variable-if-set-p mode) "Local" "Global") :width 6 :face 'marginalia-type) 774 (lighter-str :width 20 :face 'marginalia-lighter) 775 ((marginalia--function-doc mode) 776 :truncate 1.0 :face 'marginalia-documentation)))) 777 778 (defun marginalia-annotate-package (cand) 779 "Annotate package CAND with its description summary." 780 (when-let ((pkg-alist (bound-and-true-p package-alist)) 781 (name (replace-regexp-in-string "-[0-9\\.-]+\\'" "" cand)) 782 (pkg (intern-soft name)) 783 (desc (or (unless (equal name cand) 784 (cl-loop with version = (substring cand (1+ (length name))) 785 for d in (alist-get pkg pkg-alist) 786 if (equal (package-version-join (package-desc-version d)) version) 787 return d)) 788 ;; taken from `describe-package-1' 789 (car (alist-get pkg pkg-alist)) 790 (if-let (built-in (assq pkg package--builtins)) 791 (package--from-builtin built-in) 792 (car (alist-get pkg package-archive-contents)))))) 793 (marginalia--fields 794 ((package-version-join (package-desc-version desc)) :truncate 16 :face 'marginalia-version) 795 ((cond 796 ((package-desc-archive desc) (propertize (package-desc-archive desc) 'face 'marginalia-archive)) 797 (t (propertize (or (package-desc-status desc) "orphan") 'face 'marginalia-installed))) :truncate 12) 798 ((package-desc-summary desc) :truncate 1.0 :face 'marginalia-documentation)))) 799 800 (defun marginalia--bookmark-type (bm) 801 "Return bookmark type string of BM. 802 The string is transformed according to `marginalia--bookmark-type-transforms'." 803 (let ((handler (or (bookmark-prop-get bm 'handler) 'bookmark-default-handler))) 804 (and 805 ;; Some libraries use lambda handlers instead of symbols. For 806 ;; example the function `xwidget-webkit-bookmark-make-record' is 807 ;; affected. I consider this bad style since then the lambda is 808 ;; persisted. 809 (symbolp handler) 810 (or (get handler 'bookmark-handler-type) 811 (let ((str (symbol-name handler)) 812 case-fold-search) 813 (dolist (transformer marginalia--bookmark-type-transforms str) 814 (when (string-match-p (car transformer) str) 815 (setq str 816 (if (stringp (cdr transformer)) 817 (replace-regexp-in-string (car transformer) (cdr transformer) str) 818 (funcall (cdr transformer) str)))))))))) 819 820 (defun marginalia-annotate-bookmark (cand) 821 "Annotate bookmark CAND with its file name and front context string." 822 (when-let ((bm (assoc cand (bound-and-true-p bookmark-alist)))) 823 (marginalia--fields 824 ((marginalia--bookmark-type bm) :width 10 :face 'marginalia-type) 825 ((or (bookmark-prop-get bm 'filename) 826 (bookmark-prop-get bm 'location)) 827 :truncate (if (bookmark-prop-get bm 'filename) -0.5 0.5) 828 :face 'marginalia-file-name) 829 ((let ((front (or (bookmark-prop-get bm 'front-context-string) "")) 830 (rear (or (bookmark-prop-get bm 'rear-context-string) ""))) 831 (unless (and (string-blank-p front) (string-blank-p rear)) 832 (string-clean-whitespace 833 (concat front (marginalia--ellipsis) rear)))) 834 :truncate 0.5 :face 'marginalia-documentation)))) 835 836 (defun marginalia-annotate-customize-group (cand) 837 "Annotate customization group CAND with its documentation string." 838 (marginalia--documentation (documentation-property (intern cand) 'group-documentation))) 839 840 (defun marginalia-annotate-input-method (cand) 841 "Annotate input method CAND with its description." 842 (marginalia--documentation (nth 4 (assoc cand input-method-alist)))) 843 844 (defun marginalia-annotate-charset (cand) 845 "Annotate charset CAND with its description." 846 (marginalia--documentation (charset-description (intern cand)))) 847 848 (defun marginalia-annotate-coding-system (cand) 849 "Annotate coding system CAND with its description." 850 (marginalia--documentation (coding-system-doc-string (intern cand)))) 851 852 (defun marginalia--buffer-status (buffer) 853 "Return the status of BUFFER as a string." 854 (format-mode-line '((:propertize "%1*%1+%1@" face marginalia-modified) 855 marginalia-separator 856 (7 (:propertize "%I" face marginalia-size)) 857 marginalia-separator 858 ;; InactiveMinibuffer has 18 letters, but there are longer names. 859 ;; For example Org-Agenda produces very long mode names. 860 ;; Therefore we have to truncate. 861 (20 (-20 (:propertize mode-name face marginalia-mode)))) 862 nil nil buffer)) 863 864 (defun marginalia--buffer-file (buffer) 865 "Return the file or process name of BUFFER." 866 (if-let (proc (get-buffer-process buffer)) 867 (format "(%s %s) %s" 868 proc (process-status proc) 869 (abbreviate-file-name (buffer-local-value 'default-directory buffer))) 870 (abbreviate-file-name 871 (or (cond 872 ;; see ibuffer-buffer-file-name 873 ((buffer-file-name buffer)) 874 ((when-let (dir (and (local-variable-p 'dired-directory buffer) 875 (buffer-local-value 'dired-directory buffer))) 876 (expand-file-name (if (stringp dir) dir (car dir)) 877 (buffer-local-value 'default-directory buffer)))) 878 ((local-variable-p 'list-buffers-directory buffer) 879 (buffer-local-value 'list-buffers-directory buffer))) 880 "")))) 881 882 (defun marginalia-annotate-buffer (cand) 883 "Annotate buffer CAND with modification status, file name and major mode." 884 (when-let (buffer (get-buffer cand)) 885 (marginalia--fields 886 ((marginalia--buffer-status buffer)) 887 ((marginalia--buffer-file buffer) 888 :truncate -0.5 :face 'marginalia-file-name)))) 889 890 (defun marginalia--full-candidate (cand) 891 "Return completion candidate CAND in full. 892 For some completion tables, the completion candidates offered are 893 meant to be only a part of the full minibuffer contents. For 894 example, during file name completion the candidates are one path 895 component of a full file path." 896 (if-let (win (active-minibuffer-window)) 897 (with-current-buffer (window-buffer win) 898 (concat (let ((end (minibuffer-prompt-end))) 899 (buffer-substring-no-properties 900 end (+ end marginalia--base-position))) 901 cand)) 902 ;; no minibuffer is active, trust that cand already conveys all 903 ;; necessary information (there's not much else we can do) 904 cand)) 905 906 (defun marginalia--remote-file-p (file) 907 "Return non-nil if FILE is remote. 908 The return value is a string describing the remote location, 909 e.g., the protocol." 910 (save-match-data 911 (setq file (substitute-in-file-name file)) 912 (cl-loop for r in marginalia-remote-file-regexps 913 if (string-match r file) 914 return (or (match-string 1 file) "remote")))) 915 916 (defun marginalia--annotate-local-file (cand) 917 "Annotate local file CAND." 918 (marginalia--in-minibuffer 919 (when-let (attrs (ignore-errors 920 ;; may throw permission denied errors 921 (file-attributes (substitute-in-file-name 922 (marginalia--full-candidate cand)) 923 'integer))) 924 ;; HACK: Format differently accordingly to alignment, since the file owner 925 ;; is usually not displayed. Otherwise we will see an excessive amount of 926 ;; whitespace in front of the file permissions. Furthermore the alignment 927 ;; in `consult-buffer' will look ugly. Find a better solution! 928 (if (eq marginalia-align 'right) 929 (marginalia--fields 930 ;; File owner at the left 931 ((marginalia--file-owner attrs) :face 'marginalia-file-owner) 932 ((marginalia--file-modes attrs)) 933 ((marginalia--file-size attrs) :face 'marginalia-size :width -7) 934 ((marginalia--time (file-attribute-modification-time attrs)) 935 :face 'marginalia-date :width -12)) 936 (marginalia--fields 937 ((marginalia--file-modes attrs)) 938 ((marginalia--file-size attrs) :face 'marginalia-size :width -7) 939 ((marginalia--time (file-attribute-modification-time attrs)) 940 :face 'marginalia-date :width -12) 941 ;; File owner at the right 942 ((marginalia--file-owner attrs) :face 'marginalia-file-owner)))))) 943 944 (defun marginalia-annotate-file (cand) 945 "Annotate file CAND with its size, modification time and other attributes. 946 These annotations are skipped for remote paths." 947 (if-let (remote (or (marginalia--remote-file-p cand) 948 (when-let (win (active-minibuffer-window)) 949 (with-current-buffer (window-buffer win) 950 (marginalia--remote-file-p (minibuffer-contents-no-properties)))))) 951 (marginalia--fields (remote :format "*%s*" :face 'marginalia-documentation)) 952 (marginalia--annotate-local-file cand))) 953 954 (defun marginalia--file-owner (attrs) 955 "Return file owner given ATTRS." 956 (let ((uid (file-attribute-user-id attrs)) 957 (gid (file-attribute-group-id attrs))) 958 (when (or (/= (user-uid) uid) (/= (group-gid) gid)) 959 (format "%s:%s" 960 (or (user-login-name uid) uid) 961 (or (group-name gid) gid))))) 962 963 (defun marginalia--file-size (attrs) 964 "Return formatted file size given ATTRS." 965 (propertize (file-size-human-readable (file-attribute-size attrs)) 966 'help-echo (number-to-string (file-attribute-size attrs)))) 967 968 (defun marginalia--file-modes (attrs) 969 "Return fontified file modes given the ATTRS." 970 ;; Without caching this can a be significant portion of the time 971 ;; `marginalia-annotate-file' takes to execute. Caching improves performance 972 ;; by about a factor of 20. 973 (setq attrs (file-attribute-modes attrs)) 974 (or (car (member attrs marginalia--fontified-file-modes)) 975 (progn 976 (setq attrs (substring attrs)) ;; copy because attrs is about to be modified 977 (dotimes (i (length attrs)) 978 (put-text-property 979 i (1+ i) 'face 980 (pcase (aref attrs i) 981 (?- 'marginalia-file-priv-no) 982 (?d 'marginalia-file-priv-dir) 983 (?l 'marginalia-file-priv-link) 984 (?r 'marginalia-file-priv-read) 985 (?w 'marginalia-file-priv-write) 986 (?x 'marginalia-file-priv-exec) 987 ((or ?s ?S ?t ?T) 'marginalia-file-priv-other) 988 (_ 'marginalia-file-priv-rare)) 989 attrs)) 990 (push attrs marginalia--fontified-file-modes) 991 attrs))) 992 993 (defconst marginalia--time-relative 994 `((100 "sec" 1) 995 (,(* 60 100) "min" 60.0) 996 (,(* 3600 30) "hour" 3600.0) 997 (,(* 3600 24 400) "day" ,(* 3600.0 24.0)) 998 (nil "year" ,(* 365.25 24 3600))) 999 "Formatting used by the function `marginalia--time-relative'.") 1000 1001 ;; Taken from `seconds-to-string'. 1002 (defun marginalia--time-relative (time) 1003 "Format TIME as a relative age." 1004 (setq time (max 0 (float-time (time-since time)))) 1005 (let ((sts marginalia--time-relative) here) 1006 (while (and (car (setq here (pop sts))) (<= (car here) time))) 1007 (setq time (round time (caddr here))) 1008 (format "%s %s%s ago" time (cadr here) (if (= time 1) "" "s")))) 1009 1010 (defun marginalia--time-absolute (time) 1011 "Format TIME as an absolute age." 1012 (let ((system-time-locale "C")) 1013 (format-time-string 1014 (if (> (decoded-time-year (decode-time (current-time))) 1015 (decoded-time-year (decode-time time))) 1016 " %Y %b %d" 1017 "%b %d %H:%M") 1018 time))) 1019 1020 (defun marginalia--time (time) 1021 "Format file age TIME, suitably for use in annotations." 1022 (propertize 1023 (if (< (float-time (time-since time)) marginalia-max-relative-age) 1024 (marginalia--time-relative time) 1025 (marginalia--time-absolute time)) 1026 'help-echo (format-time-string "%Y-%m-%d %T" time))) 1027 1028 (defvar-local marginalia--project-root 'unset) 1029 (defun marginalia--project-root () 1030 "Return project root." 1031 (marginalia--in-minibuffer 1032 (when (eq marginalia--project-root 'unset) 1033 (setq marginalia--project-root 1034 (or (let ((prompt (minibuffer-prompt)) 1035 case-fold-search) 1036 (and (string-match 1037 "\\`\\(?:Dired\\|Find file\\) in \\(.*\\): \\'" 1038 prompt) 1039 (match-string 1 prompt))) 1040 (when-let (proj (project-current)) 1041 (cond 1042 ((fboundp 'project-root) (project-root proj)) 1043 ((fboundp 'project-roots) (car (project-roots proj)))))))) 1044 marginalia--project-root)) 1045 1046 (defun marginalia-annotate-project-file (cand) 1047 "Annotate file CAND with its size, modification time and other attributes." 1048 ;; Absolute project directories also report project-file category 1049 (if (file-name-absolute-p cand) 1050 (marginalia-annotate-file cand) 1051 (when-let (root (marginalia--project-root)) 1052 (marginalia-annotate-file (expand-file-name cand root))))) 1053 1054 (defvar-local marginalia--library-cache nil) 1055 (defun marginalia--library-cache () 1056 "Return hash table from library name to library file." 1057 (marginalia--in-minibuffer 1058 ;; `locate-file' and `locate-library' are bottlenecks for the 1059 ;; annotator. Therefore we compute all the library paths first. 1060 (unless marginalia--library-cache 1061 (setq marginalia--library-cache (make-hash-table :test #'equal)) 1062 (dolist (dir (delete-dups 1063 (reverse ;; Reverse because of shadowing 1064 (append load-path (custom-theme--load-path))))) ;; Include themes 1065 (dolist (file (ignore-errors 1066 (directory-files dir 'full 1067 "\\.el\\(?:\\.gz\\)?\\'"))) 1068 (puthash (marginalia--library-name file) 1069 file marginalia--library-cache)))) 1070 marginalia--library-cache)) 1071 1072 (defun marginalia--library-name (file) 1073 "Get name of library FILE." 1074 (replace-regexp-in-string "\\(\\.gz\\|\\.elc?\\)+\\'" "" 1075 (file-name-nondirectory file))) 1076 1077 (defun marginalia--library-doc (file) 1078 "Return library documentation string for FILE." 1079 (let ((doc (get-text-property 0 'marginalia--library-doc file))) 1080 (unless doc 1081 ;; Extract documentation string. We cannot use `lm-summary' here, 1082 ;; since it decompresses the whole file, which is slower. 1083 (setq doc (or (ignore-errors 1084 (let ((shell-file-name "sh") 1085 (shell-command-switch "-c")) 1086 (shell-command-to-string 1087 (format (if (string-suffix-p ".gz" file) 1088 "gzip -c -q -d %s | head -n1" 1089 "head -n1 %s") 1090 (shell-quote-argument file))))) 1091 "")) 1092 (cond 1093 ((string-match "\\`(define-package\\s-+\"\\([^\"]+\\)\"" doc) 1094 (setq doc (format "Generated package description from %s.el" 1095 (match-string 1 doc)))) 1096 ((string-match "\\`;+\\s-*" doc) 1097 (setq doc (substring doc (match-end 0))) 1098 (when (string-match "\\`[^ \t]+\\s-+-+\\s-+" doc) 1099 (setq doc (substring doc (match-end 0)))) 1100 (when (string-match "\\s-*-\\*-" doc) 1101 (setq doc (substring doc 0 (match-beginning 0))))) 1102 (t (setq doc ""))) 1103 ;; Add the documentation string to the cache 1104 (put-text-property 0 1 'marginalia--library-doc doc file)) 1105 doc)) 1106 1107 (defun marginalia-annotate-theme (cand) 1108 "Annotate theme CAND with documentation and path." 1109 (marginalia-annotate-library (concat cand "-theme"))) 1110 1111 (defun marginalia-annotate-library (cand) 1112 "Annotate library CAND with documentation and path." 1113 (setq cand (marginalia--library-name cand)) 1114 (when-let (file (gethash cand (marginalia--library-cache))) 1115 (marginalia--fields 1116 ;; Display if the corresponding feature is loaded. 1117 ;; feature/=library file, but better than nothing. 1118 ((when-let (sym (intern-soft cand)) 1119 (when (memq sym features) 1120 (propertize "Loaded" 'face 'marginalia-on))) 1121 :width 8) 1122 ((marginalia--library-doc file) 1123 :truncate 1.0 :face 'marginalia-documentation) 1124 ((abbreviate-file-name (file-name-directory file)) 1125 :truncate -0.5 :face 'marginalia-file-name)))) 1126 1127 (defun marginalia-annotate-tab (cand) 1128 "Annotate named tab CAND with tab index, window and buffer information." 1129 (when-let ((tabs (funcall tab-bar-tabs-function)) 1130 (index (seq-position 1131 tabs nil 1132 (lambda (tab _) (equal (alist-get 'name tab) cand))))) 1133 (let* ((tab (nth index tabs)) 1134 (ws (alist-get 'ws tab)) 1135 (bufs (window-state-buffers ws))) 1136 ;; When the buffer key is present in the window state it is added in front 1137 ;; of the window buffer list and gets duplicated. 1138 (when (cadr (assq 'buffer ws)) (pop bufs)) 1139 (marginalia--fields 1140 (:left (1+ index) :format " (%s)" :face 'marginalia-key) 1141 ((if (eq (car tab) 'current-tab) 1142 (length (window-list nil 'no-minibuf)) 1143 (length bufs)) 1144 :format "win:%s" :face 'marginalia-size) 1145 ((or (alist-get 'group tab) 'none) 1146 :format "group:%s" :face 'marginalia-type :truncate 20) 1147 ((if (eq (car tab) 'current-tab) 1148 "(current tab)" 1149 (string-join bufs " ")) 1150 :face 'marginalia-documentation))))) 1151 1152 (defun marginalia-classify-by-command-name () 1153 "Lookup category for current command." 1154 (and marginalia--command 1155 (or (alist-get marginalia--command marginalia-command-categories) 1156 ;; The command can be an alias, e.g., `recentf' -> `recentf-open'. 1157 (when-let ((chain (function-alias-p marginalia--command))) 1158 (alist-get (car (last chain)) marginalia-command-categories))))) 1159 1160 (defun marginalia-classify-original-category () 1161 "Return original category reported by completion metadata." 1162 ;; Use `alist-get' instead of `completion-metadata-get' to bypass our 1163 ;; `marginalia--completion-metadata-get' advice! 1164 (when-let (cat (alist-get 'category marginalia--metadata)) 1165 ;; Ignore Emacs 28 symbol-help category in order to ensure that the 1166 ;; categories are refined to our categories function and variable. 1167 (and (not (eq cat 'symbol-help)) cat))) 1168 1169 (defun marginalia-classify-symbol () 1170 "Determine if currently completing symbols." 1171 (when-let (mct minibuffer-completion-table) 1172 (when (or (eq mct 'help--symbol-completion-table) 1173 (obarrayp mct) 1174 (and (not (functionp mct)) (consp mct) (symbolp (car mct)))) ; assume list of symbols 1175 'symbol))) 1176 1177 (defun marginalia-classify-by-prompt () 1178 "Determine category by matching regexps against the minibuffer prompt. 1179 This runs through the `marginalia-prompt-categories' alist 1180 looking for a regexp that matches the prompt." 1181 (when-let (prompt (minibuffer-prompt)) 1182 (setq prompt 1183 (replace-regexp-in-string "(.*?default.*?)\\|\\[.*?\\]" "" prompt)) 1184 (cl-loop with case-fold-search = t 1185 for (regexp . category) in marginalia-prompt-categories 1186 when (string-match-p regexp prompt) 1187 return category))) 1188 1189 (defun marginalia--cache-reset (&rest _) 1190 "Reset the cache." 1191 (setq marginalia--cache (and marginalia--cache (> marginalia--cache-size 0) 1192 (cons nil (make-hash-table :test #'equal 1193 :size marginalia--cache-size))))) 1194 1195 (defun marginalia--cached (cache fun key) 1196 "Cached application of function FUN with KEY. 1197 The CACHE keeps around the last `marginalia--cache-size' computed 1198 annotations. The cache is mainly useful when scrolling in 1199 completion UIs like Vertico or Icomplete." 1200 (if cache 1201 (let ((ht (cdr cache))) 1202 (or (gethash key ht) 1203 (let ((val (funcall fun key))) 1204 (push key (car cache)) 1205 (puthash key val ht) 1206 (when (>= (hash-table-count ht) marginalia--cache-size) 1207 (let ((end (last (car cache) 2))) 1208 (remhash (cadr end) ht) 1209 (setcdr end nil))) 1210 val))) 1211 (funcall fun key))) 1212 1213 (defun marginalia--align (cands) 1214 "Align annotations of CANDS according to `marginalia-align'." 1215 (cl-loop 1216 for (cand . ann) in cands do 1217 (when-let (align (text-property-any 0 (length ann) 'marginalia--align t ann)) 1218 (setq marginalia--cand-width-max 1219 (max marginalia--cand-width-max 1220 (* (ceiling (+ (string-width cand) 1221 (compat-call string-width ann 0 align)) 1222 marginalia--cand-width-step) 1223 marginalia--cand-width-step))))) 1224 (cl-loop 1225 for (cand . ann) in cands collect 1226 (progn 1227 (when-let (align (text-property-any 0 (length ann) 'marginalia--align t ann)) 1228 (put-text-property 1229 align (1+ align) 'display 1230 `(space :align-to 1231 ,(pcase-exhaustive marginalia-align 1232 ('center `(+ center ,marginalia-align-offset)) 1233 ('left `(+ left ,(+ marginalia-align-offset marginalia--cand-width-max))) 1234 ('right `(+ right ,(+ marginalia-align-offset 1 1235 (- (compat-call string-width ann 0 align) 1236 (string-width ann))))))) 1237 ann)) 1238 (list cand "" ann)))) 1239 1240 (defun marginalia--affixate (metadata annotator cands) 1241 "Affixate CANDS given METADATA and Marginalia ANNOTATOR." 1242 ;; Compute minimum width of windows, which display the minibuffer. 1243 ;; vertico-buffer displays the minibuffer in different windows. We may want 1244 ;; to generalize this and detect other types of completion buffers, e.g., 1245 ;; Embark Collect or the default completion buffer. 1246 (let* ((width (cl-loop for win in (get-buffer-window-list) minimize (window-width win))) 1247 (marginalia-field-width (min (/ width 2) marginalia-field-width)) 1248 (marginalia--metadata metadata) 1249 (cache marginalia--cache)) 1250 (marginalia--align 1251 ;; Run the annotators in the original window. `with-selected-window' 1252 ;; is necessary because of `lookup-minor-mode-from-indicator'. 1253 ;; Otherwise it would suffice to only change the current buffer. We 1254 ;; need the `selected-window' fallback for Embark Occur. 1255 (with-selected-window (or (minibuffer-selected-window) (selected-window)) 1256 (cl-loop for cand in cands collect 1257 (let ((ann (or (marginalia--cached cache annotator cand) ""))) 1258 (cons cand (if (string-blank-p ann) "" ann)))))))) 1259 1260 (defun marginalia--completion-metadata-get (metadata prop) 1261 "Meant as :before-until advice for `completion-metadata-get'. 1262 METADATA is the metadata. 1263 PROP is the property which is looked up." 1264 (pcase prop 1265 ('annotation-function 1266 ;; We do want the advice triggered for `completion-metadata-get'. 1267 (when-let ((cat (completion-metadata-get metadata 'category)) 1268 (annotator (marginalia--annotator cat))) 1269 (lambda (cand) 1270 (let ((ann (caddar (marginalia--affixate metadata annotator (list cand))))) 1271 (and (not (equal ann "")) ann))))) 1272 ('affixation-function 1273 ;; We do want the advice triggered for `completion-metadata-get'. 1274 (when-let ((cat (completion-metadata-get metadata 'category)) 1275 (annotator (marginalia--annotator cat))) 1276 (apply-partially #'marginalia--affixate metadata annotator))) 1277 ('category 1278 ;; Find the completion category by trying each of our classifiers. 1279 ;; Store the metadata for `marginalia-classify-original-category'. 1280 (let ((marginalia--metadata metadata)) 1281 (run-hook-with-args-until-success 'marginalia-classifiers))))) 1282 1283 (defun marginalia--minibuffer-setup () 1284 "Setup the minibuffer for Marginalia. 1285 Remember `this-command' for `marginalia-classify-by-command-name'." 1286 (setq marginalia--cache t marginalia--command this-command) 1287 ;; Reset cache if window size changes, recompute alignment 1288 (add-hook 'window-state-change-hook #'marginalia--cache-reset nil 'local) 1289 (marginalia--cache-reset)) 1290 1291 (defun marginalia--base-position (completions) 1292 "Record the base position of COMPLETIONS." 1293 ;; As a small optimization we track the base position only for file 1294 ;; completions, since `marginalia--full-candidate' is currently used only by 1295 ;; the file annotation function. 1296 (when minibuffer-completing-file-name 1297 (let ((base (or (cdr (last completions)) 0))) 1298 (unless (= marginalia--base-position base) 1299 (marginalia--cache-reset) 1300 (setq marginalia--base-position base 1301 marginalia--cand-width-max (default-value 'marginalia--cand-width-max))))) 1302 completions) 1303 1304 ;;;###autoload 1305 (define-minor-mode marginalia-mode 1306 "Annotate completion candidates with richer information." 1307 :global t :group 'marginalia 1308 (if marginalia-mode 1309 (progn 1310 ;; Remember `this-command' in order to select the annotation function. 1311 (add-hook 'minibuffer-setup-hook #'marginalia--minibuffer-setup) 1312 ;; Replace the metadata function. 1313 (advice-add #'completion-metadata-get :before-until #'marginalia--completion-metadata-get) 1314 ;; Record completion base position, for `marginalia--full-candidate' 1315 (advice-add #'completion-all-completions :filter-return #'marginalia--base-position)) 1316 (advice-remove #'completion-all-completions #'marginalia--base-position) 1317 (advice-remove #'completion-metadata-get #'marginalia--completion-metadata-get) 1318 (remove-hook 'minibuffer-setup-hook #'marginalia--minibuffer-setup))) 1319 1320 ;;;###autoload 1321 (defun marginalia-cycle () 1322 "Cycle between annotators in `marginalia-annotator-registry'." 1323 (interactive) 1324 (with-current-buffer (window-buffer 1325 (or (active-minibuffer-window) 1326 (user-error "Marginalia: No active minibuffer"))) 1327 (let* ((pt (max 0 (- (point) (minibuffer-prompt-end)))) 1328 (metadata (completion-metadata (buffer-substring-no-properties 1329 (minibuffer-prompt-end) 1330 (+ (minibuffer-prompt-end) pt)) 1331 minibuffer-completion-table 1332 minibuffer-completion-predicate)) 1333 (cat (or (completion-metadata-get metadata 'category) 1334 (user-error "Marginalia: Unknown completion category"))) 1335 (ann (or (assq cat marginalia-annotator-registry) 1336 (user-error "Marginalia: No annotators found for category `%s'" cat)))) 1337 (marginalia--cache-reset) 1338 (setcdr ann (append (cddr ann) (list (cadr ann)))) 1339 ;; When the builtin annotator is selected and no builtin function is 1340 ;; available, skip to the next annotator. Note that we cannot use 1341 ;; `completion-metadata-get' to access the metadata since we must 1342 ;; bypass the `marginalia--completion-metadata-get' advice. 1343 (when (and (eq (cadr ann) 'builtin) 1344 (not (assq 'annotation-function metadata)) 1345 (not (assq 'affixation-function metadata)) 1346 (not (plist-get completion-extra-properties :annotation-function)) 1347 (not (plist-get completion-extra-properties :affixation-function))) 1348 (setcdr ann (append (cddr ann) (list (cadr ann))))) 1349 (message "Marginalia: Use annotator `%s' for category `%s'" (cadr ann) (car ann))))) 1350 1351 ;; Emacs 28: Only show `marginalia-cycle' in M-x in recursive minibuffers 1352 (put #'marginalia-cycle 'completion-predicate 1353 (lambda (&rest _) (> (minibuffer-depth) 1))) 1354 1355 (provide 'marginalia) 1356 ;;; marginalia.el ends here