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