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