Personal emacs config
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5345 lines
197 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. ;;; ivy.el --- Incremental Vertical completYon -*- lexical-binding: t -*-
  2. ;; Copyright (C) 2015-2021 Free Software Foundation, Inc.
  3. ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
  4. ;; URL: https://github.com/abo-abo/swiper
  5. ;; Version: 0.13.4
  6. ;; Package-Requires: ((emacs "24.5"))
  7. ;; Keywords: matching
  8. ;; This file is part of GNU Emacs.
  9. ;; This file is free software; you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation; either version 3, or (at your option)
  12. ;; any later version.
  13. ;; This program is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; For a full copy of the GNU General Public License
  18. ;; see <https://www.gnu.org/licenses/>.
  19. ;;; Commentary:
  20. ;; This package provides `ivy-read' as an alternative to
  21. ;; `completing-read' and similar functions.
  22. ;;
  23. ;; There's no intricate code to determine the best candidate.
  24. ;; Instead, the user can navigate to it with `ivy-next-line' and
  25. ;; `ivy-previous-line'.
  26. ;;
  27. ;; The matching is done by splitting the input text by spaces and
  28. ;; re-building it into a regex.
  29. ;; So "for example" is transformed into "\\(for\\).*\\(example\\)".
  30. ;;; Code:
  31. (require 'colir)
  32. (require 'ivy-overlay)
  33. (require 'ivy-faces)
  34. (require 'cl-lib)
  35. (require 'ring)
  36. (eval-when-compile
  37. (require 'subr-x))
  38. ;;* Customization
  39. (defgroup ivy nil
  40. "Incremental vertical completion."
  41. :group 'convenience)
  42. (defcustom ivy-height 10
  43. "Number of lines for the minibuffer window.
  44. See also `ivy-height-alist'."
  45. :type 'integer)
  46. (defcustom ivy-count-format "%-4d "
  47. "The style to use for displaying the current candidate count for `ivy-read'.
  48. Set this to \"\" to suppress the count visibility.
  49. Set this to \"(%d/%d) \" to display both the index and the count."
  50. :type '(choice
  51. (const :tag "Count disabled" "")
  52. (const :tag "Count matches" "%-4d ")
  53. (const :tag "Count matches and show current match" "(%d/%d) ")
  54. string))
  55. (defcustom ivy-pre-prompt-function nil
  56. "When non-nil, add strings before the `ivy-read' prompt."
  57. :type '(choice
  58. (const :tag "Do nothing" nil)
  59. (function :tag "Custom function")))
  60. (defcustom ivy-add-newline-after-prompt nil
  61. "When non-nil, add a newline after the `ivy-read' prompt."
  62. :type 'boolean)
  63. (defcustom ivy-wrap nil
  64. "When non-nil, wrap around after the first and the last candidate."
  65. :type 'boolean)
  66. (defcustom ivy-display-style 'fancy
  67. "The style for formatting the minibuffer.
  68. By default, the matched strings are copied as is.
  69. The fancy display style highlights matching parts of the regexp,
  70. a behavior similar to `swiper'."
  71. :type '(choice
  72. (const :tag "Plain" nil)
  73. (const :tag "Fancy" fancy)))
  74. (defcustom ivy-on-del-error-function #'abort-recursive-edit
  75. "Function to call when deletion fails during completion.
  76. The usual reason for `ivy-backward-delete-char' to fail is when
  77. there is no text left to delete, i.e., when it is called at the
  78. beginning of the minibuffer.
  79. The default setting provides a quick exit from completion.
  80. Another common option is `ignore', which does nothing."
  81. :type '(choice
  82. (const :tag "Exit completion" abort-recursive-edit)
  83. (const :tag "Do nothing" ignore)
  84. (function :tag "Custom function")))
  85. (defcustom ivy-extra-directories '("../" "./")
  86. "Add this to the front of the list when completing file names.
  87. Only \"./\" and \"../\" apply here. They appear in reverse order."
  88. :type '(repeat :tag "Dirs"
  89. (choice
  90. (const :tag "Parent Directory" "../")
  91. (const :tag "Current Directory" "./"))))
  92. (defcustom ivy-use-virtual-buffers nil
  93. "When non-nil, add recent files and/or bookmarks to `ivy-switch-buffer'.
  94. The value `recentf' includes only recent files to the virtual
  95. buffers list, whereas the value `bookmarks' does the same for
  96. bookmarks. Any other non-nil value includes both."
  97. :type '(choice
  98. (const :tag "Don't use virtual buffers" nil)
  99. (const :tag "Recent files" recentf)
  100. (const :tag "Bookmarks" bookmarks)
  101. (const :tag "All virtual buffers" t)))
  102. (defvar ivy--display-function nil
  103. "The display-function is used in current.")
  104. (defvar ivy-display-functions-props
  105. '((ivy-display-function-overlay :cleanup ivy-overlay-cleanup))
  106. "Map Ivy display functions to their property lists.
  107. Examples of properties include associated `:cleanup' functions.")
  108. (defcustom ivy-display-functions-alist
  109. '((ivy-completion-in-region . ivy-display-function-overlay)
  110. (t . nil))
  111. "An alist for customizing where to display the candidates.
  112. Each key is a caller symbol. When the value is nil (the default),
  113. the candidates are shown in the minibuffer. Otherwise, the value
  114. is a function which takes a string argument comprising the
  115. current matching candidates and displays it somewhere.
  116. See also `https://github.com/abo-abo/swiper/wiki/ivy-display-function'."
  117. :type '(alist
  118. :key-type symbol
  119. :value-type (choice
  120. (const :tag "Minibuffer" nil)
  121. (const :tag "LV" ivy-display-function-lv)
  122. (const :tag "Popup" ivy-display-function-popup)
  123. (const :tag "Overlay" ivy-display-function-overlay)
  124. (function :tag "Custom function"))))
  125. (defvar ivy-completing-read-dynamic-collection nil
  126. "Run `ivy-completing-read' with `:dynamic-collection t`.")
  127. (defcustom ivy-completing-read-handlers-alist
  128. '((tmm-menubar . completing-read-default)
  129. (tmm-shortcut . completing-read-default)
  130. (bbdb-create . ivy-completing-read-with-empty-string-def)
  131. (auto-insert . ivy-completing-read-with-empty-string-def)
  132. (Info-on-current-buffer . ivy-completing-read-with-empty-string-def)
  133. (Info-follow-reference . ivy-completing-read-with-empty-string-def)
  134. (Info-menu . ivy-completing-read-with-empty-string-def)
  135. (Info-index . ivy-completing-read-with-empty-string-def)
  136. (Info-virtual-index . ivy-completing-read-with-empty-string-def)
  137. (info-display-manual . ivy-completing-read-with-empty-string-def))
  138. "An alist of handlers to replace `completing-read' in `ivy-mode'."
  139. :type '(alist :key-type symbol :value-type function))
  140. (defcustom ivy-height-alist nil
  141. "An alist to customize `ivy-height'.
  142. It is a list of (CALLER . HEIGHT). CALLER is a caller of
  143. `ivy-read' and HEIGHT is the number of lines displayed.
  144. HEIGHT can also be a function that returns the number of lines."
  145. :type '(alist
  146. :key-type function
  147. :value-type (choice integer function)))
  148. (defvar ivy-completing-read-ignore-handlers-depth -1
  149. "Used to avoid infinite recursion.
  150. If `(minibuffer-depth)' equals this, `ivy-completing-read' will
  151. act as if `ivy-completing-read-handlers-alist' is empty.")
  152. (defvar ivy-highlight-grep-commands nil
  153. "List of grep-like commands.")
  154. (defvar ivy--actions-list nil
  155. "A list of extra actions per command.")
  156. (defun ivy-set-actions (cmd actions)
  157. "Set CMD extra exit points to ACTIONS."
  158. (setq ivy--actions-list
  159. (plist-put ivy--actions-list cmd actions)))
  160. (defun ivy-add-actions (cmd actions)
  161. "Add extra exit points ACTIONS to CMD.
  162. Existing exit points of CMD are overwritten by those in
  163. ACTIONS that have the same key."
  164. (setq ivy--actions-list
  165. (plist-put ivy--actions-list cmd
  166. (cl-delete-duplicates
  167. (append (plist-get ivy--actions-list cmd) actions)
  168. :key #'car :test #'equal))))
  169. (defun ivy--compute-extra-actions (action caller)
  170. "Add extra actions to ACTION based on CALLER."
  171. (let* ((extra-actions (cl-delete-duplicates
  172. (append (plist-get ivy--actions-list t)
  173. (plist-get ivy--actions-list this-command)
  174. (plist-get ivy--actions-list caller))
  175. :key #'car :test #'equal))
  176. (override-default (assoc "o" extra-actions)))
  177. (cond (override-default
  178. (cons 1 (cons override-default
  179. (cl-delete "o" extra-actions
  180. :key #'car :test #'equal))))
  181. ((not extra-actions)
  182. action)
  183. ((functionp action)
  184. `(1
  185. ("o" ,action "default")
  186. ,@extra-actions))
  187. ((null action)
  188. `(1
  189. ("o" identity "default")
  190. ,@extra-actions))
  191. (t
  192. (cons (car action)
  193. (cl-delete-duplicates (cdr (append action extra-actions))
  194. :key #'car :test #'equal :from-end t))))))
  195. (defvar ivy--prompts-list nil)
  196. (defun ivy-set-prompt (caller prompt-fn)
  197. "Associate CALLER with PROMPT-FN.
  198. PROMPT-FN is a function of no arguments that returns a prompt string."
  199. (setq ivy--prompts-list
  200. (plist-put ivy--prompts-list caller prompt-fn)))
  201. (defvar ivy--display-transformers-alist nil
  202. "A list of str->str transformers per command.")
  203. (defun ivy-set-display-transformer (cmd transformer)
  204. "Set CMD a displayed candidate TRANSFORMER.
  205. It's a lambda that takes a string one of the candidates in the
  206. collection and returns a string for display, the same candidate
  207. plus some extra information.
  208. This lambda is called only on the `ivy-height' candidates that
  209. are about to be displayed, not on the whole collection."
  210. (declare (obsolete "Use `ivy-configure' :display-transformer-fn" "<2020-05-20 Wed>"))
  211. (ivy--alist-set 'ivy--display-transformers-alist cmd transformer))
  212. (defvar ivy--sources-list nil
  213. "A list of extra sources per command.")
  214. (defun ivy-set-sources (cmd sources)
  215. "Attach to CMD a list of extra SOURCES.
  216. Each static source is a function that takes no argument and
  217. returns a list of strings.
  218. The (original-source) determines the position of the original
  219. dynamic source.
  220. Extra dynamic sources aren't supported yet.
  221. Example:
  222. (defun small-recentf ()
  223. (cl-subseq recentf-list 0 20))
  224. (ivy-set-sources
  225. 'counsel-locate
  226. '((small-recentf)
  227. (original-source)))"
  228. (setq ivy--sources-list
  229. (plist-put ivy--sources-list cmd sources)))
  230. (defun ivy--compute-extra-candidates (caller)
  231. (let ((extra-sources (or (plist-get ivy--sources-list caller)
  232. '((original-source))))
  233. (result nil))
  234. (dolist (source extra-sources)
  235. (cond ((equal source '(original-source))
  236. (push source result))
  237. ((null (cdr source))
  238. (push (list (car source) (funcall (car source))) result))))
  239. result))
  240. (defvar ivy-current-prefix-arg nil
  241. "Prefix arg to pass to actions.
  242. This is a global variable that is set by ivy functions for use in
  243. action functions.")
  244. ;;* Keymap
  245. (require 'delsel)
  246. (defun ivy-define-key (keymap key def)
  247. "Forward to (`define-key' KEYMAP KEY DEF).
  248. Remove DEF from `counsel-M-x' list."
  249. (put def 'no-counsel-M-x t)
  250. (define-key keymap key def))
  251. (defvar ivy-minibuffer-map
  252. (let ((map (make-sparse-keymap)))
  253. (ivy-define-key map (kbd "C-m") 'ivy-done)
  254. (define-key map [down-mouse-1] 'ignore)
  255. (ivy-define-key map [mouse-1] 'ivy-mouse-done)
  256. (ivy-define-key map [mouse-3] 'ivy-mouse-dispatching-done)
  257. (ivy-define-key map (kbd "C-M-m") 'ivy-call)
  258. (ivy-define-key map (kbd "C-j") 'ivy-alt-done)
  259. (ivy-define-key map (kbd "C-M-j") 'ivy-immediate-done)
  260. (ivy-define-key map (kbd "TAB") 'ivy-partial-or-done)
  261. (ivy-define-key map [remap next-line] 'ivy-next-line)
  262. (ivy-define-key map [remap previous-line] 'ivy-previous-line)
  263. (ivy-define-key map (kbd "C-r") 'ivy-reverse-i-search)
  264. (define-key map (kbd "SPC") 'self-insert-command)
  265. (ivy-define-key map [remap delete-backward-char] 'ivy-backward-delete-char)
  266. (ivy-define-key map [remap backward-delete-char-untabify] 'ivy-backward-delete-char)
  267. (ivy-define-key map [remap backward-kill-word] 'ivy-backward-kill-word)
  268. (ivy-define-key map [remap delete-char] 'ivy-delete-char)
  269. (ivy-define-key map [remap forward-char] 'ivy-forward-char)
  270. (ivy-define-key map (kbd "<right>") 'ivy-forward-char)
  271. (ivy-define-key map [remap kill-word] 'ivy-kill-word)
  272. (ivy-define-key map [remap beginning-of-buffer] 'ivy-beginning-of-buffer)
  273. (ivy-define-key map [remap end-of-buffer] 'ivy-end-of-buffer)
  274. (ivy-define-key map (kbd "M-n") 'ivy-next-history-element)
  275. (ivy-define-key map (kbd "M-p") 'ivy-previous-history-element)
  276. (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
  277. (ivy-define-key map [remap scroll-up-command] 'ivy-scroll-up-command)
  278. (ivy-define-key map [remap scroll-down-command] 'ivy-scroll-down-command)
  279. (ivy-define-key map (kbd "<next>") 'ivy-scroll-up-command)
  280. (ivy-define-key map (kbd "<prior>") 'ivy-scroll-down-command)
  281. (ivy-define-key map (kbd "C-v") 'ivy-scroll-up-command)
  282. (ivy-define-key map (kbd "M-v") 'ivy-scroll-down-command)
  283. (ivy-define-key map (kbd "C-M-n") 'ivy-next-line-and-call)
  284. (ivy-define-key map (kbd "C-M-p") 'ivy-previous-line-and-call)
  285. (ivy-define-key map (kbd "M-a") 'ivy-toggle-marks)
  286. (ivy-define-key map (kbd "M-r") 'ivy-toggle-regexp-quote)
  287. (ivy-define-key map (kbd "M-j") 'ivy-yank-word)
  288. (ivy-define-key map (kbd "M-i") 'ivy-insert-current)
  289. (ivy-define-key map (kbd "C-M-y") 'ivy-insert-current-full)
  290. (ivy-define-key map (kbd "C-o") 'hydra-ivy/body)
  291. (ivy-define-key map (kbd "M-o") 'ivy-dispatching-done)
  292. (ivy-define-key map (kbd "C-M-o") 'ivy-dispatching-call)
  293. (ivy-define-key map [remap kill-line] 'ivy-kill-line)
  294. (ivy-define-key map [remap kill-whole-line] 'ivy-kill-whole-line)
  295. (ivy-define-key map (kbd "S-SPC") 'ivy-restrict-to-matches)
  296. (ivy-define-key map [remap kill-ring-save] 'ivy-kill-ring-save)
  297. (ivy-define-key map (kbd "C-M-a") 'ivy-read-action)
  298. (ivy-define-key map (kbd "C-c C-o") 'ivy-occur)
  299. (ivy-define-key map (kbd "C-c C-a") 'ivy-toggle-ignore)
  300. (ivy-define-key map (kbd "C-c C-s") 'ivy-rotate-sort)
  301. (ivy-define-key map [remap describe-mode] 'ivy-help)
  302. (ivy-define-key map "$" 'ivy-magic-read-file-env)
  303. map)
  304. "Keymap used in the minibuffer.")
  305. (autoload 'hydra-ivy/body "ivy-hydra" "" t)
  306. (autoload 'ivy-hydra-read-action "ivy-hydra" "" t)
  307. (defvar ivy-mode-map
  308. (let ((map (make-sparse-keymap)))
  309. (ivy-define-key map [remap switch-to-buffer] 'ivy-switch-buffer)
  310. (ivy-define-key map [remap switch-to-buffer-other-window] 'ivy-switch-buffer-other-window)
  311. map)
  312. "Keymap for `ivy-mode'.")
  313. ;;* Globals
  314. (cl-defstruct ivy-state
  315. prompt collection
  316. predicate require-match initial-input
  317. history preselect keymap update-fn sort
  318. ;; The frame in which `ivy-read' was called
  319. frame
  320. ;; The window in which `ivy-read' was called
  321. window
  322. ;; The buffer in which `ivy-read' was called
  323. buffer
  324. ;; The value of `ivy-text' to be used by `ivy-occur'
  325. text
  326. action
  327. unwind
  328. re-builder
  329. matcher
  330. ;; When this is non-nil, call it for each input change to get new candidates
  331. dynamic-collection
  332. ;; A lambda that transforms candidates only for display
  333. display-transformer-fn
  334. directory
  335. caller
  336. current
  337. def
  338. ignore
  339. multi-action
  340. extra-props)
  341. (defvar ivy-last (make-ivy-state)
  342. "The last parameters passed to `ivy-read'.
  343. This should eventually become a stack so that you could use
  344. `ivy-read' recursively.")
  345. (defvar ivy--sessions nil
  346. "Alist mapping session symbols to `ivy-state' objects.")
  347. (defvar ivy-recursive-last nil)
  348. (defvar ivy-recursive-restore t
  349. "When non-nil, restore the above state when exiting the minibuffer.
  350. This variable is let-bound to nil by functions that take care of
  351. the restoring themselves.")
  352. (defsubst ivy-set-action (action)
  353. "Set the current `ivy-last' field to ACTION."
  354. (setf (ivy-state-action ivy-last) action))
  355. (defvar inhibit-message)
  356. (defvar ffap-machine-p-known)
  357. (defun ivy-thing-at-point ()
  358. "Return a string that corresponds to the current thing at point."
  359. (substring-no-properties
  360. (cond
  361. ((use-region-p)
  362. (let* ((beg (region-beginning))
  363. (end (region-end))
  364. (eol (save-excursion (goto-char beg) (line-end-position))))
  365. (buffer-substring-no-properties beg (min end eol))))
  366. ((thing-at-point 'url))
  367. ((and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
  368. (let ((inhibit-message t)
  369. (ffap-machine-p-known 'reject))
  370. (run-hook-with-args-until-success 'file-name-at-point-functions))))
  371. ((let ((s (thing-at-point 'symbol)))
  372. (and (stringp s)
  373. (if (string-match "\\`[`']?\\(.*?\\)'?\\'" s)
  374. (match-string 1 s)
  375. s))))
  376. ((looking-at "(+\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>")
  377. (match-string-no-properties 1))
  378. (t
  379. ""))))
  380. (defvar ivy-history nil
  381. "History list of candidates entered in the minibuffer.
  382. Maximum length of the history list is determined by the value
  383. of `history-length'.")
  384. (defvar ivy--directory nil
  385. "Current directory when completing file names.")
  386. (defvar ivy--directory-hist nil
  387. "Store the history of directories.
  388. This allows RET to reverse consecutive DEL.")
  389. (defvar ivy--length 0
  390. "Store the amount of viable candidates.")
  391. (defvar ivy-text ""
  392. "Store the user's string as it is typed in.")
  393. (defvar ivy-regex ""
  394. "Store the regex value that corresponds to `ivy-text'.")
  395. (defvar ivy--regex-function 'ivy--regex
  396. "Current function for building a regex.")
  397. (defun ivy-set-text (str)
  398. "Set `ivy-text' to STR."
  399. (setq ivy-text str)
  400. (setq ivy-regex (funcall ivy--regex-function ivy-text)))
  401. (defvar ivy--index 0
  402. "Store the index of the current candidate.")
  403. (defvar ivy--window-index 0
  404. "Store the index of the current candidate in the minibuffer window.
  405. This means it's between 0 and `ivy-height'.")
  406. (defvar ivy-exit nil
  407. "Store `done' if the completion was successfully selected.
  408. Otherwise, store nil.")
  409. (defvar ivy--all-candidates nil
  410. "Store the candidates passed to `ivy-read'.")
  411. (defvar ivy--extra-candidates '((original-source))
  412. "Store candidates added by the extra sources.
  413. This is an internal-use alist. Each key is a function name, or
  414. original-source (which represents where the current dynamic
  415. candidates should go).
  416. Each value is an evaluation of the function, in case of static
  417. sources. These values will subsequently be filtered on `ivy-text'.
  418. This variable is set by `ivy-read' and used by `ivy--set-candidates'.")
  419. (defcustom ivy-use-ignore-default t
  420. "The default policy for user-configured candidate filtering."
  421. :type '(choice
  422. (const :tag "Ignore ignored always" always)
  423. (const :tag "Ignore ignored when others exist" t)
  424. (const :tag "Don't ignore" nil)))
  425. (defvar ivy-use-ignore t
  426. "Store policy for user-configured candidate filtering.
  427. This may be changed dynamically by `ivy-toggle-ignore'.
  428. Use `ivy-use-ignore-default' for a permanent configuration.")
  429. (defvar ivy--default nil
  430. "Default initial input.")
  431. (defvar ivy--prompt nil
  432. "Store the format-style prompt.
  433. When non-nil, it should contain at least one %d.")
  434. (defvar ivy--prompt-extra ""
  435. "Temporary modifications to the prompt.")
  436. (defvar ivy--old-re nil
  437. "Store the old regexp.
  438. Either a string or a list for `ivy-re-match'.")
  439. (defvar ivy--old-cands nil
  440. "Store the candidates matched by `ivy--old-re'.")
  441. (defvar ivy--highlight-function 'ivy--highlight-default
  442. "Current function for formatting the candidates.")
  443. (defvar ivy--subexps 0
  444. "Number of groups in the current `ivy--regex'.")
  445. (defvar ivy--full-length nil
  446. "The total amount of candidates when :dynamic-collection is non-nil.")
  447. (defvar ivy--old-text ""
  448. "Store old `ivy-text' for dynamic completion.")
  449. (defvar ivy--trying-to-resume-dynamic-collection nil
  450. "Non-nil if resuming from a dynamic collection.
  451. When non-nil, ivy will wait until the first chunk of asynchronous
  452. candidates has been received before selecting the last
  453. preselected candidate.")
  454. (defun ivy--set-index-dynamic-collection ()
  455. (when ivy--trying-to-resume-dynamic-collection
  456. (let ((preselect-index
  457. (ivy--preselect-index (ivy-state-preselect ivy-last) ivy--all-candidates)))
  458. (when preselect-index
  459. (ivy-set-index preselect-index)))
  460. (setq ivy--trying-to-resume-dynamic-collection nil)))
  461. (defcustom ivy-case-fold-search-default
  462. (if search-upper-case
  463. 'auto
  464. case-fold-search)
  465. "The default value for `case-fold-search' in Ivy operations.
  466. The special value `auto' means case folding is performed so long
  467. as the entire input string comprises lower-case characters. This
  468. corresponds to the default behaviour of most Emacs search
  469. functionality, e.g. as seen in `isearch'."
  470. :link '(info-link "(emacs)Lax Search")
  471. :type '(choice
  472. (const :tag "Auto" auto)
  473. (const :tag "Always" t)
  474. (const :tag "Never" nil)))
  475. (defvar ivy-case-fold-search ivy-case-fold-search-default
  476. "Store the current overriding `case-fold-search'.")
  477. (defcustom ivy-more-chars-alist
  478. '((t . 3))
  479. "Map commands to their minimum required input length.
  480. That is the number of characters prompted for before fetching
  481. candidates. The special key t is used as a fallback."
  482. :type '(alist :key-type symbol :value-type integer))
  483. (defun ivy-more-chars ()
  484. "Return two fake candidates prompting for at least N input.
  485. N is obtained from `ivy-more-chars-alist'."
  486. (let ((diff (- (ivy-alist-setting ivy-more-chars-alist)
  487. (length ivy-text))))
  488. (when (> diff 0)
  489. (list "" (format "%d chars more" diff)))))
  490. (defun ivy--case-fold-p (string)
  491. "Return nil if STRING should be matched case-sensitively."
  492. (if (eq ivy-case-fold-search 'auto)
  493. (string= string (downcase string))
  494. ivy-case-fold-search))
  495. (defun ivy--case-fold-string= (s1 s2)
  496. "Like `string=', but obeys `case-fold-search'."
  497. (eq t (compare-strings s1 nil nil s2 nil nil case-fold-search)))
  498. (defmacro ivy-quit-and-run (&rest body)
  499. "Quit the minibuffer and run BODY afterwards."
  500. (declare (indent 0))
  501. `(progn
  502. (put 'quit 'error-message "")
  503. (run-at-time nil nil
  504. (lambda ()
  505. (put 'quit 'error-message "Quit")
  506. (with-demoted-errors "Error: %S"
  507. ,@body)))
  508. (abort-recursive-edit)))
  509. (defun ivy-exit-with-action (action &optional exit-code)
  510. "Quit the minibuffer and call ACTION afterwards."
  511. (ivy-set-action
  512. `(lambda (x)
  513. (funcall ',action x)
  514. (ivy-set-action ',(ivy-state-action ivy-last))))
  515. (setq ivy-exit (or exit-code 'done))
  516. (exit-minibuffer))
  517. (defmacro with-ivy-window (&rest body)
  518. "Execute BODY in the window from which `ivy-read' was called."
  519. (declare (indent 0)
  520. (debug t))
  521. `(with-selected-window (ivy--get-window ivy-last)
  522. ,@body))
  523. (defun ivy--expand-file-name (text)
  524. (cond
  525. ((eq (ivy-state-history ivy-last) 'grep-files-history)
  526. text)
  527. (ivy--directory
  528. (if (and (string-match-p "^/" text) (file-remote-p ivy--directory))
  529. (let ((parts (split-string ivy--directory ":")))
  530. (concat (nth 0 parts) ":" (nth 1 parts) ":" text))
  531. (expand-file-name text ivy--directory)))
  532. (t
  533. text)))
  534. (defun ivy--done (text)
  535. "Insert TEXT and exit minibuffer."
  536. (if (member (ivy-state-prompt ivy-last) '("Create directory: " "Make directory: "))
  537. (ivy-immediate-done)
  538. (when (stringp text)
  539. (insert
  540. (setf (ivy-state-current ivy-last)
  541. (ivy--expand-file-name text))))
  542. (setq ivy-exit 'done)
  543. (exit-minibuffer)))
  544. (defcustom ivy-use-selectable-prompt nil
  545. "When non-nil, make the prompt line selectable like a candidate.
  546. The prompt line can be selected by calling `ivy-previous-line' when the first
  547. regular candidate is selected. Both actions `ivy-done' and `ivy-alt-done',
  548. when called on a selected prompt, are forwarded to `ivy-immediate-done', which
  549. results to the same as calling `ivy-immediate-done' explicitly when a regular
  550. candidate is selected.
  551. Note that if `ivy-wrap' is set to t, calling `ivy-previous-line' when the
  552. prompt is selected wraps around to the last candidate, while calling
  553. `ivy-next-line' on the last candidate wraps around to the first
  554. candidate, not the prompt."
  555. :type 'boolean)
  556. (defvar ivy--use-selectable-prompt nil
  557. "Store the effective `ivy-use-selectable-prompt' for current session.")
  558. (defun ivy--prompt-selectable-p ()
  559. "Return t if the prompt line is selectable."
  560. (and ivy-use-selectable-prompt
  561. (or (memq (ivy-state-require-match ivy-last)
  562. '(nil confirm confirm-after-completion))
  563. ;; :require-match is t, but "" is in the collection
  564. (let ((coll (ivy-state-collection ivy-last)))
  565. (and (listp coll)
  566. (if (consp (car coll))
  567. (member '("") coll)
  568. (member "" coll)))))))
  569. (defun ivy--prompt-selected-p ()
  570. "Return t if the prompt line is selected."
  571. (and ivy--use-selectable-prompt
  572. (= ivy--index -1)))
  573. ;;* Commands
  574. (defun ivy-done ()
  575. "Exit the minibuffer with the selected candidate."
  576. (interactive)
  577. (if (ivy--prompt-selected-p)
  578. (ivy-immediate-done)
  579. (setq ivy-current-prefix-arg current-prefix-arg)
  580. (delete-minibuffer-contents)
  581. (cond ((and (= ivy--length 0)
  582. (eq this-command 'ivy-dispatching-done))
  583. (ivy--done ivy-text))
  584. ((or (> ivy--length 0)
  585. ;; the action from `ivy-dispatching-done' may not need a
  586. ;; candidate at all
  587. (eq this-command 'ivy-dispatching-done))
  588. (ivy--done (ivy-state-current ivy-last)))
  589. ((and (memq (ivy-state-collection ivy-last)
  590. '(read-file-name-internal internal-complete-buffer))
  591. (eq confirm-nonexistent-file-or-buffer t)
  592. (not (string= " (confirm)" ivy--prompt-extra)))
  593. (setq ivy--prompt-extra " (confirm)")
  594. (insert ivy-text)
  595. (ivy--exhibit))
  596. ((memq (ivy-state-require-match ivy-last)
  597. '(nil confirm confirm-after-completion))
  598. (ivy--done ivy-text))
  599. (t
  600. (setq ivy--prompt-extra " (match required)")
  601. (insert ivy-text)
  602. (ivy--exhibit)))))
  603. (defvar ivy-mouse-1-tooltip
  604. "Exit the minibuffer with the selected candidate."
  605. "The doc visible in the tooltip for mouse-1 binding in the minibuffer.")
  606. (defvar ivy-mouse-3-tooltip
  607. "Display alternative actions."
  608. "The doc visible in the tooltip for mouse-3 binding in the minibuffer.")
  609. (defun ivy-mouse-offset (event)
  610. "Compute the offset between the candidate at point and the selected one."
  611. (if event
  612. (let* ((line-number-at-point
  613. (max 2
  614. (line-number-at-pos (posn-point (event-start event)))))
  615. (line-number-candidate ;; convert to 0 based index
  616. (- line-number-at-point 2))
  617. (offset
  618. (- line-number-candidate
  619. ivy--window-index)))
  620. offset)
  621. nil))
  622. (defun ivy-mouse-done (event)
  623. (interactive "@e")
  624. (let ((offset (ivy-mouse-offset event)))
  625. (when offset
  626. (ivy-next-line offset)
  627. (ivy--exhibit)
  628. (ivy-alt-done))))
  629. (defun ivy-mouse-dispatching-done (event)
  630. (interactive "@e")
  631. (let ((offset (ivy-mouse-offset event)))
  632. (when offset
  633. (ivy-next-line offset)
  634. (ivy--exhibit)
  635. (ivy-dispatching-done))))
  636. (defcustom ivy-read-action-format-function 'ivy-read-action-format-default
  637. "Function used to transform the actions list into a docstring."
  638. :type '(radio
  639. (function-item ivy-read-action-format-default)
  640. (function-item ivy-read-action-format-columns)))
  641. (defun ivy-read-action-format-default (actions)
  642. "Create a docstring from ACTIONS.
  643. ACTIONS is a list. Each list item is a list of 3 items:
  644. key (a string), cmd and doc (a string)."
  645. (format "%s\n%s\n"
  646. (if (eq this-command 'ivy-read-action)
  647. "Select action: "
  648. (ivy-state-current ivy-last))
  649. (mapconcat
  650. (lambda (x)
  651. (format "%s: %s"
  652. (propertize
  653. (car x)
  654. 'face 'ivy-action)
  655. (nth 2 x)))
  656. actions
  657. "\n")))
  658. (defun ivy-read-action-format-columns (actions)
  659. "Create a docstring from ACTIONS, using several columns if needed to preserve `ivy-height'.
  660. ACTIONS is a list. Each list item is a list of 3 items: key (a
  661. string), cmd and doc (a string)."
  662. (let ((length (length actions))
  663. (i 0)
  664. (max-rows (- ivy-height 1))
  665. rows cols col lwidth rwidth)
  666. (while (< i length)
  667. (setq col (cl-subseq actions i (min length (cl-incf i max-rows))))
  668. (setq lwidth (apply 'max (mapcar (lambda (x)
  669. (length (nth 0 x)))
  670. col)))
  671. (setq rwidth (apply 'max (mapcar (lambda (x)
  672. (length (nth 2 x)))
  673. col)))
  674. (setq col (mapcar (lambda (x)
  675. (format (format "%%%ds: %%-%ds" lwidth rwidth)
  676. (propertize (car x) 'face 'ivy-action)
  677. (nth 2 x)))
  678. col))
  679. (cond
  680. ((null rows)
  681. (setq rows (length col)))
  682. ((< (length col) rows)
  683. (setq col (append col (make-list (- rows (length col)) "")))))
  684. (push col cols))
  685. (format "%s\n%s\n"
  686. (if (eq this-command 'ivy-read-action)
  687. "Select action: "
  688. (ivy-state-current ivy-last))
  689. (mapconcat 'identity
  690. (apply 'cl-mapcar
  691. (lambda (&rest args)
  692. (mapconcat 'identity args " | "))
  693. (nreverse cols))
  694. "\n"))))
  695. (defcustom ivy-read-action-function #'ivy-read-action-by-key
  696. "Function used to read an action."
  697. :type '(radio
  698. (function-item ivy-read-action-by-key)
  699. (function-item ivy-read-action-ivy)
  700. (function-item ivy-hydra-read-action)))
  701. (defun ivy-read-action ()
  702. "Change the action to one of the available ones.
  703. Return nil for `minibuffer-keyboard-quit' or wrong key during the
  704. selection, non-nil otherwise."
  705. (interactive)
  706. (let ((actions (ivy-state-action ivy-last)))
  707. (if (not (ivy--actionp actions))
  708. t
  709. (let ((ivy--directory ivy--directory))
  710. (funcall ivy-read-action-function actions)))))
  711. (defvar set-message-function)
  712. (defun ivy-read-action-by-key (actions)
  713. (let* ((set-message-function nil)
  714. (hint (funcall ivy-read-action-format-function (cdr actions)))
  715. (resize-mini-windows t)
  716. (key "")
  717. action-idx)
  718. (while (and (setq action-idx (cl-position-if
  719. (lambda (x)
  720. (string-prefix-p key (car x)))
  721. (cdr actions)))
  722. (not (string= key (car (nth action-idx (cdr actions))))))
  723. (setq key (concat key (key-description (vector (read-key hint))))))
  724. (ivy-shrink-after-dispatching)
  725. (cond ((member key '("ESC" "C-g" "M-o"))
  726. nil)
  727. ((null action-idx)
  728. (message "%s is not bound" key)
  729. nil)
  730. (t
  731. (message "")
  732. (setcar actions (1+ action-idx))
  733. (ivy-set-action actions)))))
  734. (defvar ivy-marked-candidates nil
  735. "List of marked candidates.
  736. Use `ivy-mark' to populate this.
  737. When this list is non-nil at the end of the session, the action
  738. will be called for each element of this list.")
  739. (defun ivy-read-action-ivy (actions)
  740. "Select an action from ACTIONS using Ivy."
  741. (let ((enable-recursive-minibuffers t))
  742. (if (and (> (minibuffer-depth) 1)
  743. (eq (ivy-state-caller ivy-last) 'ivy-read-action-ivy))
  744. (minibuffer-keyboard-quit)
  745. (let ((ivy-marked-candidates ivy-marked-candidates))
  746. (ivy-read (format "action (%s): " (ivy-state-current ivy-last))
  747. (cl-mapcar
  748. (lambda (a i) (cons (format "[%s] %s" (nth 0 a) (nth 2 a)) i))
  749. (cdr actions) (number-sequence 1 (length (cdr actions))))
  750. :action (lambda (a)
  751. (setcar actions (cdr a))
  752. (ivy-set-action actions))
  753. :caller 'ivy-read-action-ivy)))))
  754. (defun ivy-shrink-after-dispatching ()
  755. "Shrink the window after dispatching when action list is too large."
  756. (when (window-minibuffer-p)
  757. (window-resize nil (- ivy-height (window-height)))))
  758. (defun ivy-dispatching-done ()
  759. "Select one of the available actions and call `ivy-done'."
  760. (interactive)
  761. (let ((ivy-exit 'ivy-dispatching-done))
  762. (when (ivy-read-action)
  763. (ivy-done)))
  764. (ivy-shrink-after-dispatching))
  765. (defun ivy-dispatching-call ()
  766. "Select one of the available actions and call `ivy-call'."
  767. (interactive)
  768. (setq ivy-current-prefix-arg current-prefix-arg)
  769. (let ((actions (copy-sequence (ivy-state-action ivy-last)))
  770. (old-ivy-text ivy-text))
  771. (unwind-protect
  772. (when (ivy-read-action)
  773. (ivy-set-text old-ivy-text)
  774. (ivy-call))
  775. (ivy-set-action actions)))
  776. (ivy-shrink-after-dispatching))
  777. (defun ivy-build-tramp-name (x)
  778. "Reconstruct X into a path.
  779. Is is a cons cell, related to `tramp-get-completion-function'."
  780. (let ((user (car x))
  781. (domain (cadr x)))
  782. (if user
  783. (concat user "@" domain)
  784. domain)))
  785. (declare-function Info-find-node "info")
  786. (declare-function Info-read-node-name-1 "info")
  787. (declare-function tramp-get-completion-function "tramp")
  788. (defcustom ivy-alt-done-functions-alist nil
  789. "Customize what `ivy-alt-done' does per-collection."
  790. :type '(alist :key-type symbol :value-type function))
  791. (defun ivy--completing-fname-p ()
  792. (eq 'file (cdr (assoc
  793. 'category
  794. (ignore-errors
  795. (funcall (ivy-state-collection ivy-last) ivy-text nil 'metadata))))))
  796. (defun ivy-alt-done (&optional arg)
  797. "Exit the minibuffer with the selected candidate.
  798. When ARG is t, exit with current text, ignoring the candidates.
  799. When the current candidate during file name completion is a
  800. directory, continue completion from within that directory instead
  801. of exiting. This function is otherwise like `ivy-done'."
  802. (interactive "P")
  803. (setq ivy-current-prefix-arg current-prefix-arg)
  804. (let (alt-done-fn)
  805. (cond ((or arg (ivy--prompt-selected-p))
  806. (ivy-immediate-done))
  807. ((setq alt-done-fn (ivy-alist-setting ivy-alt-done-functions-alist))
  808. (funcall alt-done-fn))
  809. ((ivy--completing-fname-p)
  810. (ivy--directory-done))
  811. (t
  812. (ivy-done)))))
  813. (defun ivy--info-alt-done ()
  814. (if (member (ivy-state-current ivy-last) '("(./)" "(../)"))
  815. (ivy-quit-and-run
  816. (ivy-read "Go to file: " #'read-file-name-internal
  817. :action (lambda (x)
  818. (Info-find-node
  819. (expand-file-name x ivy--directory)
  820. "Top"))))
  821. (ivy-done)))
  822. (defvar ivy-auto-select-single-candidate nil
  823. "When non-nil, auto-select the candidate if it is the only one.
  824. When t, it is the same as if the user were prompted and selected the candidate
  825. by calling the default action. This variable has no use unless the collection
  826. contains a single candidate.")
  827. (defun ivy--directory-enter ()
  828. (let (dir)
  829. (when (and
  830. (> ivy--length 0)
  831. (not (string= (ivy-state-current ivy-last) "./"))
  832. (setq dir (ivy-expand-file-if-directory (ivy-state-current ivy-last))))
  833. (ivy--cd dir)
  834. (ivy--exhibit))))
  835. (defun ivy--handle-directory (input)
  836. "Detect the next directory based on special values of INPUT."
  837. (cond ((string= input "/")
  838. "/")
  839. ((string= input "/sudo::")
  840. (concat input ivy--directory))))
  841. (defun ivy--tramp-candidates ()
  842. (let ((method (match-string 1 ivy-text))
  843. (user (match-string 2 ivy-text))
  844. (rest (match-string 3 ivy-text))
  845. res)
  846. (dolist (x (tramp-get-completion-function method))
  847. (setq res (append res (funcall (car x) (cadr x)))))
  848. (setq res (delq nil res))
  849. (when user
  850. (dolist (x res)
  851. (setcar x user)))
  852. (setq res (delete-dups res))
  853. (let* ((old-ivy-last ivy-last)
  854. (enable-recursive-minibuffers t)
  855. (host (let ((ivy-auto-select-single-candidate nil))
  856. (ivy-read "user@host: "
  857. (mapcar #'ivy-build-tramp-name res)
  858. :initial-input rest))))
  859. (setq ivy-last old-ivy-last)
  860. (when host
  861. (setq ivy--directory "/")
  862. (ivy--cd (concat "/" method ":" host ":/"))))))
  863. (defun ivy--directory-done ()
  864. "Handle exit from the minibuffer when completing file names."
  865. (let ((dir (ivy--handle-directory ivy-text)))
  866. (cond ((equal (ivy-state-current ivy-last) (ivy-state-def ivy-last))
  867. (ivy-done))
  868. ((and (ivy-state-require-match ivy-last)
  869. (equal ivy-text "")
  870. (null ivy--old-cands))
  871. (ivy-immediate-done))
  872. (dir
  873. (let ((inhibit-message t))
  874. (ivy--cd dir)))
  875. ((ivy--directory-enter))
  876. ((unless (string= ivy-text "")
  877. ;; Obsolete since 26.1 and removed in 28.1.
  878. (defvar tramp-completion-mode)
  879. (with-no-warnings
  880. (let* ((tramp-completion-mode t)
  881. (file (expand-file-name
  882. (if (> ivy--length 0) (ivy-state-current ivy-last) ivy-text)
  883. ivy--directory)))
  884. (when (ignore-errors (file-exists-p file))
  885. (if (file-directory-p file)
  886. (ivy--cd (file-name-as-directory file))
  887. (ivy-done))
  888. ivy-text)))))
  889. ((or (and (equal ivy--directory "/")
  890. (string-match-p "\\`[^/]+:.*:.*\\'" ivy-text))
  891. (string-match-p "\\`/[^/]+:.*:.*\\'" ivy-text))
  892. (ivy-done))
  893. ((ivy--tramp-prefix-p)
  894. (ivy--tramp-candidates))
  895. (t
  896. (ivy-done)))))
  897. (defun ivy--tramp-prefix-p ()
  898. (or (and (equal ivy--directory "/")
  899. (cond ((string-match
  900. "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
  901. ivy-text)
  902. (save-match-data
  903. (ivy-set-text (ivy-state-current ivy-last))))
  904. ((string-match
  905. "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
  906. (ivy-state-current ivy-last))
  907. (save-match-data
  908. (ivy-set-text (ivy-state-current ivy-last))))))
  909. (string-match
  910. "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
  911. ivy-text)))
  912. (defun ivy-expand-file-if-directory (file-name)
  913. "Expand FILE-NAME as directory.
  914. When this directory doesn't exist, return nil."
  915. (when (stringp file-name)
  916. (let ((full-name
  917. ;; Ignore host name must not match method "ssh"
  918. (ignore-errors
  919. (file-name-as-directory
  920. (expand-file-name file-name ivy--directory)))))
  921. (when (and full-name (file-directory-p full-name))
  922. full-name))))
  923. (defcustom ivy-tab-space nil
  924. "When non-nil, `ivy-partial-or-done' should insert a space."
  925. :type 'boolean)
  926. (defun ivy-partial-or-done ()
  927. "Complete the minibuffer text as much as possible.
  928. If the text hasn't changed as a result, forward to `ivy-alt-done'."
  929. (interactive)
  930. (cond
  931. ((and (numberp completion-cycle-threshold)
  932. (< (length ivy--all-candidates) completion-cycle-threshold))
  933. (let ((ivy-wrap t))
  934. (ivy-next-line)))
  935. ((and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
  936. (or (and (equal ivy--directory "/")
  937. (string-match-p "\\`[^/]+:.*\\'" ivy-text))
  938. (= (string-to-char ivy-text) ?/)))
  939. (let ((default-directory ivy--directory)
  940. dir)
  941. (minibuffer-complete)
  942. (ivy-set-text (ivy--input))
  943. (when (setq dir (ivy-expand-file-if-directory ivy-text))
  944. (ivy--cd dir))))
  945. (t
  946. (or (ivy-partial)
  947. (when (or (eq this-command last-command)
  948. (eq ivy--length 1))
  949. (ivy-alt-done))))))
  950. (defun ivy--partial-cd-for-single-directory ()
  951. (when (and
  952. (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
  953. (= 1 (length
  954. (ivy--re-filter
  955. (funcall ivy--regex-function
  956. (concat "^" (string-remove-prefix "^" ivy-text)))
  957. ivy--all-candidates)))
  958. (let ((default-directory ivy--directory))
  959. (file-directory-p (ivy-state-current ivy-last))))
  960. (ivy--directory-done)))
  961. (defun ivy-partial ()
  962. "Complete the minibuffer text as much as possible."
  963. (interactive)
  964. (let* ((parts (or (ivy--split-spaces ivy-text) (list "")))
  965. (tail (last parts))
  966. (postfix (car tail))
  967. (case-fold-search (ivy--case-fold-p ivy-text))
  968. (completion-ignore-case case-fold-search)
  969. (new (try-completion (string-remove-prefix "^" postfix)
  970. (if (ivy-state-dynamic-collection ivy-last)
  971. ivy--all-candidates
  972. (mapcar (lambda (str)
  973. (let ((i (string-match-p postfix str)))
  974. (and i (substring str i))))
  975. ivy--old-cands)))))
  976. (cond ((eq new t) nil)
  977. ((string= new ivy-text) nil)
  978. ((string= (car tail) (car (ivy--split-spaces new))) nil)
  979. (new
  980. (delete-region (minibuffer-prompt-end) (point-max))
  981. (setcar tail
  982. (if (= (string-to-char postfix) ?^)
  983. (concat "^" new)
  984. new))
  985. (ivy-set-text
  986. (concat
  987. (mapconcat #'identity parts " ")
  988. (and ivy-tab-space (not (= (length ivy--old-cands) 1)) " ")))
  989. (insert ivy-text)
  990. (ivy--partial-cd-for-single-directory)
  991. t))))
  992. (defvar ivy-completion-beg nil
  993. "Completion bounds start.")
  994. (defvar ivy-completion-end nil
  995. "Completion bounds end.")
  996. (defun ivy-immediate-done ()
  997. "Exit the minibuffer with current input instead of current candidate."
  998. (interactive)
  999. (delete-minibuffer-contents)
  1000. (setf (ivy-state-current ivy-last)
  1001. (cond ((or (not ivy--directory)
  1002. (eq (ivy-state-history ivy-last) 'grep-files-history))
  1003. ivy-text)
  1004. ((and (string= ivy-text "")
  1005. (eq (ivy-state-collection ivy-last)
  1006. #'read-file-name-internal))
  1007. (if (ivy-state-def ivy-last)
  1008. (if (and
  1009. (file-exists-p (ivy-state-def ivy-last))
  1010. (/= (length ivy--directory)
  1011. (1+ (length (expand-file-name (ivy-state-def ivy-last))))))
  1012. ivy--directory
  1013. (copy-sequence (ivy-state-def ivy-last)))
  1014. ivy--directory))
  1015. (t
  1016. (expand-file-name ivy-text ivy--directory))))
  1017. (insert (ivy-state-current ivy-last))
  1018. (setq ivy-completion-beg ivy-completion-end)
  1019. (setq ivy-exit 'done)
  1020. (exit-minibuffer))
  1021. (defun ivy--restore-session (&optional session)
  1022. "Resume a recorded completion SESSION, if any exists."
  1023. (when ivy--sessions
  1024. (unless session
  1025. (setq session (intern
  1026. (let ((ivy-last ivy-last)
  1027. ivy--all-candidates
  1028. ivy-text)
  1029. (ivy-read "Choose ivy session: "
  1030. ivy--sessions
  1031. :require-match t)))))
  1032. (setq ivy-last (or (cdr (assq session ivy--sessions))
  1033. ivy-last)))
  1034. (let ((data (plist-get (ivy-state-extra-props ivy-last) :ivy-data)))
  1035. (when data
  1036. (setq ivy--all-candidates (plist-get data :all-candidates))
  1037. (setq ivy-text (plist-get data :text)))))
  1038. ;;;###autoload
  1039. (defun ivy-resume (&optional session)
  1040. "Resume the last completion session, or SESSION if non-nil.
  1041. With a prefix arg, try to restore a recorded completion session,
  1042. if one exists."
  1043. (interactive)
  1044. (when (or current-prefix-arg session)
  1045. (ivy--restore-session session))
  1046. (if (or (null (ivy-state-action ivy-last))
  1047. (eq (ivy--get-action ivy-last) #'identity))
  1048. (user-error "The last session isn't compatible with `ivy-resume'")
  1049. (when (memq (ivy-state-caller ivy-last)
  1050. '(swiper
  1051. swiper-isearch swiper-backward
  1052. swiper-isearch-backward
  1053. counsel-grep))
  1054. (switch-to-buffer (ivy-state-buffer ivy-last)))
  1055. (with-current-buffer (ivy-state-buffer ivy-last)
  1056. (let ((default-directory (ivy-state-directory ivy-last))
  1057. (ivy-use-ignore-default (ivy-state-ignore ivy-last)))
  1058. (ivy-read
  1059. (ivy-state-prompt ivy-last)
  1060. (ivy-state-collection ivy-last)
  1061. :predicate (ivy-state-predicate ivy-last)
  1062. :require-match (ivy-state-require-match ivy-last)
  1063. :initial-input ivy-text
  1064. :history (ivy-state-history ivy-last)
  1065. :preselect (ivy-state-current ivy-last)
  1066. :keymap (ivy-state-keymap ivy-last)
  1067. :update-fn (ivy-state-update-fn ivy-last)
  1068. :sort (ivy-state-sort ivy-last)
  1069. :action (ivy-state-action ivy-last)
  1070. :unwind (ivy-state-unwind ivy-last)
  1071. :re-builder (ivy-state-re-builder ivy-last)
  1072. :matcher (ivy-state-matcher ivy-last)
  1073. :dynamic-collection (ivy-state-dynamic-collection ivy-last)
  1074. :extra-props (ivy-state-extra-props ivy-last)
  1075. :caller (ivy-state-caller ivy-last))))))
  1076. (defvar-local ivy-calling nil
  1077. "When non-nil, call the current action when `ivy--index' changes.")
  1078. (defun ivy-set-index (index)
  1079. "Set `ivy--index' to INDEX."
  1080. (setq ivy--index index)
  1081. (when ivy-calling
  1082. (ivy--exhibit)
  1083. (ivy-call)))
  1084. (defun ivy-beginning-of-buffer ()
  1085. "Select the first completion candidate."
  1086. (interactive)
  1087. (ivy-set-index 0))
  1088. (defun ivy-end-of-buffer ()
  1089. "Select the last completion candidate."
  1090. (interactive)
  1091. (ivy-set-index (1- ivy--length)))
  1092. (defun ivy-scroll-up-command ()
  1093. "Scroll the candidates upward by the minibuffer height."
  1094. (interactive)
  1095. (ivy-set-index (min (1- (+ ivy--index ivy-height))
  1096. (1- ivy--length))))
  1097. (defun ivy-scroll-down-command ()
  1098. "Scroll the candidates downward by the minibuffer height."
  1099. (interactive)
  1100. (ivy-set-index (max (1+ (- ivy--index ivy-height))
  1101. 0)))
  1102. (defun ivy-next-line (&optional arg)
  1103. "Move cursor vertically down ARG candidates."
  1104. (interactive "p")
  1105. (setq arg (or arg 1))
  1106. (let ((index (+ ivy--index arg)))
  1107. (if (> index (1- ivy--length))
  1108. (if ivy-wrap
  1109. (ivy-beginning-of-buffer)
  1110. (ivy-set-index (1- ivy--length)))
  1111. (ivy-set-index index))))
  1112. (defun ivy-next-line-or-history (&optional arg)
  1113. "Move cursor vertically down ARG candidates.
  1114. If the input is empty, select the previous history element instead."
  1115. (interactive "p")
  1116. (let ((orig-index ivy--index))
  1117. (ivy-next-line arg)
  1118. (when (and (string= ivy-text "") (= ivy--index orig-index))
  1119. (ivy-previous-history-element 1))))
  1120. (defun ivy-previous-line (&optional arg)
  1121. "Move cursor vertically up ARG candidates."
  1122. (interactive "p")
  1123. (setq arg (or arg 1))
  1124. (let ((index (- ivy--index arg))
  1125. (min-index (if ivy--use-selectable-prompt -1 0)))
  1126. (if (< index min-index)
  1127. (if ivy-wrap
  1128. (ivy-end-of-buffer)
  1129. (ivy-set-index min-index))
  1130. (ivy-set-index index))))
  1131. (defun ivy-previous-line-or-history (arg)
  1132. "Move cursor vertically up ARG candidates.
  1133. If the input is empty, select the previous history element instead."
  1134. (interactive "p")
  1135. (let ((orig-index ivy--index))
  1136. (ivy-previous-line arg)
  1137. (when (and (string= ivy-text "") (= ivy--index orig-index))
  1138. (ivy-previous-history-element 1))))
  1139. (defun ivy-toggle-calling ()
  1140. "Flip `ivy-calling'."
  1141. (interactive)
  1142. (when (setq ivy-calling (not ivy-calling))
  1143. (ivy-call)))
  1144. (defun ivy-toggle-ignore ()
  1145. "Toggle user-configured candidate filtering."
  1146. (interactive)
  1147. (setq ivy-use-ignore
  1148. (if ivy-use-ignore
  1149. nil
  1150. (or ivy-use-ignore-default t)))
  1151. (setf (ivy-state-ignore ivy-last) ivy-use-ignore)
  1152. ;; invalidate cache
  1153. (setq ivy--old-cands nil))
  1154. (defun ivy--get-action (state)
  1155. "Get the action function from STATE."
  1156. (let ((action (ivy-state-action state)))
  1157. (when action
  1158. (if (functionp action)
  1159. action
  1160. (cadr (nth (car action) action))))))
  1161. (defun ivy--get-multi-action (state)
  1162. "Get the multi-action function from STATE."
  1163. (let* ((action (ivy-state-action state))
  1164. (multi-action
  1165. (and (listp action)
  1166. (not (eq (car action) 'lambda))
  1167. (nth 3 (nth (car action) action)))))
  1168. (if multi-action
  1169. multi-action
  1170. (when (eq (car action) 1)
  1171. (ivy-state-multi-action state)))))
  1172. (defun ivy--get-window (state)
  1173. "Get the window from STATE."
  1174. (if (ivy-state-p state)
  1175. (let ((window (ivy-state-window state)))
  1176. (if (window-live-p window)
  1177. window
  1178. (next-window)))
  1179. (selected-window)))
  1180. (defun ivy--actionp (x)
  1181. "Return non-nil when X is a list of actions."
  1182. (and (consp x) (not (memq (car x) '(closure lambda)))))
  1183. (defcustom ivy-action-wrap nil
  1184. "When non-nil, `ivy-next-action' and `ivy-prev-action' wrap."
  1185. :type 'boolean)
  1186. (defun ivy-next-action ()
  1187. "When the current action is a list, scroll it forwards."
  1188. (interactive)
  1189. (let ((action (ivy-state-action ivy-last)))
  1190. (when (ivy--actionp action)
  1191. (let ((len (1- (length action)))
  1192. (idx (car action)))
  1193. (if (>= idx len)
  1194. (when ivy-action-wrap
  1195. (setf (car action) 1))
  1196. (cl-incf (car action)))))))
  1197. (defun ivy-prev-action ()
  1198. "When the current action is a list, scroll it backwards."
  1199. (interactive)
  1200. (let ((action (ivy-state-action ivy-last)))
  1201. (when (ivy--actionp action)
  1202. (if (<= (car action) 1)
  1203. (when ivy-action-wrap
  1204. (setf (car action) (1- (length action))))
  1205. (cl-decf (car action))))))
  1206. (defun ivy-action-name ()
  1207. "Return the name associated with the current action."
  1208. (let ((action (ivy-state-action ivy-last)))
  1209. (if (ivy--actionp action)
  1210. (format "[%d/%d] %s"
  1211. (car action)
  1212. (1- (length action))
  1213. (nth 2 (nth (car action) action)))
  1214. "[1/1] default")))
  1215. (defvar ivy-inhibit-action nil
  1216. "When non-nil, `ivy-call' does nothing.
  1217. Example use:
  1218. (let* ((ivy-inhibit-action t)
  1219. (str (ivy-switch-buffer)))
  1220. ;; do whatever with str - the corresponding buffer will not be opened
  1221. )")
  1222. (defun ivy-recursive-restore ()
  1223. "Restore the above state when exiting the minibuffer.
  1224. See variable `ivy-recursive-restore' for further information."
  1225. (when (and ivy-recursive-last
  1226. ivy-recursive-restore
  1227. (not (eq ivy-last ivy-recursive-last)))
  1228. (ivy--reset-state (setq ivy-last ivy-recursive-last))))
  1229. (defvar ivy-mark-prefix ">"
  1230. "Prefix used by `ivy-mark'.")
  1231. (defun ivy--call-marked (action)
  1232. (let* ((prefix-len (length ivy-mark-prefix))
  1233. (marked-candidates
  1234. (mapcar
  1235. (lambda (s)
  1236. (let ((cand (substring s prefix-len)))
  1237. (if ivy--directory
  1238. (expand-file-name cand ivy--directory)
  1239. cand)))
  1240. ivy-marked-candidates))
  1241. (multi-action (ivy--get-multi-action ivy-last)))
  1242. (if multi-action
  1243. (let ((default-directory (ivy-state-directory ivy-last)))
  1244. (funcall multi-action (mapcar #'ivy--call-cand marked-candidates)))
  1245. (dolist (c marked-candidates)
  1246. (let ((default-directory (ivy-state-directory ivy-last)))
  1247. (funcall action (ivy--call-cand c)))))))
  1248. (defun ivy--call-cand (current)
  1249. (let ((collection (ivy-state-collection ivy-last)))
  1250. (cond
  1251. ;; Alist type.
  1252. ((and (consp (car-safe collection))
  1253. ;; Previously, the cdr of the selected
  1254. ;; candidate would be returned. Now, the
  1255. ;; whole candidate is returned.
  1256. (let ((idx (get-text-property 0 'idx current)))
  1257. (if idx
  1258. (progn
  1259. (ivy--remove-props current 'idx)
  1260. (nth idx collection))
  1261. (assoc current collection)))))
  1262. (ivy--directory
  1263. (expand-file-name current ivy--directory))
  1264. ((equal current "")
  1265. ivy-text)
  1266. (t
  1267. current))))
  1268. (defun ivy-call ()
  1269. "Call the current action without exiting completion."
  1270. (interactive)
  1271. ;; Testing with `ivy-with' seems to call `ivy-call' again,
  1272. ;; in which case `this-command' is nil; so check for this.
  1273. (unless (memq this-command '(nil
  1274. ivy-done
  1275. ivy-alt-done
  1276. ivy-dispatching-done))
  1277. (setq ivy-current-prefix-arg current-prefix-arg))
  1278. (let* ((action
  1279. (if (functionp ivy-inhibit-action)
  1280. ivy-inhibit-action
  1281. (and (not ivy-inhibit-action)
  1282. (ivy--get-action ivy-last))))
  1283. (current (ivy-state-current ivy-last))
  1284. (x (ivy--call-cand current))
  1285. (res
  1286. (cond
  1287. ((null action)
  1288. current)
  1289. (t
  1290. (select-window (ivy--get-window ivy-last))
  1291. (set-buffer (ivy-state-buffer ivy-last))
  1292. (prog1 (unwind-protect
  1293. (if ivy-marked-candidates
  1294. (ivy--call-marked action)
  1295. (funcall action x))
  1296. (ivy-recursive-restore))
  1297. (unless (or (eq ivy-exit 'done)
  1298. (minibuffer-window-active-p (selected-window))
  1299. (null (active-minibuffer-window)))
  1300. (select-window (active-minibuffer-window))))))))
  1301. (if ivy-inhibit-action
  1302. res
  1303. current)))
  1304. (defun ivy-call-and-recenter ()
  1305. "Call action and recenter window according to the selected candidate."
  1306. (interactive)
  1307. (ivy-call)
  1308. (with-ivy-window
  1309. (recenter-top-bottom)))
  1310. (defun ivy-next-line-and-call (&optional arg)
  1311. "Move cursor vertically down ARG candidates.
  1312. Call the permanent action if possible."
  1313. (interactive "p")
  1314. (ivy-next-line arg)
  1315. (ivy--exhibit)
  1316. (ivy-call))
  1317. (defun ivy-previous-line-and-call (&optional arg)
  1318. "Move cursor vertically up ARG candidates.
  1319. Call the permanent action if possible."
  1320. (interactive "p")
  1321. (ivy-previous-line arg)
  1322. (ivy--exhibit)
  1323. (ivy-call))
  1324. (defun ivy-previous-history-element (arg)
  1325. "Forward to `previous-history-element' with ARG."
  1326. (interactive "p")
  1327. (previous-history-element arg)
  1328. (ivy--cd-maybe)
  1329. (move-end-of-line 1)
  1330. (ivy--maybe-scroll-history))
  1331. (defun ivy--insert-symbol-boundaries ()
  1332. (undo-boundary)
  1333. (beginning-of-line)
  1334. (insert "\\_<")
  1335. (end-of-line)
  1336. (insert "\\_>"))
  1337. (defun ivy-next-history-element (arg)
  1338. "Forward to `next-history-element' with ARG."
  1339. (interactive "p")
  1340. (if (and (= minibuffer-history-position 0)
  1341. (equal ivy-text ""))
  1342. (progn
  1343. (when minibuffer-default
  1344. (setq ivy--default (car minibuffer-default)))
  1345. (insert ivy--default)
  1346. (when (and (with-ivy-window (derived-mode-p 'prog-mode))
  1347. (eq (ivy-state-caller ivy-last) 'swiper)
  1348. (not (file-exists-p ivy--default))
  1349. (not (ivy-ffap-url-p ivy--default))
  1350. (not (ivy-state-dynamic-collection ivy-last))
  1351. (> (point) (minibuffer-prompt-end)))
  1352. (ivy--insert-symbol-boundaries)))
  1353. (next-history-element arg))
  1354. (ivy--cd-maybe)
  1355. (move-end-of-line 1)
  1356. (ivy--maybe-scroll-history))
  1357. (defvar ivy-ffap-url-functions nil
  1358. "List of functions that check if the point is on a URL.")
  1359. (defun ivy--cd-maybe ()
  1360. "Check if the current input points to a different directory.
  1361. If so, move to that directory, while keeping only the file name."
  1362. (when ivy--directory
  1363. (let ((input (ivy--input))
  1364. url)
  1365. (if (setq url (or (ivy-ffap-url-p input)
  1366. (with-ivy-window
  1367. (cl-reduce
  1368. (lambda (a b)
  1369. (or a (funcall b)))
  1370. ivy-ffap-url-functions
  1371. :initial-value nil))))
  1372. (ivy-exit-with-action
  1373. (lambda (_)
  1374. (ivy-ffap-url-fetcher url))
  1375. 'no-update-history)
  1376. (setq input (expand-file-name input))
  1377. (let ((file (file-name-nondirectory input))
  1378. (dir (expand-file-name (file-name-directory input))))
  1379. (if (string= dir ivy--directory)
  1380. (progn
  1381. (delete-minibuffer-contents)
  1382. (insert file))
  1383. (ivy--cd dir)
  1384. (insert file)))))))
  1385. (defun ivy--maybe-scroll-history ()
  1386. "If the selected history element has an index, scroll there."
  1387. (let ((idx (ignore-errors
  1388. (get-text-property
  1389. (minibuffer-prompt-end)
  1390. 'ivy-index))))
  1391. (when idx
  1392. (ivy--exhibit)
  1393. (ivy-set-index idx))))
  1394. (declare-function tramp-get-completion-methods "tramp")
  1395. (defun ivy--cd (dir)
  1396. "When completing file names, move to directory DIR."
  1397. (if (ivy--completing-fname-p)
  1398. (progn
  1399. (push dir ivy--directory-hist)
  1400. (setq ivy--old-cands nil)
  1401. (setq ivy--old-re nil)
  1402. (ivy-set-index 0)
  1403. (setq ivy--all-candidates
  1404. (append
  1405. (ivy--sorted-files (setq ivy--directory dir))
  1406. (when (and (string= dir "/") (featurep 'tramp))
  1407. (sort
  1408. (mapcar
  1409. (lambda (s) (substring s 1))
  1410. (tramp-get-completion-methods ""))
  1411. #'string<))))
  1412. (ivy-set-text "")
  1413. (setf (ivy-state-directory ivy-last) dir)
  1414. (delete-minibuffer-contents))
  1415. (error "Unexpected")))
  1416. (defun ivy--parent-dir (filename)
  1417. "Return parent directory of absolute FILENAME."
  1418. (file-name-directory (directory-file-name filename)))
  1419. (defun ivy-backward-delete-char ()
  1420. "Forward to `delete-backward-char'.
  1421. Call `ivy-on-del-error-function' if an error occurs, usually when
  1422. there is no more text to delete at the beginning of the
  1423. minibuffer."
  1424. (interactive)
  1425. (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
  1426. (progn
  1427. (ivy--cd (ivy--parent-dir (expand-file-name ivy--directory)))
  1428. (ivy--exhibit))
  1429. (setq prefix-arg current-prefix-arg)
  1430. (condition-case nil
  1431. (call-interactively #'delete-backward-char)
  1432. (error
  1433. (when ivy-on-del-error-function
  1434. (funcall ivy-on-del-error-function))))))
  1435. (defun ivy-delete-char (arg)
  1436. "Forward to `delete-char' ARG."
  1437. (interactive "p")
  1438. (unless (eolp)
  1439. (delete-char arg)))
  1440. (defun ivy-forward-char (arg)
  1441. "Forward to `forward-char' ARG."
  1442. (interactive "p")
  1443. (unless (eolp)
  1444. (forward-char arg)))
  1445. (defun ivy-kill-word (arg)
  1446. "Forward to `kill-word' ARG."
  1447. (interactive "p")
  1448. (unless (eolp)
  1449. (kill-word arg)))
  1450. (defun ivy-kill-line ()
  1451. "Forward to `kill-line'."
  1452. (interactive)
  1453. (if (eolp)
  1454. (kill-region (minibuffer-prompt-end) (point))
  1455. (kill-line)))
  1456. (defun ivy-kill-whole-line ()
  1457. "Forward to `kill-whole-line'."
  1458. (interactive)
  1459. (kill-region (minibuffer-prompt-end) (line-end-position)))
  1460. (defun ivy-backward-kill-word ()
  1461. "Forward to `backward-kill-word'."
  1462. (interactive)
  1463. (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
  1464. (progn
  1465. (ivy--cd (ivy--parent-dir (expand-file-name ivy--directory)))
  1466. (ivy--exhibit))
  1467. (ignore-errors
  1468. (let ((pt (point))
  1469. (last-command (if (eq last-command 'ivy-backward-kill-word)
  1470. 'kill-region
  1471. last-command)))
  1472. (forward-word -1)
  1473. (kill-region pt (point))))))
  1474. (defvar ivy--regexp-quote #'regexp-quote
  1475. "Store the regexp quoting state.")
  1476. (defun ivy-toggle-regexp-quote ()
  1477. "Toggle the regexp quoting."
  1478. (interactive)
  1479. (setq ivy--old-re nil)
  1480. (cl-rotatef ivy--regex-function ivy--regexp-quote)
  1481. (setq ivy--old-text "")
  1482. (setq ivy-regex (funcall ivy--regex-function ivy-text)))
  1483. (defcustom ivy-format-functions-alist
  1484. '((t . ivy-format-function-default))
  1485. "An alist of functions that transform the list of candidates into a string.
  1486. This string is inserted into the minibuffer."
  1487. :type '(alist
  1488. :key-type symbol
  1489. :value-type
  1490. (choice
  1491. (const :tag "Default" ivy-format-function-default)
  1492. (const :tag "Arrow prefix" ivy-format-function-arrow)
  1493. (const :tag "Full line" ivy-format-function-line)
  1494. (function :tag "Custom function"))))
  1495. (defun ivy-sort-file-function-default (x y)
  1496. "Compare two files X and Y.
  1497. Prioritize directories."
  1498. (if (get-text-property 0 'dirp x)
  1499. (if (get-text-property 0 'dirp y)
  1500. (string< (directory-file-name x) (directory-file-name y))
  1501. t)
  1502. (if (get-text-property 0 'dirp y)
  1503. nil
  1504. (string< x y))))
  1505. (defun ivy-string< (x y)
  1506. "Like `string<', but operate on CARs when given cons cells."
  1507. (string< (if (consp x) (car x) x)
  1508. (if (consp y) (car y) y)))
  1509. (define-obsolete-function-alias 'ivy-sort-file-function-using-ido
  1510. 'ido-file-extension-lessp "<2019-10-12 Sat>")
  1511. (defcustom ivy-sort-functions-alist
  1512. '((t . ivy-string<))
  1513. "An alist of sorting functions for each collection function.
  1514. Interactive functions that call completion fit in here as well.
  1515. Nil means no sorting, which is useful to turn off the sorting for
  1516. functions that have candidates in the natural buffer order, like
  1517. `org-refile' or `Man-goto-section'.
  1518. A list can be used to associate multiple sorting functions with a
  1519. collection. The car of the list is the current sort
  1520. function. This list can be rotated with `ivy-rotate-sort'.
  1521. The entry associated with t is used for all fall-through cases.
  1522. See also `ivy-sort-max-size'."
  1523. :type
  1524. '(alist
  1525. :key-type (choice
  1526. (const :tag "Fall-through" t)
  1527. (symbol :tag "Collection"))
  1528. :value-type (choice
  1529. (const :tag "Plain sort" ivy-string<)
  1530. (const :tag "File sort" ivy-sort-file-function-default)
  1531. (const :tag "File sort using Ido" ido-file-extension-lessp)
  1532. (const :tag "No sort" nil)
  1533. (function :tag "Custom function")
  1534. (repeat (function :tag "Custom function")))))
  1535. (defun ivy--sort-function (collection)
  1536. "Retrieve sort function for COLLECTION from `ivy-sort-functions-alist'."
  1537. (let ((entry (cdr (or (assq collection ivy-sort-functions-alist)
  1538. (assq (ivy-state-caller ivy-last) ivy-sort-functions-alist)
  1539. (assq t ivy-sort-functions-alist)))))
  1540. (and (or (functionp entry)
  1541. (functionp (setq entry (car-safe entry))))
  1542. entry)))
  1543. (defun ivy-rotate-sort ()
  1544. "Rotate through sorting functions available for current collection.
  1545. This only has an effect if multiple sorting functions are
  1546. specified for the current collection in
  1547. `ivy-sort-functions-alist'."
  1548. (interactive)
  1549. (let ((cell (or (assq (ivy-state-collection ivy-last) ivy-sort-functions-alist)
  1550. (assq (ivy-state-caller ivy-last) ivy-sort-functions-alist)
  1551. (assq t ivy-sort-functions-alist))))
  1552. (when (consp (cdr cell))
  1553. (setcdr cell (nconc (cddr cell) (list (cadr cell))))
  1554. (ivy--reset-state ivy-last))))
  1555. (defcustom ivy-index-functions-alist
  1556. '((t . ivy-recompute-index-zero))
  1557. "An alist of index recomputing functions for each collection function.
  1558. When the input changes, the appropriate function returns an
  1559. integer - the index of the matched candidate that should be
  1560. selected."
  1561. :type '(alist :key-type symbol :value-type function))
  1562. (defvar ivy-re-builders-alist
  1563. '((t . ivy--regex-plus))
  1564. "An alist of regex building functions for each collection function.
  1565. Each key is (in order of priority):
  1566. 1. The actual collection function, e.g. `read-file-name-internal'.
  1567. 2. The symbol passed by :caller into `ivy-read'.
  1568. 3. `this-command'.
  1569. 4. t.
  1570. Each value is a function that should take a string and return a
  1571. valid regex or a regex sequence (see below).
  1572. Possible choices: `ivy--regex', `regexp-quote',
  1573. `ivy--regex-plus', `ivy--regex-fuzzy', `ivy--regex-ignore-order'.
  1574. If a function returns a list, it should format like this:
  1575. '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
  1576. The matches will be filtered in a sequence, you can mix the
  1577. regexps that should match and that should not match as you
  1578. like.")
  1579. (defvar ivy-highlight-functions-alist
  1580. '((ivy--regex-ignore-order . ivy--highlight-ignore-order)
  1581. (ivy--regex-fuzzy . ivy--highlight-fuzzy)
  1582. (ivy--regex-plus . ivy--highlight-default))
  1583. "An alist of highlighting functions for each regex builder function.")
  1584. (defcustom ivy-initial-inputs-alist
  1585. '((org-refile . "^")
  1586. (org-agenda-refile . "^")
  1587. (org-capture-refile . "^")
  1588. (Man-completion-table . "^")
  1589. (woman . "^"))
  1590. "An alist associating commands with their initial input.
  1591. Each cdr is either a string or a function called in the context
  1592. of a call to `ivy-read'."
  1593. :type '(alist
  1594. :key-type (symbol)
  1595. :value-type (choice (string) (function))))
  1596. (defcustom ivy-hooks-alist nil
  1597. "An alist associating commands to setup functions.
  1598. Examples: `toggle-input-method', (lambda () (insert \"^\")), etc.
  1599. May supersede `ivy-initial-inputs-alist'."
  1600. :type '(alist :key-type symbol :value-type function))
  1601. (defvar ivy--occurs-list nil
  1602. "A list of custom occur generators per command.")
  1603. (defun ivy-set-occur (cmd occur)
  1604. "Assign CMD a custom OCCUR function."
  1605. (setq ivy--occurs-list
  1606. (plist-put ivy--occurs-list cmd occur)))
  1607. (defcustom ivy-update-fns-alist nil
  1608. "An alist associating commands to their :update-fn values."
  1609. :type '(alist
  1610. :key-type symbol
  1611. :value-type
  1612. (radio
  1613. (const :tag "Off" nil)
  1614. (const :tag "Call action on change" auto))))
  1615. (defcustom ivy-unwind-fns-alist nil
  1616. "An alist associating commands to their :unwind values."
  1617. :type '(alist :key-type symbol :value-type function))
  1618. (defcustom ivy-init-fns-alist nil
  1619. "An alist associating commands to their :init values.
  1620. An :init is a function with no arguments.
  1621. `ivy-read' calls it to initialize."
  1622. :type '(alist :key-type symbol :value-type function))
  1623. (defun ivy--alist-set (alist-sym key val)
  1624. (let ((curr-val (symbol-value alist-sym))
  1625. (customized-val (get alist-sym 'customized-value))
  1626. (default-val (eval (car (get alist-sym 'standard-value)))))
  1627. ;; when the value was set by `customize-set-variable', don't touch it
  1628. (unless customized-val
  1629. ;; only works if the value wasn't customized by the user
  1630. (when (or (null default-val) (equal curr-val default-val))
  1631. (let ((cell (assoc key curr-val)))
  1632. (if cell
  1633. (setcdr cell val)
  1634. (set alist-sym (cons (cons key val)
  1635. (symbol-value alist-sym)))))
  1636. (when default-val
  1637. (put alist-sym 'standard-value
  1638. (list (list 'quote (symbol-value alist-sym)))))))))
  1639. (declare-function counsel-set-async-exit-code "counsel")
  1640. (defvar ivy--parents-alist nil
  1641. "Configure parent caller for child caller.
  1642. The child caller inherits and can override the settings of the parent.")
  1643. (cl-defun ivy-configure (caller
  1644. &key
  1645. parent
  1646. initial-input
  1647. height
  1648. occur
  1649. update-fn
  1650. init-fn
  1651. unwind-fn
  1652. index-fn
  1653. sort-fn
  1654. sort-matches-fn
  1655. format-fn
  1656. display-fn
  1657. display-transformer-fn
  1658. alt-done-fn
  1659. more-chars
  1660. grep-p
  1661. exit-codes)
  1662. "Configure `ivy-read' params for CALLER."
  1663. (declare (indent 1))
  1664. (when parent
  1665. (ivy--alist-set 'ivy--parents-alist caller parent))
  1666. (when initial-input
  1667. (ivy--alist-set 'ivy-initial-inputs-alist caller initial-input))
  1668. (when height
  1669. (ivy--alist-set 'ivy-height-alist caller height))
  1670. (when occur
  1671. (ivy-set-occur caller occur))
  1672. (when update-fn
  1673. (ivy--alist-set 'ivy-update-fns-alist caller update-fn))
  1674. (when unwind-fn
  1675. (ivy--alist-set 'ivy-unwind-fns-alist caller unwind-fn))
  1676. (when init-fn
  1677. (ivy--alist-set 'ivy-init-fns-alist caller init-fn))
  1678. (when index-fn
  1679. (ivy--alist-set 'ivy-index-functions-alist caller index-fn))
  1680. (when sort-fn
  1681. (ivy--alist-set 'ivy-sort-functions-alist caller sort-fn))
  1682. (when sort-matches-fn
  1683. (ivy--alist-set 'ivy-sort-matches-functions-alist caller sort-matches-fn))
  1684. (when format-fn
  1685. (ivy--alist-set 'ivy-format-functions-alist caller format-fn))
  1686. (when display-fn
  1687. (ivy--alist-set 'ivy-display-functions-alist caller display-fn))
  1688. (when display-transformer-fn
  1689. (ivy--alist-set 'ivy--display-transformers-alist caller display-transformer-fn))
  1690. (when alt-done-fn
  1691. (ivy--alist-set 'ivy-alt-done-functions-alist caller alt-done-fn))
  1692. (when more-chars
  1693. (ivy--alist-set 'ivy-more-chars-alist caller more-chars))
  1694. (when grep-p
  1695. (cl-pushnew caller ivy-highlight-grep-commands))
  1696. (when exit-codes
  1697. (let (code msg)
  1698. (while (and (setq code (pop exit-codes))
  1699. (setq msg (pop exit-codes)))
  1700. (counsel-set-async-exit-code caller code msg)))))
  1701. (defcustom ivy-sort-max-size 30000
  1702. "Sorting won't be done for collections larger than this."
  1703. :type 'integer)
  1704. (defalias 'ivy--dirname-p
  1705. ;; Added in Emacs 25.1.
  1706. (if (fboundp 'directory-name-p)
  1707. #'directory-name-p
  1708. (lambda (name)
  1709. "Return non-nil if NAME ends with a directory separator."
  1710. (string-suffix-p "/" name))))
  1711. (defun ivy--sorted-files (dir)
  1712. "Return the list of files in DIR.
  1713. Directories come first."
  1714. (let* ((default-directory dir)
  1715. (seq (condition-case nil
  1716. (mapcar (lambda (s) (replace-regexp-in-string "\\$\\$" "$" s))
  1717. (all-completions "" #'read-file-name-internal
  1718. (ivy-state-predicate ivy-last)))
  1719. (error
  1720. (directory-files dir))))
  1721. sort-fn)
  1722. (setq seq (delete "./" (delete "../" seq)))
  1723. (when (eq (setq sort-fn (ivy--sort-function #'read-file-name-internal))
  1724. #'ivy-sort-file-function-default)
  1725. (setq seq (mapcar (lambda (x)
  1726. (propertize x 'dirp (ivy--dirname-p x)))
  1727. seq)))
  1728. (when sort-fn
  1729. (setq seq (sort seq sort-fn)))
  1730. (dolist (dir ivy-extra-directories)
  1731. (push dir seq))
  1732. (if (string= dir "/")
  1733. (cl-remove-if (lambda (s) (string-match ":$" s)) (delete "../" seq))
  1734. seq)))
  1735. (defun ivy-alist-setting (alist &optional key)
  1736. "Return the value associated with KEY in ALIST, using `assq'.
  1737. KEY defaults to the last caller of `ivy-read'; if no entry is
  1738. found, it falls back to the key t."
  1739. (let ((caller (or key (ivy-state-caller ivy-last))))
  1740. (or
  1741. (and caller (cdr (assq caller alist)))
  1742. (let ((parent (cdr (assq caller ivy--parents-alist))))
  1743. (when parent
  1744. (ivy-alist-setting alist parent)))
  1745. (cdr (assq t alist)))))
  1746. (defun ivy--height (caller)
  1747. (let ((v (or (ivy-alist-setting ivy-height-alist caller)
  1748. ivy-height)))
  1749. (if (integerp v)
  1750. v
  1751. (if (functionp v)
  1752. (funcall v caller)
  1753. (error "Unexpected value: %S" v)))))
  1754. (defun ivy--remove-props (str &rest props)
  1755. "Return STR with text PROPS destructively removed."
  1756. (ignore-errors
  1757. (remove-list-of-text-properties 0 (length str) props str))
  1758. str)
  1759. (defun ivy--update-prompt (prompt)
  1760. (cond ((equal prompt "Keyword, C-h: ")
  1761. ;; auto-insert.el
  1762. "Keyword (C-M-j to end): ")
  1763. (t
  1764. ;; misearch.el
  1765. (replace-regexp-in-string "RET to end" "C-M-j to end" prompt))))
  1766. ;;** Entry Point
  1767. ;;;###autoload
  1768. (cl-defun ivy-read (prompt collection
  1769. &key
  1770. predicate require-match initial-input
  1771. history preselect def keymap update-fn sort
  1772. action multi-action
  1773. unwind re-builder matcher
  1774. dynamic-collection
  1775. extra-props
  1776. caller)
  1777. "Read a string in the minibuffer, with completion.
  1778. PROMPT is a string, normally ending in a colon and a space.
  1779. `ivy-count-format' is prepended to PROMPT during completion.
  1780. COLLECTION is either a list of strings, a function, an alist, or
  1781. a hash table, supplied for `minibuffer-completion-table'.
  1782. PREDICATE is applied to filter out the COLLECTION immediately.
  1783. This argument is for compatibility with `completing-read'.
  1784. When REQUIRE-MATCH is non-nil, only members of COLLECTION can be
  1785. selected.
  1786. If INITIAL-INPUT is non-nil, then insert that input in the
  1787. minibuffer initially.
  1788. HISTORY is a name of a variable to hold the completion session
  1789. history.
  1790. KEYMAP is composed with `ivy-minibuffer-map'.
  1791. PRESELECT, when non-nil, determines which one of the candidates
  1792. matching INITIAL-INPUT to select initially. An integer stands
  1793. for the position of the desired candidate in the collection,
  1794. counting from zero. Otherwise, use the first occurrence of
  1795. PRESELECT in the collection. Comparison is first done with
  1796. `equal'. If that fails, and when applicable, match PRESELECT as
  1797. a regular expression.
  1798. DEF is for compatibility with `completing-read'.
  1799. UPDATE-FN is called each time the candidate list is re-displayed.
  1800. When SORT is non-nil, `ivy-sort-functions-alist' determines how
  1801. to sort candidates before displaying them.
  1802. ACTION is a function to call after selecting a candidate.
  1803. It takes one argument, the selected candidate. If COLLECTION is
  1804. an alist, the argument is a cons cell, otherwise it's a string.
  1805. MULTI-ACTION, when non-nil, is called instead of ACTION when
  1806. there are marked candidates. It takes the list of candidates as
  1807. its only argument. When it's nil, ACTION is called on each marked
  1808. candidate.
  1809. UNWIND is a function of no arguments to call before exiting.
  1810. RE-BUILDER is a function transforming input text into a regex
  1811. pattern.
  1812. MATCHER is a function which can override how candidates are
  1813. filtered based on user input. It takes a regex pattern and a
  1814. list of candidates, and returns the list of matching candidates.
  1815. DYNAMIC-COLLECTION is a boolean specifying whether the list of
  1816. candidates is updated after each input by calling COLLECTION.
  1817. EXTRA-PROPS is a plist that can be used to store
  1818. collection-specific session-specific data.
  1819. CALLER is a symbol to uniquely identify the caller to `ivy-read'.
  1820. It is used, along with COLLECTION, to determine which
  1821. customizations apply to the current completion session."
  1822. (let ((init-fn (ivy-alist-setting ivy-init-fns-alist caller)))
  1823. (when init-fn
  1824. (funcall init-fn)))
  1825. ;; get un-stuck from an existing `read-key' overriding minibuffer keys
  1826. (when (equal overriding-local-map '(keymap))
  1827. (keyboard-quit))
  1828. (setq caller (or caller this-command))
  1829. (let* ((ivy-recursive-last (and (active-minibuffer-window) ivy-last))
  1830. (ivy--display-function
  1831. (when (or ivy-recursive-last
  1832. (not (window-minibuffer-p)))
  1833. (ivy-alist-setting ivy-display-functions-alist caller))))
  1834. (setq update-fn (or update-fn (ivy-alist-setting ivy-update-fns-alist caller)))
  1835. (setq unwind (or unwind (ivy-alist-setting ivy-unwind-fns-alist caller)))
  1836. (setq ivy-last
  1837. (make-ivy-state
  1838. :prompt (ivy--update-prompt prompt)
  1839. :collection collection
  1840. :predicate predicate
  1841. :require-match require-match
  1842. :initial-input initial-input
  1843. :history history
  1844. :preselect preselect
  1845. :keymap keymap
  1846. :update-fn (if (eq update-fn 'auto)
  1847. (lambda ()
  1848. (with-ivy-window
  1849. (funcall
  1850. (ivy--get-action ivy-last)
  1851. (if (consp (car-safe (ivy-state-collection ivy-last)))
  1852. (assoc (ivy-state-current ivy-last)
  1853. (ivy-state-collection ivy-last))
  1854. (ivy-state-current ivy-last)))))
  1855. update-fn)
  1856. :sort sort
  1857. :action (ivy--compute-extra-actions action caller)
  1858. :multi-action multi-action
  1859. :frame (selected-frame)
  1860. :window (selected-window)
  1861. :buffer (current-buffer)
  1862. :unwind unwind
  1863. :re-builder re-builder
  1864. :matcher matcher
  1865. :dynamic-collection dynamic-collection
  1866. :display-transformer-fn (ivy-alist-setting ivy--display-transformers-alist caller)
  1867. :directory default-directory
  1868. :extra-props extra-props
  1869. :caller caller
  1870. :def def))
  1871. (ivy--reset-state ivy-last)
  1872. (unwind-protect
  1873. (minibuffer-with-setup-hook
  1874. #'ivy--minibuffer-setup
  1875. (let* ((hist (or history 'ivy-history))
  1876. (minibuffer-completion-table collection)
  1877. (minibuffer-completion-predicate predicate)
  1878. (ivy-height (ivy--height caller))
  1879. (resize-mini-windows (unless (display-graphic-p)
  1880. 'grow-only)))
  1881. (if (and ivy-auto-select-single-candidate
  1882. ivy--all-candidates
  1883. (null (cdr ivy--all-candidates)))
  1884. (progn
  1885. (setf (ivy-state-current ivy-last)
  1886. (car ivy--all-candidates))
  1887. (setq ivy-exit 'done))
  1888. (condition-case err
  1889. (read-from-minibuffer
  1890. prompt
  1891. (ivy-state-initial-input ivy-last)
  1892. (make-composed-keymap keymap ivy-minibuffer-map)
  1893. nil
  1894. hist)
  1895. (error
  1896. (unless (equal err '(error "Selecting deleted buffer"))
  1897. (signal (car err) (cdr err))))))
  1898. (when (eq ivy-exit 'done)
  1899. (ivy--update-history hist))))
  1900. (let ((session (or (plist-get extra-props :session)
  1901. (unless (or (minibufferp)
  1902. (null (ivy-state-action ivy-last))
  1903. (eq (ivy--get-action ivy-last) #'identity))
  1904. caller))))
  1905. (when session
  1906. (setf (ivy-state-extra-props ivy-last)
  1907. (plist-put extra-props :ivy-data `(:all-candidates ,ivy--all-candidates
  1908. :text ,ivy-text)))
  1909. (ivy--alist-set 'ivy--sessions session ivy-last)))
  1910. (ivy--cleanup))
  1911. (ivy-call)))
  1912. (defun ivy--update-history (hist)
  1913. (let ((item
  1914. (if (or (string= ivy-text "")
  1915. (eq
  1916. (plist-get (ivy-state-extra-props ivy-last) :caller)
  1917. 'ivy-completing-read)
  1918. (eq (ivy-state-history ivy-last) 'file-name-history))
  1919. (ivy-state-current ivy-last)
  1920. ivy-text)))
  1921. (cond ((equal item ""))
  1922. ((stringp item)
  1923. (set hist (cons (propertize item 'ivy-index ivy--index)
  1924. (delete item (symbol-value hist))))))))
  1925. (defun ivy--cleanup ()
  1926. ;; Fixes a bug in ESS, #1660
  1927. (put 'post-command-hook 'permanent-local nil)
  1928. (remove-hook 'post-command-hook #'ivy--queue-exhibit)
  1929. (remove-hook 'window-size-change-functions #'ivy--window-size-changed)
  1930. (let ((cleanup (ivy--display-function-prop :cleanup))
  1931. (unwind (ivy-state-unwind ivy-last)))
  1932. (when (functionp cleanup)
  1933. (funcall cleanup))
  1934. (when unwind
  1935. (funcall unwind)))
  1936. (ivy--pulse-cleanup)
  1937. (unless (eq ivy-exit 'done)
  1938. (ivy-recursive-restore)))
  1939. (defun ivy--display-function-prop (prop)
  1940. "Return PROP associated with current `ivy--display-function'."
  1941. (plist-get (cdr (assq ivy--display-function
  1942. ivy-display-functions-props))
  1943. prop))
  1944. (defvar Info-complete-menu-buffer)
  1945. (defun ivy--alist-to-cands (alist)
  1946. "Transform ALIST to a list of strings."
  1947. (let ((i -1))
  1948. (mapcar (lambda (x)
  1949. (propertize x 'idx (cl-incf i)))
  1950. (all-completions "" alist))))
  1951. (defun ivy--reset-state (state)
  1952. "Reset the ivy to STATE.
  1953. This is useful for recursive `ivy-read'."
  1954. (setq ivy-marked-candidates nil)
  1955. (unless (equal (selected-frame) (ivy-state-frame state))
  1956. (select-window (active-minibuffer-window)))
  1957. (let* ((prompt (or (ivy-state-prompt state) ""))
  1958. (collection (ivy-state-collection state))
  1959. (predicate (ivy-state-predicate state))
  1960. (history (ivy-state-history state))
  1961. (preselect (ivy-state-preselect state))
  1962. (re-builder (ivy-state-re-builder state))
  1963. (dynamic-collection (ivy-state-dynamic-collection state))
  1964. (require-match (ivy-state-require-match state))
  1965. (caller (or (ivy-state-caller state) this-command))
  1966. (sort (or (ivy-state-sort state) (assoc caller ivy-sort-functions-alist)))
  1967. (initial-input
  1968. (or (ivy-state-initial-input state)
  1969. (let ((init (ivy-alist-setting ivy-initial-inputs-alist caller)))
  1970. (if (functionp init) (funcall init) init))))
  1971. (def (ivy-state-def state)))
  1972. (when (and (eq caller 'swiper-isearch) (buffer-modified-p))
  1973. (setq preselect nil))
  1974. (setq ivy--extra-candidates (ivy--compute-extra-candidates caller))
  1975. (setq ivy--directory nil)
  1976. (setq ivy--directory-hist (list default-directory))
  1977. (setq ivy-case-fold-search ivy-case-fold-search-default)
  1978. (setf (ivy-state-re-builder ivy-last)
  1979. (setq ivy--regex-function
  1980. (or re-builder
  1981. (and (functionp collection)
  1982. (cdr (assq collection ivy-re-builders-alist)))
  1983. (ivy-alist-setting ivy-re-builders-alist)
  1984. #'ivy--regex)))
  1985. (setq ivy--subexps 0)
  1986. (setq ivy--regexp-quote #'regexp-quote)
  1987. (setq ivy--old-text "")
  1988. (setq ivy--full-length nil)
  1989. (ivy-set-text (or initial-input ""))
  1990. (setq ivy--index 0)
  1991. (setq ivy-calling nil)
  1992. (setq ivy-use-ignore ivy-use-ignore-default)
  1993. (setf (ivy-state-ignore state) ivy-use-ignore)
  1994. (setq ivy--highlight-function
  1995. (or (cdr (assq (ivy-alist-setting ivy-re-builders-alist)
  1996. ivy-highlight-functions-alist))
  1997. #'ivy--highlight-default))
  1998. (let ((ivy-recursive-restore nil)
  1999. coll sort-fn)
  2000. (cond ((eq collection #'Info-read-node-name-1)
  2001. (setq coll
  2002. (if (equal (bound-and-true-p Info-current-file) "dir")
  2003. (mapcar (lambda (x) (format "(%s)" x))
  2004. (delete-dups
  2005. (all-completions "(" collection predicate)))
  2006. (all-completions "" collection predicate))))
  2007. ((memq collection '(read-file-name-internal ffap-read-file-or-url-internal))
  2008. (require 'tramp)
  2009. (when (and (equal def initial-input)
  2010. (member "./" ivy-extra-directories))
  2011. (setq def nil))
  2012. (setq ivy--directory default-directory)
  2013. (when (and initial-input
  2014. (not (equal initial-input "")))
  2015. (cond ((file-directory-p initial-input)
  2016. (when (equal (file-name-nondirectory initial-input) "")
  2017. (setf (ivy-state-preselect state) (setq preselect nil))
  2018. (setq def nil))
  2019. (setq ivy--directory (file-name-as-directory initial-input))
  2020. (setq initial-input nil)
  2021. (when preselect
  2022. (let ((preselect-directory
  2023. (file-name-directory preselect)))
  2024. (when (and preselect-directory
  2025. (not (equal
  2026. (expand-file-name
  2027. preselect-directory)
  2028. (expand-file-name ivy--directory))))
  2029. (setf (ivy-state-preselect state)
  2030. (setq preselect nil))))))
  2031. ((ignore-errors
  2032. (file-exists-p (file-name-directory initial-input)))
  2033. (setq ivy--directory (file-name-directory initial-input))
  2034. (setf (ivy-state-preselect state)
  2035. (file-name-nondirectory initial-input)))))
  2036. (require 'dired)
  2037. (when preselect
  2038. (let ((preselect-directory (ivy--parent-dir preselect)))
  2039. (when (and preselect-directory
  2040. (not (string= preselect-directory
  2041. default-directory)))
  2042. (setq ivy--directory preselect-directory))
  2043. (setq preselect (file-relative-name preselect
  2044. preselect-directory))
  2045. (setf (ivy-state-preselect state) preselect)))
  2046. (setq sort nil)
  2047. (setq coll (ivy--sorted-files ivy--directory))
  2048. (when initial-input
  2049. (unless (or require-match
  2050. (equal initial-input default-directory)
  2051. (equal initial-input ""))
  2052. (setq coll (cons initial-input coll)))
  2053. (setq initial-input (file-name-nondirectory initial-input))))
  2054. ((eq collection #'internal-complete-buffer)
  2055. (setq coll (ivy--buffer-list
  2056. ""
  2057. (and ivy-use-virtual-buffers
  2058. (member caller '(ivy-switch-buffer
  2059. ivy-switch-buffer-other-window
  2060. counsel-switch-buffer)))
  2061. predicate)))
  2062. (dynamic-collection
  2063. (setq coll (if (and (eq this-command 'ivy-resume) (not (buffer-modified-p)))
  2064. ivy--all-candidates
  2065. (ivy--dynamic-collection-cands (or initial-input "")))))
  2066. ((consp (car-safe collection))
  2067. (setq collection (cl-remove-if-not predicate collection))
  2068. (when (and sort (setq sort-fn (ivy--sort-function caller)))
  2069. (setq collection (sort (copy-sequence collection) sort-fn))
  2070. (setq sort nil))
  2071. (setf (ivy-state-collection ivy-last) collection)
  2072. (setq coll (ivy--alist-to-cands collection)))
  2073. ((or (functionp collection)
  2074. (byte-code-function-p collection)
  2075. (vectorp collection)
  2076. (hash-table-p collection)
  2077. (and (listp collection) (symbolp (car collection))))
  2078. (let ((Info-complete-menu-buffer
  2079. ;; FIXME: This is a temporary workaround for issue #1803.
  2080. (or (bound-and-true-p Info-complete-menu-buffer)
  2081. (ivy-state-buffer state))))
  2082. (setq coll (all-completions "" collection predicate))))
  2083. (t
  2084. (setq coll (all-completions "" collection predicate))))
  2085. (unless (ivy-state-dynamic-collection ivy-last)
  2086. (setq coll (delete "" coll)))
  2087. (when (and sort
  2088. (or (functionp collection)
  2089. (not (eq history 'org-refile-history)))
  2090. (setq sort-fn (ivy--sort-function
  2091. (if (functionp collection) collection caller)))
  2092. (listp coll)
  2093. (null (nthcdr ivy-sort-max-size coll)))
  2094. (setq coll (sort (copy-sequence coll) sort-fn)))
  2095. (when def
  2096. (cond ((stringp (car-safe def))
  2097. (setq coll
  2098. (delete-dups
  2099. (append def coll))))
  2100. ((and (stringp def) (not (member def coll)))
  2101. (push def coll))))
  2102. (setq coll (ivy--set-candidates coll))
  2103. (setq ivy--old-re nil)
  2104. (setq ivy--old-cands nil)
  2105. (when initial-input
  2106. ;; Needed for anchor to work
  2107. (setq ivy--old-cands coll)
  2108. (setq ivy--old-cands (ivy--filter initial-input coll)))
  2109. (unless (setq ivy--trying-to-resume-dynamic-collection
  2110. (and preselect dynamic-collection))
  2111. (when (integerp preselect)
  2112. (setq ivy--old-re "")
  2113. (ivy-set-index preselect)))
  2114. (setq ivy--all-candidates coll)
  2115. (unless (integerp preselect)
  2116. (ivy-set-index (or
  2117. (and dynamic-collection
  2118. ivy--index)
  2119. (and preselect
  2120. (ivy--preselect-index
  2121. preselect
  2122. (if initial-input
  2123. ivy--old-cands
  2124. coll)))
  2125. 0))))
  2126. (setq ivy-exit nil)
  2127. (setq ivy--default
  2128. (if (region-active-p)
  2129. (buffer-substring (region-beginning) (region-end))
  2130. (ivy-thing-at-point)))
  2131. (setq ivy--prompt (ivy-add-prompt-count (ivy--quote-format-string prompt)))
  2132. (setq ivy--use-selectable-prompt (ivy--prompt-selectable-p))
  2133. (setf (ivy-state-initial-input ivy-last) initial-input)))
  2134. (defun ivy-add-prompt-count (prompt)
  2135. "Add count information to PROMPT."
  2136. (cond ((null ivy-count-format)
  2137. (error "`ivy-count-format' must not be nil; set it to \"\" instead"))
  2138. ((string-match "%d.*\\(%d\\)" ivy-count-format)
  2139. (let* ((w
  2140. (if (listp ivy--all-candidates)
  2141. (1+ (floor (log (max 1 (length ivy--all-candidates)) 10)))
  2142. 1))
  2143. (s (replace-match (format "%%-%dd" w) t t ivy-count-format 1)))
  2144. (string-match "%d" s)
  2145. (concat (replace-match (format "%%%dd" w) t t s)
  2146. prompt)))
  2147. ((string-match-p "%.*d" ivy-count-format)
  2148. (concat ivy-count-format prompt))
  2149. (t
  2150. prompt)))
  2151. (defun ivy--quote-format-string (str)
  2152. "Make STR suitable for `format' with no extra arguments."
  2153. (replace-regexp-in-string "%" "%%" str t t))
  2154. ;;;###autoload
  2155. (defun ivy-completing-read (prompt collection
  2156. &optional predicate require-match initial-input
  2157. history def inherit-input-method)
  2158. "Read a string in the minibuffer, with completion.
  2159. This interface conforms to `completing-read' and can be used for
  2160. `completing-read-function'.
  2161. PROMPT is a string that normally ends in a colon and a space.
  2162. COLLECTION is either a list of strings, an alist, an obarray, or a hash table.
  2163. PREDICATE limits completion to a subset of COLLECTION.
  2164. REQUIRE-MATCH is a boolean value or a symbol. See `completing-read'.
  2165. INITIAL-INPUT is a string inserted into the minibuffer initially.
  2166. HISTORY is a list of previously selected inputs.
  2167. DEF is the default value.
  2168. INHERIT-INPUT-METHOD is currently ignored."
  2169. (let ((handler
  2170. (and (< ivy-completing-read-ignore-handlers-depth (minibuffer-depth))
  2171. (assq this-command ivy-completing-read-handlers-alist))))
  2172. (if handler
  2173. (let ((completion-in-region-function #'completion--in-region)
  2174. (ivy-completing-read-ignore-handlers-depth (1+ (minibuffer-depth))))
  2175. (funcall (cdr handler)
  2176. prompt collection
  2177. predicate require-match
  2178. initial-input history
  2179. def inherit-input-method))
  2180. ;; See the doc of `completing-read'.
  2181. (when (consp history)
  2182. (when (numberp (cdr history))
  2183. (setq initial-input (nth (1- (cdr history))
  2184. (symbol-value (car history)))))
  2185. (setq history (car history)))
  2186. (when (consp def)
  2187. (setq def (car def)))
  2188. (let ((str (ivy-read
  2189. prompt collection
  2190. :predicate predicate
  2191. :require-match (when (and collection require-match)
  2192. require-match)
  2193. :initial-input (cond ((consp initial-input)
  2194. (car initial-input))
  2195. ((and (stringp initial-input)
  2196. (not (eq collection #'read-file-name-internal))
  2197. (string-match-p "\\+" initial-input))
  2198. (replace-regexp-in-string
  2199. "\\+" "\\\\+" initial-input))
  2200. (t
  2201. initial-input))
  2202. :preselect def
  2203. :def def
  2204. :history history
  2205. :keymap nil
  2206. :dynamic-collection ivy-completing-read-dynamic-collection
  2207. :extra-props '(:caller ivy-completing-read)
  2208. :caller (if (and collection (symbolp collection))
  2209. collection
  2210. this-command))))
  2211. (if (string= str "")
  2212. ;; For `completing-read' compat, return the first element of
  2213. ;; DEFAULT, if it is a list; "", if DEFAULT is nil; or DEFAULT.
  2214. (or def "")
  2215. str)))))
  2216. (defun ivy-completing-read-with-empty-string-def
  2217. (prompt collection
  2218. &optional predicate require-match initial-input
  2219. history def inherit-input-method)
  2220. "Same as `ivy-completing-read' but with different handling of DEF.
  2221. Specifically, if DEF is nil, it is treated the same as if DEF was
  2222. the empty string. This mimics the behavior of
  2223. `completing-read-default'. This function can therefore be used in
  2224. place of `ivy-completing-read' for commands that rely on this
  2225. behavior."
  2226. (ivy-completing-read
  2227. prompt collection predicate require-match initial-input
  2228. history (or def "") inherit-input-method))
  2229. (declare-function mc/all-fake-cursors "ext:multiple-cursors-core")
  2230. ;; Kludge: Try to retain original minibuffer completion data.
  2231. (defvar ivy--minibuffer-table)
  2232. (defvar ivy--minibuffer-pred)
  2233. (defvar ivy--minibuffer-try nil
  2234. "Store original `try-completion' result for sole completions.")
  2235. (defun ivy-completion-in-region-action (str)
  2236. "Insert STR, erasing the previous one.
  2237. The previous string is between `ivy-completion-beg' and `ivy-completion-end'."
  2238. (when (consp str)
  2239. (setq str (cdr str)))
  2240. (when (stringp str)
  2241. (let ((fake-cursors (and (require 'multiple-cursors-core nil t)
  2242. (mc/all-fake-cursors)))
  2243. (pt (point))
  2244. (beg ivy-completion-beg)
  2245. (end ivy-completion-end))
  2246. (when beg
  2247. (delete-region beg end))
  2248. (setq ivy-completion-beg (point))
  2249. (insert (substring-no-properties str))
  2250. (let ((minibuffer-completion-table (if (boundp 'ivy--minibuffer-table)
  2251. ivy--minibuffer-table
  2252. (ivy-state-collection ivy-last)))
  2253. (minibuffer-completion-predicate (if (boundp 'ivy--minibuffer-pred)
  2254. ivy--minibuffer-pred
  2255. (ivy-state-predicate ivy-last))))
  2256. (completion--done str (cond ((eq ivy--minibuffer-try t) 'finished)
  2257. ((eq ivy-exit 'done) 'unknown)
  2258. ('exact))))
  2259. (setq ivy-completion-end (point))
  2260. (save-excursion
  2261. (dolist (cursor fake-cursors)
  2262. (goto-char (overlay-start cursor))
  2263. (delete-region (+ (point) (- beg pt))
  2264. (+ (point) (- end pt)))
  2265. (insert (substring-no-properties str))
  2266. ;; manually move the fake cursor
  2267. (move-overlay cursor (point) (1+ (point)))
  2268. (set-marker (overlay-get cursor 'point) (point))
  2269. (set-marker (overlay-get cursor 'mark) (point)))))))
  2270. (defun ivy-completion-common-length (str)
  2271. "Return the amount of characters that match in STR.
  2272. `completion-all-completions' computes this and returns the result
  2273. via text properties.
  2274. The first non-matching part is propertized:
  2275. - either with: (face (completions-first-difference))
  2276. - or: (font-lock-face completions-first-difference)."
  2277. (let ((char-property-alias-alist '((face font-lock-face)))
  2278. (i (1- (length str))))
  2279. (catch 'done
  2280. (while (>= i 0)
  2281. (when (equal (get-text-property i 'face str)
  2282. '(completions-first-difference))
  2283. (throw 'done i))
  2284. (cl-decf i))
  2285. (throw 'done (length str)))))
  2286. (defun ivy-completion-in-region (start end collection &optional predicate)
  2287. "An Ivy function suitable for `completion-in-region-function'.
  2288. The function completes the text between START and END using COLLECTION.
  2289. PREDICATE (a function called with no arguments) says when to exit.
  2290. See `completion-in-region' for further information."
  2291. (let* ((enable-recursive-minibuffers t)
  2292. (str (buffer-substring-no-properties start end))
  2293. (completion-ignore-case (ivy--case-fold-p str))
  2294. (md (completion-metadata str collection predicate))
  2295. (reg (- end start))
  2296. (comps (completion-all-completions str collection predicate reg md))
  2297. (try (completion-try-completion str collection predicate reg md))
  2298. (ivy--minibuffer-table collection)
  2299. (ivy--minibuffer-pred predicate))
  2300. (cond ((null comps)
  2301. (message "No matches"))
  2302. ((progn
  2303. (nconc comps nil)
  2304. (and (null (cdr comps))
  2305. (string= str (car comps))))
  2306. (message "Sole match"))
  2307. (t
  2308. (when (eq collection 'crm--collection-fn)
  2309. (setq comps (delete-dups comps)))
  2310. (let* ((len (ivy-completion-common-length (car comps)))
  2311. (initial (cond ((= len 0)
  2312. "")
  2313. ((let ((str-len (length str)))
  2314. (when (> len str-len)
  2315. (setq len str-len)
  2316. str)))
  2317. (t
  2318. (substring str (- len))))))
  2319. (delete-region (- end len) end)
  2320. (setq ivy-completion-beg (- end len))
  2321. (setq ivy-completion-end ivy-completion-beg)
  2322. (if (null (cdr comps))
  2323. (progn
  2324. (unless (minibuffer-window-active-p (selected-window))
  2325. (setf (ivy-state-window ivy-last) (selected-window)))
  2326. (let ((ivy--minibuffer-try try))
  2327. (ivy-completion-in-region-action
  2328. (substring-no-properties (car comps)))))
  2329. (dolist (s comps)
  2330. ;; Remove face `completions-first-difference'.
  2331. (ivy--remove-props s 'face))
  2332. (setq ivy--old-re nil)
  2333. (unless (ivy--filter initial comps)
  2334. (setq initial nil)
  2335. (setq predicate nil)
  2336. (setq collection comps))
  2337. (unless (derived-mode-p #'emacs-lisp-mode)
  2338. (setq collection comps)
  2339. (setq predicate nil))
  2340. (ivy-read (format "(%s): " str) collection
  2341. :predicate predicate
  2342. :initial-input (concat
  2343. (and (derived-mode-p #'emacs-lisp-mode)
  2344. "^")
  2345. initial)
  2346. :action #'ivy-completion-in-region-action
  2347. :unwind (lambda ()
  2348. (unless (eq ivy-exit 'done)
  2349. (goto-char ivy-completion-beg)
  2350. (when initial
  2351. (insert initial))))
  2352. :caller 'ivy-completion-in-region)))
  2353. ;; Return value should be non-nil on valid completion;
  2354. ;; see `completion-in-region'.
  2355. t))))
  2356. (defun ivy-completion-in-region-prompt ()
  2357. "Prompt function for `ivy-completion-in-region'.
  2358. See `ivy-set-prompt'."
  2359. (and (window-minibuffer-p (ivy-state-window ivy-last))
  2360. (ivy-add-prompt-count (ivy-state-prompt ivy-last))))
  2361. (ivy-set-prompt #'ivy-completion-in-region #'ivy-completion-in-region-prompt)
  2362. (defcustom ivy-do-completion-in-region t
  2363. "When non-nil `ivy-mode' will set `completion-in-region-function'."
  2364. :type 'boolean)
  2365. (defvar ivy--old-crf nil
  2366. "Store previous value of `completing-read-function'.")
  2367. (defvar ivy--old-cirf nil
  2368. "Store previous value of `completion-in-region-function'.")
  2369. ;;;###autoload
  2370. (define-minor-mode ivy-mode
  2371. "Toggle Ivy mode on or off.
  2372. Turn Ivy mode on if ARG is positive, off otherwise.
  2373. Turning on Ivy mode sets `completing-read-function' to
  2374. `ivy-completing-read'.
  2375. Global bindings:
  2376. \\{ivy-mode-map}
  2377. Minibuffer bindings:
  2378. \\{ivy-minibuffer-map}"
  2379. :group 'ivy
  2380. :global t
  2381. :keymap ivy-mode-map
  2382. :lighter " ivy"
  2383. (if ivy-mode
  2384. (progn
  2385. (unless (eq completing-read-function #'ivy-completing-read)
  2386. (setq ivy--old-crf completing-read-function)
  2387. (setq completing-read-function #'ivy-completing-read))
  2388. (when ivy-do-completion-in-region
  2389. (unless (eq completion-in-region-function #'ivy-completion-in-region)
  2390. (setq ivy--old-cirf completion-in-region-function)
  2391. (setq completion-in-region-function #'ivy-completion-in-region))))
  2392. (when (eq completing-read-function #'ivy-completing-read)
  2393. (setq completing-read-function (or ivy--old-crf
  2394. #'completing-read-default))
  2395. (setq ivy--old-crf nil))
  2396. (when (eq completion-in-region-function #'ivy-completion-in-region)
  2397. (setq completion-in-region-function (or ivy--old-cirf
  2398. #'completion--in-region))
  2399. (setq ivy--old-cirf nil))))
  2400. (defun ivy--preselect-index (preselect candidates)
  2401. "Return the index of PRESELECT in CANDIDATES."
  2402. (or (cond ((integerp preselect)
  2403. (if (integerp (car candidates))
  2404. (cl-position preselect candidates)
  2405. preselect))
  2406. ((cl-position preselect candidates :test #'equal))
  2407. ((ivy--regex-p preselect)
  2408. (cl-position preselect candidates :test #'string-match-p)))
  2409. 0))
  2410. ;;* Implementation
  2411. ;;** Regex
  2412. (defun ivy-re-match (re-seq str)
  2413. "Return non-nil if RE-SEQ is matched by STR.
  2414. RE-SEQ is a list of (RE . MATCH-P).
  2415. RE is a regular expression.
  2416. MATCH-P is t when RE should match STR and nil when RE should not
  2417. match STR.
  2418. Each element of RE-SEQ must match for the function to return true.
  2419. This concept is used to generalize regular expressions for
  2420. `ivy--regex-plus' and `ivy--regex-ignore-order'."
  2421. (let ((res t)
  2422. re)
  2423. (while (and res (setq re (pop re-seq)))
  2424. (setq res
  2425. (if (cdr re)
  2426. (string-match-p (car re) str)
  2427. (not (string-match-p (car re) str)))))
  2428. res))
  2429. (defvar ivy--regex-hash
  2430. (make-hash-table :test #'equal)
  2431. "Store pre-computed regex.")
  2432. (defvar ivy--input-garbage nil)
  2433. (defun ivy--split (str)
  2434. "Split STR into list of substrings bounded by spaces.
  2435. Single spaces act as splitting points. Consecutive spaces
  2436. \"quote\" their preceding spaces, i.e., guard them from being
  2437. split. This allows the literal interpretation of N spaces by
  2438. inputting N+1 spaces. Any substring not constituting a valid
  2439. regexp is passed to `regexp-quote'."
  2440. (let ((len (length str))
  2441. (i 0)
  2442. (start 0)
  2443. (res nil)
  2444. match-len
  2445. end
  2446. c)
  2447. (catch 'break
  2448. (while (< i len)
  2449. (setq c (aref str i))
  2450. (cond ((= ?\[ c)
  2451. (if (setq end (ivy--match-regex-brackets
  2452. (substring str i)))
  2453. (cl-incf i end)
  2454. (setq ivy--input-garbage (substring str i))
  2455. (throw 'break nil)))
  2456. ((= ?\\ c)
  2457. (if (and (< (1+ i) len) (= ?\( (aref str (1+ i))))
  2458. (progn
  2459. (when (> i start)
  2460. (push (substring str start i) res))
  2461. (if (eq (string-match "\\\\([^\0]*?\\\\)" str i) i)
  2462. (progn
  2463. (push (match-string 0 str) res)
  2464. (setq i (match-end 0))
  2465. (setq start i))
  2466. (setq ivy--input-garbage (substring str i))
  2467. (throw 'break nil)))
  2468. (cl-incf i)))
  2469. ((= ?\ c)
  2470. (string-match " +" str i)
  2471. (setq match-len (- (match-end 0) (match-beginning 0)))
  2472. (if (= match-len 1)
  2473. (progn
  2474. (when (> i start)
  2475. (push (substring str start i) res))
  2476. (setq start (1+ i)))
  2477. (setq str (replace-match
  2478. (make-string (1- match-len) ?\ )
  2479. nil nil str))
  2480. (setq len (length str))
  2481. (cl-incf i (1- match-len)))
  2482. (cl-incf i))
  2483. (t
  2484. (cl-incf i)))))
  2485. (when (< start i)
  2486. (push (substring str start) res))
  2487. (mapcar #'ivy--regex-or-literal (nreverse res))))
  2488. (defun ivy--match-regex-brackets (str)
  2489. (let ((len (length str))
  2490. (i 1)
  2491. (open-count 1)
  2492. c)
  2493. (while (and (< i len)
  2494. (> open-count 0))
  2495. (setq c (aref str i))
  2496. (cond ((= c ?\[)
  2497. (cl-incf open-count))
  2498. ((= c ?\])
  2499. (cl-decf open-count)))
  2500. (cl-incf i))
  2501. (when (= open-count 0)
  2502. (if (eq (string-match "[+*?]" str i) i)
  2503. (match-end 0)
  2504. i))))
  2505. (defun ivy--trim-trailing-re (regex)
  2506. "Trim incomplete REGEX.
  2507. If REGEX ends with \\|, trim it, since then it matches an empty string."
  2508. (if (string-match "\\`\\(.*\\)[\\]|\\'" regex)
  2509. (match-string 1 regex)
  2510. regex))
  2511. (defun ivy--regex (str &optional greedy)
  2512. "Re-build regex pattern from STR in case it has a space.
  2513. When GREEDY is non-nil, join words in a greedy way."
  2514. (let ((hashed (unless greedy
  2515. (gethash str ivy--regex-hash))))
  2516. (if hashed
  2517. (progn
  2518. (setq ivy--subexps (car hashed))
  2519. (cdr hashed))
  2520. (when (string-match-p "\\(?:[^\\]\\|^\\)\\\\\\'" str)
  2521. (setq str (substring str 0 -1)))
  2522. (setq str (ivy--trim-trailing-re str))
  2523. (cdr (puthash str
  2524. (let ((subs (ivy--split str)))
  2525. (if (= (length subs) 1)
  2526. (cons
  2527. (setq ivy--subexps 0)
  2528. (if (string-match-p "\\`\\.[^.]" (car subs))
  2529. (concat "\\." (substring (car subs) 1))
  2530. (car subs)))
  2531. (cons
  2532. (setq ivy--subexps (length subs))
  2533. (replace-regexp-in-string
  2534. "\\.\\*\\??\\\\( "
  2535. "\\( "
  2536. (mapconcat
  2537. (lambda (x)
  2538. (if (string-match-p "\\`\\\\([^?][^\0]*\\\\)\\'" x)
  2539. x
  2540. (format "\\(%s\\)" x)))
  2541. subs
  2542. (if greedy ".*" ".*?"))
  2543. nil t))))
  2544. ivy--regex-hash)))))
  2545. (defun ivy--regex-p (object)
  2546. "Return OBJECT if it is a valid regular expression, else nil."
  2547. (ignore-errors (string-match-p object "") object))
  2548. (defun ivy--regex-or-literal (str)
  2549. "If STR isn't a legal regexp, escape it."
  2550. (or (ivy--regex-p str) (regexp-quote str)))
  2551. (defun ivy--split-negation (str)
  2552. "Split STR into text before and after ! delimiter.
  2553. Do not split if the delimiter is escaped as \\!.
  2554. Assumes there is at most one un-escaped delimiter and discards
  2555. text after delimiter if it is empty. Modifies match data."
  2556. (unless (string= str "")
  2557. (let ((delim "\\(?:\\`\\|[^\\]\\)\\(!\\)"))
  2558. (mapcar (lambda (split)
  2559. ;; Store "\!" as "!".
  2560. (replace-regexp-in-string "\\\\!" "!" split t t))
  2561. (if (string-match delim str)
  2562. ;; Ignore everything past first un-escaped ! rather than
  2563. ;; crashing. We can't warn or error because the minibuffer is
  2564. ;; already active.
  2565. (let* ((i (match-beginning 1))
  2566. (j (and (string-match delim str (1+ i))
  2567. (match-beginning 1)))
  2568. (neg (substring str (1+ i) j)))
  2569. (cons (substring str 0 i)
  2570. (and (not (string= neg ""))
  2571. (list neg))))
  2572. (list str))))))
  2573. (defun ivy--split-spaces (str)
  2574. "Split STR on spaces, unless they're preceded by \\.
  2575. No un-escaped spaces are left in the output. Any substring not
  2576. constituting a valid regexp is passed to `regexp-quote'."
  2577. (when str
  2578. (let ((i 0) ; End of last search.
  2579. (j 0) ; End of last delimiter.
  2580. parts)
  2581. (while (string-match "\\(\\\\ \\)\\| +" str i)
  2582. (setq i (match-end 0))
  2583. (if (not (match-beginning 1))
  2584. ;; Un-escaped space(s).
  2585. (let ((delim (match-beginning 0)))
  2586. (when (< j delim)
  2587. (push (substring str j delim) parts))
  2588. (setq j i))
  2589. ;; Store "\ " as " ".
  2590. (setq str (replace-match " " t t str 1))
  2591. (setq i (1- i))))
  2592. (when (< j (length str))
  2593. (push (substring str j) parts))
  2594. (mapcar #'ivy--regex-or-literal (nreverse parts)))))
  2595. (defun ivy--regex-ignore-order (str)
  2596. "Re-build regex from STR by splitting at spaces and using ! for negation.
  2597. Examples:
  2598. foo -> matches \"foo\"
  2599. foo bar -> matches if both \"foo\" and \"bar\" match (any order)
  2600. foo !bar -> matches if \"foo\" matches and \"bar\" does not match
  2601. foo !bar baz -> matches if \"foo\" matches and neither \"bar\" nor \"baz\" match
  2602. foo[a-z] -> matches \"foo[a-z]\"
  2603. Escaping examples:
  2604. foo\\!bar -> matches \"foo!bar\"
  2605. foo\\ bar -> matches \"foo bar\"
  2606. Returns a list suitable for `ivy-re-match'."
  2607. (setq str (ivy--trim-trailing-re str))
  2608. (let* (regex-parts
  2609. (raw-parts (ivy--split-negation str)))
  2610. (dolist (part (ivy--split-spaces (car raw-parts)))
  2611. (push (cons part t) regex-parts))
  2612. (when (cdr raw-parts)
  2613. (dolist (part (ivy--split-spaces (cadr raw-parts)))
  2614. (push (cons part nil) regex-parts)))
  2615. (if regex-parts (nreverse regex-parts)
  2616. "")))
  2617. (defun ivy--regex-plus (str)
  2618. "Build a regex sequence from STR.
  2619. Spaces are wild card characters, everything before \"!\" should
  2620. match. Everything after \"!\" should not match."
  2621. (let ((parts (ivy--split-negation str)))
  2622. (cl-case (length parts)
  2623. (0
  2624. "")
  2625. (1
  2626. (if (= (aref str 0) ?!)
  2627. (list (cons "" t)
  2628. (list (ivy--regex (car parts))))
  2629. (ivy--regex (car parts))))
  2630. (2
  2631. (cons
  2632. (cons (ivy--regex (car parts)) t)
  2633. (mapcar #'list (split-string (cadr parts) " " t))))
  2634. (t (error "Unexpected: use only one !")))))
  2635. (defun ivy--regex-fuzzy (str)
  2636. "Build a regex sequence from STR.
  2637. Insert .* between each char."
  2638. (setq str (ivy--trim-trailing-re str))
  2639. (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
  2640. (prog1
  2641. (concat (match-string 1 str)
  2642. (let ((lst (string-to-list (match-string 2 str))))
  2643. (apply #'concat
  2644. (cl-mapcar
  2645. #'concat
  2646. (cons "" (cdr (mapcar (lambda (c) (format "[^%c\n]*" c))
  2647. lst)))
  2648. (mapcar (lambda (x) (format "\\(%s\\)" (regexp-quote (char-to-string x))))
  2649. lst))))
  2650. (match-string 3 str))
  2651. (setq ivy--subexps (length (match-string 2 str))))
  2652. str))
  2653. (defcustom ivy-fixed-height-minibuffer nil
  2654. "When non nil, fix the height of the minibuffer during ivy completion.
  2655. This effectively sets the minimum height at this level to `ivy-height' and
  2656. tries to ensure that it does not change depending on the number of candidates."
  2657. :type 'boolean)
  2658. ;;** Rest
  2659. (defcustom ivy-truncate-lines t
  2660. "Minibuffer setting for `truncate-lines'."
  2661. :type 'boolean)
  2662. (defun ivy--minibuffer-setup ()
  2663. "Setup ivy completion in the minibuffer."
  2664. (setq-local mwheel-scroll-up-function 'ivy-next-line)
  2665. (setq-local mwheel-scroll-down-function 'ivy-previous-line)
  2666. (setq-local completion-show-inline-help nil)
  2667. (setq-local line-spacing nil)
  2668. (setq-local minibuffer-default-add-function
  2669. (lambda ()
  2670. (list ivy--default)))
  2671. (setq-local inhibit-field-text-motion nil)
  2672. (setq truncate-lines ivy-truncate-lines)
  2673. (setq-local max-mini-window-height ivy-height)
  2674. (let ((height (cond ((and ivy-fixed-height-minibuffer
  2675. (not (eq (ivy-state-caller ivy-last)
  2676. #'ivy-completion-in-region)))
  2677. (+ ivy-height (if ivy-add-newline-after-prompt 1 0)))
  2678. (ivy-add-newline-after-prompt 2))))
  2679. (when height
  2680. (set-window-text-height nil height)))
  2681. (add-hook 'post-command-hook #'ivy--queue-exhibit nil t)
  2682. (add-hook 'window-size-change-functions #'ivy--window-size-changed nil t)
  2683. (let ((hook (ivy-alist-setting ivy-hooks-alist)))
  2684. (when (functionp hook)
  2685. (funcall hook))))
  2686. (defun ivy--input ()
  2687. "Return the current minibuffer input."
  2688. ;; assume one-line minibuffer input
  2689. (save-excursion
  2690. (goto-char (minibuffer-prompt-end))
  2691. (let ((inhibit-field-text-motion t))
  2692. (buffer-substring-no-properties
  2693. (point)
  2694. (line-end-position)))))
  2695. (defun ivy--minibuffer-cleanup ()
  2696. "Delete the displayed completion candidates."
  2697. (save-excursion
  2698. (goto-char (minibuffer-prompt-end))
  2699. (delete-region (line-end-position) (point-max))))
  2700. (defun ivy-cleanup-string (str)
  2701. "Destructively remove unwanted text properties from STR."
  2702. (ivy--remove-props str 'field))
  2703. (defvar ivy-set-prompt-text-properties-function
  2704. #'ivy-set-prompt-text-properties-default
  2705. "Function to set the text properties of the default ivy prompt.
  2706. Called with two arguments, PROMPT and PROPS, where PROMPT is the
  2707. string to be propertized and PROPS is a plist of default text
  2708. properties that may be applied to PROMPT. The function should
  2709. return the propertized PROMPT, which may be modified in-place.")
  2710. (defun ivy-set-prompt-text-properties-default (prompt props)
  2711. "Propertize (confirm) and (match required) parts of PROMPT.
  2712. PROPS is a plist of default text properties to apply to these
  2713. parts beyond their respective faces `ivy-confirm-face' and
  2714. `ivy-match-required-face'."
  2715. (dolist (pair '(("confirm" . ivy-confirm-face)
  2716. ("match required" . ivy-match-required-face)))
  2717. (let ((i (string-match-p (car pair) prompt)))
  2718. (when i
  2719. (add-text-properties i (+ i (length (car pair)))
  2720. `(face ,(cdr pair) ,@props)
  2721. prompt))))
  2722. prompt)
  2723. (defun ivy-prompt ()
  2724. "Return the current prompt."
  2725. (let* ((caller (ivy-state-caller ivy-last))
  2726. (fn (plist-get ivy--prompts-list caller)))
  2727. (if fn
  2728. (condition-case err
  2729. (funcall fn)
  2730. (wrong-number-of-arguments
  2731. (lwarn 'ivy :error "%s
  2732. Prompt function set via `ivy-set-prompt' for caller `%s'
  2733. should take no arguments."
  2734. (error-message-string err)
  2735. caller)
  2736. ;; Old behavior.
  2737. (funcall fn (ivy-state-prompt ivy-last))))
  2738. ivy--prompt)))
  2739. (defun ivy--break-lines (str width)
  2740. "Break each line in STR with newlines to fit into WIDTH columns."
  2741. (if (<= width 0)
  2742. str
  2743. (let (lines)
  2744. (dolist (line (split-string str "\n"))
  2745. (while (and line (> (string-width line) width))
  2746. (let ((prefix "") (extra 0))
  2747. (while (string-empty-p prefix)
  2748. ;; Grow `width' until it fits at least one char from `line'.
  2749. (setq prefix (truncate-string-to-width line (+ width extra)))
  2750. (setq extra (1+ extra)))
  2751. ;; Avoid introducing spurious newline if `prefix' and `line' are
  2752. ;; equal, i.e., if `line' couldn't be truncated to `width'.
  2753. (setq line (and (> (length line) (length prefix))
  2754. (substring line (length prefix))))
  2755. (push prefix lines)))
  2756. (when line (push line lines)))
  2757. (string-join (nreverse lines) "\n"))))
  2758. (defun ivy--insert-prompt ()
  2759. "Update the prompt according to `ivy--prompt'."
  2760. (when (setq ivy--prompt (ivy-prompt))
  2761. (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
  2762. counsel-find-symbol))
  2763. (setq ivy--prompt-extra ""))
  2764. (let (head tail)
  2765. (if (string-match "\\(.*?\\)\\(:? ?\\)\\'" ivy--prompt)
  2766. (progn
  2767. (setq head (match-string 1 ivy--prompt))
  2768. (setq tail (match-string 2 ivy--prompt)))
  2769. (setq head ivy--prompt)
  2770. (setq tail ""))
  2771. (let ((inhibit-read-only t)
  2772. (std-props '(front-sticky t rear-nonsticky t field t read-only t))
  2773. (n-str
  2774. (concat
  2775. (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
  2776. (> (minibuffer-depth) 1))
  2777. (format "[%d] " (minibuffer-depth))
  2778. "")
  2779. (concat
  2780. (if (string-match "%d.*%d" ivy-count-format)
  2781. (format head
  2782. (1+ ivy--index)
  2783. (or (and (ivy-state-dynamic-collection ivy-last)
  2784. ivy--full-length)
  2785. ivy--length))
  2786. (format head
  2787. (or (and (ivy-state-dynamic-collection ivy-last)
  2788. ivy--full-length)
  2789. ivy--length)))
  2790. ivy--prompt-extra
  2791. tail)))
  2792. (d-str (if ivy--directory
  2793. (abbreviate-file-name ivy--directory)
  2794. "")))
  2795. (save-excursion
  2796. (goto-char (point-min))
  2797. (delete-region (point-min) (minibuffer-prompt-end))
  2798. (let ((wid-n (string-width n-str))
  2799. (wid-d (string-width d-str))
  2800. (ww (window-width)))
  2801. (setq n-str
  2802. (cond ((> (+ wid-n wid-d) ww)
  2803. (concat n-str "\n" d-str "\n"))
  2804. ((> (+ wid-n wid-d (string-width ivy-text)) ww)
  2805. (concat n-str d-str "\n"))
  2806. (t
  2807. (concat n-str d-str)))))
  2808. (when ivy-pre-prompt-function
  2809. (setq n-str (concat (funcall ivy-pre-prompt-function) n-str)))
  2810. (when ivy-add-newline-after-prompt
  2811. (setq n-str (concat n-str "\n")))
  2812. (setq n-str (ivy--break-lines n-str (window-width)))
  2813. (set-text-properties 0 (length n-str)
  2814. `(face minibuffer-prompt ,@std-props)
  2815. n-str)
  2816. (setq n-str (funcall ivy-set-prompt-text-properties-function
  2817. n-str std-props))
  2818. (insert n-str))
  2819. ;; Mark prompt as selected if the user moves there or it is the only
  2820. ;; option left. Since the user input stays put, we have to manually
  2821. ;; remove the face as well.
  2822. (when ivy--use-selectable-prompt
  2823. (if (= ivy--index -1)
  2824. (add-face-text-property
  2825. (minibuffer-prompt-end) (line-end-position) 'ivy-prompt-match)
  2826. (remove-list-of-text-properties
  2827. (minibuffer-prompt-end) (line-end-position) '(face))))
  2828. ;; get out of the prompt area
  2829. (constrain-to-field nil (point-max))))))
  2830. (defun ivy--sort-maybe (collection)
  2831. "Sort COLLECTION if needed."
  2832. (let ((sort (ivy-state-sort ivy-last)))
  2833. (if (and sort
  2834. (or (functionp sort)
  2835. (functionp (setq sort (ivy--sort-function
  2836. (ivy-state-collection ivy-last))))))
  2837. (sort (copy-sequence collection) sort)
  2838. collection)))
  2839. (defcustom ivy-magic-slash-non-match-action 'ivy-magic-slash-non-match-cd-selected
  2840. "Action to take when a slash is added to the end of a non existing directory.
  2841. Possible choices are 'ivy-magic-slash-non-match-cd-selected,
  2842. 'ivy-magic-slash-non-match-create, or nil"
  2843. :type '(choice
  2844. (const :tag "Use currently selected directory"
  2845. ivy-magic-slash-non-match-cd-selected)
  2846. (const :tag "Create and use new directory"
  2847. ivy-magic-slash-non-match-create)
  2848. (const :tag "Do nothing"
  2849. nil)))
  2850. (defun ivy--create-and-cd (dir)
  2851. "When completing file names, create directory DIR and move there."
  2852. (make-directory dir)
  2853. (ivy--cd dir))
  2854. (defun ivy--magic-file-doubleslash-directory ()
  2855. "Return an appropriate directory for when two slashes are entered."
  2856. (let (remote)
  2857. (cond
  2858. ;; Windows
  2859. ;; ((string-match "\\`[[:alpha:]]:/" ivy--directory)
  2860. ;; (match-string 0 ivy--directory))
  2861. ;; Remote root if on remote
  2862. ((setq remote (file-remote-p ivy--directory))
  2863. (concat remote "/"))
  2864. ;; Local root
  2865. (t
  2866. "/"))))
  2867. (defun ivy--magic-file-slash ()
  2868. "Handle slash when completing file names."
  2869. (when (or (and (eq this-command #'self-insert-command)
  2870. (eolp))
  2871. (eq this-command #'ivy-partial-or-done))
  2872. (let ((canonical (expand-file-name ivy-text ivy--directory))
  2873. (magic (not (string= ivy-text "/"))))
  2874. (cond ((member ivy-text ivy--all-candidates)
  2875. (ivy--cd canonical))
  2876. ((and (eq system-type 'windows-nt) (string= ivy-text "//")))
  2877. ((string-suffix-p "//" ivy-text)
  2878. (ivy--cd
  2879. (ivy--magic-file-doubleslash-directory)))
  2880. ((string-match-p "\\`/ssh:" ivy-text)
  2881. (ivy--cd (file-name-directory ivy-text)))
  2882. ((string-match "[[:alpha:]]:/\\'" ivy-text)
  2883. (let ((drive-root (match-string 0 ivy-text)))
  2884. (when (file-exists-p drive-root)
  2885. (ivy--cd drive-root))))
  2886. ((and magic (file-directory-p canonical))
  2887. (ivy--cd canonical))
  2888. ((let ((default-directory ivy--directory))
  2889. (and (or (> ivy--index 0)
  2890. (= ivy--length 1)
  2891. magic)
  2892. (not (ivy--prompt-selected-p))
  2893. (not (equal (ivy-state-current ivy-last) ""))
  2894. (file-directory-p (ivy-state-current ivy-last))
  2895. (or (eq ivy-magic-slash-non-match-action
  2896. 'ivy-magic-slash-non-match-cd-selected)
  2897. (eq this-command #'ivy-partial-or-done))))
  2898. (ivy--cd
  2899. (expand-file-name (ivy-state-current ivy-last) ivy--directory)))
  2900. ((and (eq ivy-magic-slash-non-match-action
  2901. 'ivy-magic-slash-non-match-create)
  2902. magic)
  2903. (ivy--create-and-cd canonical))))))
  2904. (defun ivy-magic-read-file-env ()
  2905. "If reading filename, jump to environment variable location."
  2906. (interactive)
  2907. (if (and ivy--directory
  2908. (equal ivy-text ""))
  2909. (let* ((cands (cl-loop for pair in process-environment
  2910. for (var val) = (split-string pair "=" t)
  2911. if (and val (not (equal "" val)))
  2912. if (file-exists-p
  2913. (if (file-name-absolute-p val)
  2914. val
  2915. (setq val
  2916. (expand-file-name val ivy--directory))))
  2917. collect (cons var val)))
  2918. (enable-recursive-minibuffers t)
  2919. (x (ivy-read "Env: " cands))
  2920. (path (cdr (assoc x cands))))
  2921. (insert (if (file-accessible-directory-p path)
  2922. (file-name-as-directory path)
  2923. path))
  2924. (ivy--cd-maybe))
  2925. (insert last-input-event)))
  2926. (defun ivy-make-magic-action (caller key)
  2927. "Return a command that does the equivalent of `ivy-read-action' and KEY.
  2928. This happens only when the input is empty.
  2929. The intention is to bind the result to keys that are typically
  2930. bound to `self-insert-command'."
  2931. (let* ((alist (assoc key
  2932. (plist-get
  2933. ivy--actions-list
  2934. caller)))
  2935. (doc (format "%s (`%S')"
  2936. (nth 2 alist)
  2937. (nth 1 alist))))
  2938. `(lambda (&optional arg)
  2939. ,doc
  2940. (interactive "p")
  2941. (if (string= "" ivy-text)
  2942. (execute-kbd-macro
  2943. (kbd ,(concat "M-o " key)))
  2944. (self-insert-command arg)))))
  2945. (defcustom ivy-magic-tilde t
  2946. "When non-nil, ~ will move home when selecting files.
  2947. Otherwise, ~/ will move home."
  2948. :type 'boolean)
  2949. (defcustom ivy-dynamic-exhibit-delay-ms 0
  2950. "Delay in ms before dynamic collections are refreshed"
  2951. :type 'integer)
  2952. (defvar ivy--exhibit-timer nil)
  2953. (defun ivy--queue-exhibit ()
  2954. "Insert Ivy completions display, possibly after a timeout for
  2955. dynamic collections.
  2956. Should be run via minibuffer `post-command-hook'."
  2957. (if (and (> ivy-dynamic-exhibit-delay-ms 0)
  2958. (ivy-state-dynamic-collection ivy-last))
  2959. (progn
  2960. (when ivy--exhibit-timer (cancel-timer ivy--exhibit-timer))
  2961. (setq ivy--exhibit-timer
  2962. (run-with-timer
  2963. (/ ivy-dynamic-exhibit-delay-ms 1000.0)
  2964. nil
  2965. 'ivy--exhibit)))
  2966. (ivy--exhibit)))
  2967. (defalias 'ivy--file-local-name
  2968. (if (fboundp 'file-local-name)
  2969. #'file-local-name
  2970. (lambda (file)
  2971. (or (file-remote-p file 'localname) file)))
  2972. "Compatibility shim for `file-local-name'.
  2973. The function was added in Emacs 26.1.")
  2974. (defun ivy--magic-tilde-directory (dir)
  2975. "Return an appropriate home for DIR for when ~ or ~/ are entered."
  2976. (file-name-as-directory
  2977. (expand-file-name
  2978. (let* ((home (expand-file-name (concat (file-remote-p dir) "~/")))
  2979. (dir-path (ivy--file-local-name dir))
  2980. (home-path (ivy--file-local-name home)))
  2981. (if (string= dir-path home-path)
  2982. "~"
  2983. home)))))
  2984. (defvar ivy--minibuffer-metadata nil)
  2985. (defun ivy-update-candidates (cands)
  2986. (let ((ivy--minibuffer-metadata
  2987. (unless (ivy-state-dynamic-collection ivy-last)
  2988. (completion-metadata "" minibuffer-completion-table
  2989. minibuffer-completion-predicate))))
  2990. (ivy--insert-minibuffer
  2991. (ivy--format
  2992. (setq ivy--all-candidates cands)))))
  2993. (defun ivy--exhibit ()
  2994. "Insert Ivy completions display.
  2995. Should be run via minibuffer `post-command-hook'."
  2996. (when (memq 'ivy--queue-exhibit post-command-hook)
  2997. (let ((inhibit-field-text-motion nil))
  2998. (constrain-to-field nil (point-max)))
  2999. (ivy-set-text (ivy--input))
  3000. (let ((new-minibuffer (ivy--update-minibuffer)))
  3001. (when new-minibuffer
  3002. (ivy--insert-minibuffer new-minibuffer)))
  3003. t))
  3004. (defun ivy--dynamic-collection-cands (input)
  3005. (let ((coll (funcall (ivy-state-collection ivy-last) input)))
  3006. (if (listp coll)
  3007. (mapcar (lambda (x) (if (consp x) (car x) x)) coll)
  3008. coll)))
  3009. (defun ivy--update-minibuffer ()
  3010. (prog1
  3011. (if (ivy-state-dynamic-collection ivy-last)
  3012. ;; while-no-input would cause annoying
  3013. ;; "Waiting for process to die...done" message interruptions
  3014. (let ((inhibit-message t)
  3015. coll in-progress)
  3016. (unless (or (equal ivy--old-text ivy-text)
  3017. (eq this-command 'ivy-resume))
  3018. (while-no-input
  3019. (setq coll (ivy--dynamic-collection-cands ivy-text))
  3020. (when (eq coll 0)
  3021. (setq coll nil)
  3022. (setq ivy--old-re nil)
  3023. (setq in-progress t))
  3024. (setq ivy--all-candidates (ivy--sort-maybe coll))))
  3025. (when (eq ivy--all-candidates 0)
  3026. (setq ivy--all-candidates nil)
  3027. (setq ivy--old-re nil)
  3028. (setq in-progress t))
  3029. (when (or ivy--all-candidates
  3030. (and (not (get-process " *counsel*"))
  3031. (not in-progress)))
  3032. (ivy--set-index-dynamic-collection)
  3033. (ivy--format ivy--all-candidates)))
  3034. (cond (ivy--directory
  3035. (cond ((or (string= "~/" ivy-text)
  3036. (and (string= "~" ivy-text)
  3037. ivy-magic-tilde))
  3038. (ivy--cd (ivy--magic-tilde-directory ivy--directory)))
  3039. ((string-match "/\\'" ivy-text)
  3040. (ivy--magic-file-slash))))
  3041. ((eq (ivy-state-collection ivy-last) #'internal-complete-buffer)
  3042. (when (or (and (string-match "\\` " ivy-text)
  3043. (not (string-match "\\` " ivy--old-text)))
  3044. (and (string-match "\\` " ivy--old-text)
  3045. (not (string-match "\\` " ivy-text))))
  3046. (setq ivy--all-candidates
  3047. (if (= (string-to-char ivy-text) ?\s)
  3048. (ivy--buffer-list " ")
  3049. (ivy--buffer-list "" ivy-use-virtual-buffers)))
  3050. (setq ivy--old-re nil))))
  3051. (with-current-buffer (ivy-state-buffer ivy-last)
  3052. (ivy--format
  3053. (ivy--filter ivy-text ivy--all-candidates))))
  3054. (setq ivy--old-text ivy-text)))
  3055. (defun ivy-display-function-fallback (str)
  3056. (let ((buffer-undo-list t))
  3057. (save-excursion
  3058. (forward-line 1)
  3059. (insert str))))
  3060. (defun ivy--insert-minibuffer (text)
  3061. "Insert TEXT into minibuffer with appropriate cleanup."
  3062. (let ((resize-mini-windows nil)
  3063. (update-fn (ivy-state-update-fn ivy-last))
  3064. (old-mark (marker-position (mark-marker)))
  3065. (win (active-minibuffer-window))
  3066. deactivate-mark)
  3067. (when win
  3068. (with-selected-window win
  3069. (ivy--minibuffer-cleanup)
  3070. (when update-fn
  3071. (funcall update-fn))
  3072. (ivy--insert-prompt)
  3073. ;; Do nothing if while-no-input was aborted.
  3074. (when (stringp text)
  3075. (if ivy--display-function
  3076. (funcall ivy--display-function text)
  3077. (ivy-display-function-fallback text)))
  3078. (ivy--resize-minibuffer-to-fit)
  3079. ;; prevent region growing due to text remove/add
  3080. (when (region-active-p)
  3081. (set-mark old-mark))))))
  3082. (defvar ivy-auto-shrink-minibuffer nil
  3083. "When non-nil and the height < `ivy-height', auto-shrink the minibuffer.")
  3084. (make-obsolete-variable 'ivy-auto-shrink-minibuffer
  3085. 'ivy-auto-shrink-minibuffer-alist
  3086. "<2020-04-28 Tue>")
  3087. (defcustom ivy-auto-shrink-minibuffer-alist nil
  3088. "An alist to configure auto-shrinking of the minibuffer.
  3089. Each key is a caller symbol. When the value is non-nil, and the
  3090. height < `ivy-height', auto-shrink the minibuffer."
  3091. :type '(alist
  3092. :key-type symbol
  3093. :value-type boolean))
  3094. (defun ivy--do-shrink-window ()
  3095. (let ((h (save-excursion
  3096. (goto-char (minibuffer-prompt-end))
  3097. (let ((inhibit-field-text-motion t))
  3098. (line-number-at-pos)))))
  3099. (shrink-window (-
  3100. (/ (window-body-height nil t)
  3101. (frame-char-height))
  3102. ivy--length h))))
  3103. (defun ivy--resize-minibuffer-to-fit ()
  3104. "Resize the minibuffer window size to fit the text in the minibuffer."
  3105. (unless (or (frame-root-window-p (minibuffer-window))
  3106. (memq this-command '(ivy-read-action
  3107. ivy-dispatching-done
  3108. ivy-dispatching-call)))
  3109. (with-selected-window (minibuffer-window)
  3110. (if (fboundp 'window-text-pixel-size)
  3111. (let ((text-height (cdr (window-text-pixel-size)))
  3112. (body-height (window-body-height nil t)))
  3113. (cond ((> text-height body-height)
  3114. ;; Note: the size increment needs to be at least
  3115. ;; frame-char-height, otherwise resizing won't do
  3116. ;; anything.
  3117. (let ((delta (max (- text-height body-height)
  3118. (frame-char-height))))
  3119. (window-resize nil delta nil t t)))
  3120. ((and (or ivy-auto-shrink-minibuffer
  3121. (ivy-alist-setting
  3122. ivy-auto-shrink-minibuffer-alist))
  3123. (< ivy--length ivy-height))
  3124. (ivy--do-shrink-window))))
  3125. (let ((text-height (count-screen-lines))
  3126. (body-height (window-body-height)))
  3127. (when (> text-height body-height)
  3128. (window-resize nil (- text-height body-height) nil t)))))))
  3129. (defun ivy--window-size-changed (&rest _)
  3130. "Resize ivy window to fit with current frame's size."
  3131. (when ivy-mode
  3132. (ivy--resize-minibuffer-to-fit)))
  3133. (defun ivy--add-face (str face)
  3134. "Propertize STR with FACE."
  3135. (let ((len (length str)))
  3136. (condition-case nil
  3137. (progn
  3138. (colir-blend-face-background 0 len face str)
  3139. (let ((foreground (face-foreground face)))
  3140. (when foreground
  3141. (add-face-text-property
  3142. 0 len (list :foreground foreground) nil str))))
  3143. (error
  3144. (ignore-errors
  3145. (font-lock-append-text-property 0 len 'face face str)))))
  3146. str)
  3147. (declare-function flx-make-string-cache "ext:flx")
  3148. (declare-function flx-score "ext:flx")
  3149. (defvar ivy--flx-cache nil)
  3150. (with-eval-after-load 'flx
  3151. (setq ivy--flx-cache (flx-make-string-cache)))
  3152. (defun ivy-toggle-case-fold ()
  3153. "Toggle `case-fold-search' for Ivy operations.
  3154. Instead of modifying `case-fold-search' directly, this command
  3155. toggles `ivy-case-fold-search', which can take on more values
  3156. than the former, between nil and either `auto' or t. See
  3157. `ivy-case-fold-search-default' for the meaning of these values.
  3158. In any Ivy completion session, the case folding starts with
  3159. `ivy-case-fold-search-default'."
  3160. (interactive)
  3161. (setq ivy-case-fold-search
  3162. (and (not ivy-case-fold-search)
  3163. (or ivy-case-fold-search-default 'auto)))
  3164. ;; Reset cache so that the candidate list updates.
  3165. (setq ivy--old-re nil))
  3166. (defun ivy--re-filter (re candidates &optional mkpred)
  3167. "Return all RE matching CANDIDATES.
  3168. RE is a list of cons cells, with a regexp car and a boolean cdr.
  3169. When the cdr is t, the car must match.
  3170. Otherwise, the car must not match."
  3171. (if (equal re "")
  3172. candidates
  3173. (ignore-errors
  3174. (dolist (re (if (stringp re) (list (cons re t)) re))
  3175. (let* ((re-str (car re))
  3176. (pred
  3177. (if mkpred
  3178. (funcall mkpred re-str)
  3179. (lambda (x) (string-match-p re-str x)))))
  3180. (setq candidates
  3181. (cl-remove nil candidates
  3182. (if (cdr re) :if-not :if)
  3183. pred))))
  3184. candidates)))
  3185. (defun ivy--filter (name candidates)
  3186. "Return all items that match NAME in CANDIDATES.
  3187. CANDIDATES are assumed to be static."
  3188. (let ((re (funcall ivy--regex-function name)))
  3189. (if (and
  3190. ivy--old-re
  3191. ivy--old-cands
  3192. (equal re ivy--old-re))
  3193. ;; quick caching for "C-n", "C-p" etc.
  3194. ivy--old-cands
  3195. (let* ((re-str (ivy-re-to-str re))
  3196. (matcher (ivy-state-matcher ivy-last))
  3197. (case-fold-search (ivy--case-fold-p name))
  3198. (cands (cond
  3199. (matcher
  3200. (funcall matcher re candidates))
  3201. ((and ivy--old-re
  3202. (stringp re)
  3203. (stringp ivy--old-re)
  3204. (not (string-match-p "\\\\" ivy--old-re))
  3205. (not (equal ivy--old-re ""))
  3206. (memq (cl-search
  3207. (if (string-match-p "\\\\)\\'" ivy--old-re)
  3208. (substring ivy--old-re 0 -2)
  3209. ivy--old-re)
  3210. re)
  3211. '(0 2))
  3212. ivy--old-cands
  3213. (ivy--re-filter re ivy--old-cands)))
  3214. (t
  3215. (ivy--re-filter re candidates)))))
  3216. (if (memq (cdr (assq (ivy-state-caller ivy-last)
  3217. ivy-index-functions-alist))
  3218. '(ivy-recompute-index-swiper
  3219. ivy-recompute-index-swiper-async
  3220. ivy-recompute-index-swiper-async-backward
  3221. ivy-recompute-index-swiper-backward))
  3222. (progn
  3223. (ivy--recompute-index re-str cands)
  3224. (setq ivy--old-cands (ivy--sort name cands)))
  3225. (setq ivy--old-cands (ivy--sort name cands))
  3226. (ivy--recompute-index re-str ivy--old-cands))
  3227. (setq ivy--old-re re)
  3228. ivy--old-cands))))
  3229. (defun ivy--set-candidates (x)
  3230. "Update `ivy--all-candidates' with X."
  3231. (let (res
  3232. ;; (ivy--recompute-index-inhibit t)
  3233. )
  3234. (dolist (source ivy--extra-candidates)
  3235. (if (equal source '(original-source))
  3236. (if (null res)
  3237. (setq res x)
  3238. (setq res (append x res)))
  3239. (setq ivy--old-re nil)
  3240. (setq res (append
  3241. (ivy--filter ivy-text (cadr source))
  3242. res))))
  3243. (setq ivy--all-candidates
  3244. (if (cdr ivy--extra-candidates)
  3245. (delete-dups res)
  3246. res))))
  3247. (defun ivy--shorter-matches-first (_name cands)
  3248. "Sort CANDS according to their length."
  3249. (if (nthcdr ivy-sort-max-size cands)
  3250. cands
  3251. (cl-sort (copy-sequence cands) #'< :key #'length)))
  3252. (defcustom ivy-sort-matches-functions-alist
  3253. '((t . nil)
  3254. (ivy-completion-in-region . ivy--shorter-matches-first)
  3255. (ivy-switch-buffer . ivy-sort-function-buffer))
  3256. "An alist of functions for sorting matching candidates.
  3257. Unlike `ivy-sort-functions-alist', which is used to sort the
  3258. whole collection only once, this alist of functions are used to
  3259. sort only matching candidates after each change in input.
  3260. The alist KEY is either a collection function or t to match
  3261. previously unmatched collection functions.
  3262. The alist VAL is a sorting function with the signature of
  3263. `ivy--prefix-sort'."
  3264. :type '(alist
  3265. :key-type (choice
  3266. (const :tag "Fall-through" t)
  3267. (symbol :tag "Collection"))
  3268. :value-type
  3269. (choice
  3270. (const :tag "Don't sort" nil)
  3271. (const :tag "Put prefix matches ahead" ivy--prefix-sort)
  3272. (function :tag "Custom sort function"))))
  3273. (defun ivy--sort-files-by-date (_name candidates)
  3274. "Re-sort CANDIDATES according to file modification date."
  3275. (let ((default-directory ivy--directory))
  3276. (sort (copy-sequence candidates) #'file-newer-than-file-p)))
  3277. (defvar ivy--flx-featurep (require 'flx nil 'noerror))
  3278. (defun ivy--sort (name candidates)
  3279. "Re-sort candidates by NAME.
  3280. All CANDIDATES are assumed to match NAME."
  3281. (let (fun)
  3282. (cond ((setq fun (ivy-alist-setting ivy-sort-matches-functions-alist))
  3283. (funcall fun name candidates))
  3284. ((and ivy--flx-featurep
  3285. (eq ivy--regex-function 'ivy--regex-fuzzy))
  3286. (ivy--flx-sort name candidates))
  3287. (t
  3288. candidates))))
  3289. (defun ivy--prefix-sort (name candidates)
  3290. "Re-sort candidates by NAME.
  3291. All CANDIDATES are assumed to match NAME.
  3292. Prefix matches to NAME are put ahead of the list."
  3293. (if (or (string= name "")
  3294. (= (aref name 0) ?^))
  3295. candidates
  3296. (let ((re-prefix (concat "\\`" (funcall ivy--regex-function name)))
  3297. res-prefix
  3298. res-noprefix)
  3299. (dolist (s candidates)
  3300. (if (string-match-p re-prefix s)
  3301. (push s res-prefix)
  3302. (push s res-noprefix)))
  3303. (nconc
  3304. (nreverse res-prefix)
  3305. (nreverse res-noprefix)))))
  3306. (defvar ivy--virtual-buffers nil
  3307. "Store the virtual buffers alist.")
  3308. (defun ivy-re-to-str (re)
  3309. "Transform RE to a string.
  3310. Functions like `ivy--regex-ignore-order' return a cons list.
  3311. This function extracts a string from the cons list."
  3312. (if (consp re) (caar re) re))
  3313. (defun ivy-sort-function-buffer (name candidates)
  3314. "Re-sort candidates by NAME.
  3315. CANDIDATES is a list of buffer names each containing NAME.
  3316. Sort open buffers before virtual buffers, and prefix matches
  3317. before substring matches."
  3318. (if (or (string= name "")
  3319. (= (aref name 0) ?^))
  3320. candidates
  3321. (let* ((base-re (ivy-re-to-str (funcall ivy--regex-function name)))
  3322. (re-star-prefix (concat "\\`\\*" base-re))
  3323. (re-prefix (concat "\\`" base-re))
  3324. res-prefix
  3325. res-noprefix
  3326. res-virtual-prefix
  3327. res-virtual-noprefix)
  3328. (dolist (s candidates)
  3329. (cond
  3330. ((and (assoc s ivy--virtual-buffers)
  3331. (or (string-match-p re-star-prefix s)
  3332. (string-match-p re-prefix s)))
  3333. (push s res-virtual-prefix))
  3334. ((assoc s ivy--virtual-buffers)
  3335. (push s res-virtual-noprefix))
  3336. ((or (string-match-p re-star-prefix s)
  3337. (string-match-p re-prefix s))
  3338. (push s res-prefix))
  3339. (t
  3340. (push s res-noprefix))))
  3341. (nconc
  3342. (nreverse res-prefix)
  3343. (nreverse res-noprefix)
  3344. (nreverse res-virtual-prefix)
  3345. (nreverse res-virtual-noprefix)))))
  3346. (defvar ivy-flx-limit 200
  3347. "Used to conditionally turn off flx sorting.
  3348. When the amount of matching candidates exceeds this limit, then
  3349. no sorting is done.")
  3350. (defvar ivy--recompute-index-inhibit nil
  3351. "When non-nil, `ivy--recompute-index' is a no-op.")
  3352. (defun ivy--recompute-index (re-str cands)
  3353. "Recompute index of selected candidate matching RE-STR.
  3354. CANDS are the current candidates."
  3355. (let ((caller (ivy-state-caller ivy-last))
  3356. (func (or (ivy-alist-setting ivy-index-functions-alist)
  3357. #'ivy-recompute-index-zero))
  3358. (case-fold-search (ivy--case-fold-p re-str))
  3359. (preselect (ivy-state-preselect ivy-last))
  3360. (current (ivy-state-current ivy-last))
  3361. (empty (string= re-str "")))
  3362. (unless (or (memq this-command '(ivy-resume ivy-partial-or-done))
  3363. ivy--recompute-index-inhibit)
  3364. (let ((index (cond
  3365. ((or empty (string= re-str "^"))
  3366. (ivy--preselect-index preselect cands))
  3367. ((and (> (length cands) 10000) (eq func #'ivy-recompute-index-zero))
  3368. 0)
  3369. ((cl-position (string-remove-prefix "^" re-str)
  3370. cands
  3371. :test #'ivy--case-fold-string=))
  3372. ((and (ivy--completing-fname-p)
  3373. (cl-position (concat re-str "/")
  3374. cands
  3375. :test #'ivy--case-fold-string=)))
  3376. ((and (eq caller 'ivy-switch-buffer)
  3377. (not empty))
  3378. (or (cl-position current cands :test #'string=)
  3379. 0))
  3380. ((and (not empty)
  3381. (not (eq caller 'swiper))
  3382. (not (and ivy--flx-featurep
  3383. (eq ivy--regex-function 'ivy--regex-fuzzy)
  3384. ;; Limit to configured number of candidates
  3385. (null (nthcdr ivy-flx-limit cands))))
  3386. ;; If there was a preselected candidate, don't try to
  3387. ;; keep it selected even if the regexp still matches it.
  3388. ;; See issue #1563. See also `ivy--preselect-index',
  3389. ;; which this logic roughly mirrors.
  3390. (not (or
  3391. (and (integerp preselect)
  3392. (= ivy--index preselect))
  3393. (equal current preselect)
  3394. (and (ivy--regex-p preselect)
  3395. (stringp current)
  3396. (string-match-p preselect current))))
  3397. ivy--old-cands
  3398. (cl-position current cands :test #'equal)))
  3399. ((funcall func re-str cands))
  3400. (t 0))))
  3401. (ivy-set-index index)))))
  3402. (defun ivy-recompute-index-swiper (_re-str cands)
  3403. "Recompute index of selected candidate when using `swiper'.
  3404. CANDS are the current candidates."
  3405. (condition-case nil
  3406. (let ((tail (nthcdr ivy--index ivy--old-cands))
  3407. idx)
  3408. (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
  3409. (progn
  3410. (while (and tail (null idx))
  3411. ;; Compare with eq to handle equal duplicates in cands
  3412. (setq idx (cl-position (pop tail) cands)))
  3413. (or
  3414. idx
  3415. (1- (length cands))))
  3416. (if ivy--old-cands
  3417. ivy--index
  3418. ;; already in ivy-state-buffer
  3419. (let ((n (line-number-at-pos))
  3420. (res 0)
  3421. (i 0))
  3422. (dolist (c cands)
  3423. (when (eq n (get-text-property 0 'swiper-line-number c))
  3424. (setq res i))
  3425. (cl-incf i))
  3426. res))))
  3427. (error 0)))
  3428. (defun ivy-recompute-index-swiper-backward (re-str cands)
  3429. "Recompute index of selected candidate when using `swiper-backward'.
  3430. CANDS are the current candidates."
  3431. (let ((idx (ivy-recompute-index-swiper re-str cands)))
  3432. (if (or (= idx -1)
  3433. (<= (get-text-property 0 'swiper-line-number (nth idx cands))
  3434. (line-number-at-pos)))
  3435. idx
  3436. (- idx 1))))
  3437. (defun ivy-recompute-index-swiper-async (_re-str cands)
  3438. "Recompute index of selected candidate when using `swiper' asynchronously.
  3439. CANDS are the current candidates."
  3440. (if (null ivy--old-cands)
  3441. (let ((ln (with-ivy-window
  3442. (line-number-at-pos))))
  3443. (or
  3444. ;; closest to current line going forwards
  3445. (cl-position-if (lambda (x)
  3446. (>= (string-to-number x) ln))
  3447. cands)
  3448. ;; closest to current line going backwards
  3449. (1- (length cands))))
  3450. (let ((tail (nthcdr ivy--index ivy--old-cands))
  3451. idx)
  3452. (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
  3453. (progn
  3454. (while (and tail (null idx))
  3455. ;; Compare with `equal', since the collection is re-created
  3456. ;; each time with `split-string'
  3457. (setq idx (cl-position (pop tail) cands :test #'equal)))
  3458. (or idx 0))
  3459. ivy--index))))
  3460. (defun ivy-recompute-index-swiper-async-backward (re-str cands)
  3461. "Recompute index of selected candidate when using `swiper-backward'
  3462. asynchronously. CANDS are the current candidates."
  3463. (if (= (length cands) 0)
  3464. 0
  3465. (let ((idx (ivy-recompute-index-swiper-async re-str cands)))
  3466. (if
  3467. (<= (string-to-number (nth idx cands))
  3468. (with-ivy-window (line-number-at-pos)))
  3469. idx
  3470. (- idx 1)))))
  3471. (defun ivy-recompute-index-zero (_re-str _cands)
  3472. "Recompute index of selected candidate.
  3473. This function serves as a fallback when nothing else is available."
  3474. 0)
  3475. (defcustom ivy-minibuffer-faces
  3476. '(ivy-minibuffer-match-face-1
  3477. ivy-minibuffer-match-face-2
  3478. ivy-minibuffer-match-face-3
  3479. ivy-minibuffer-match-face-4)
  3480. "List of `ivy' faces for minibuffer group matches."
  3481. :type '(repeat :tag "Faces"
  3482. (choice
  3483. (const ivy-minibuffer-match-face-1)
  3484. (const ivy-minibuffer-match-face-2)
  3485. (const ivy-minibuffer-match-face-3)
  3486. (const ivy-minibuffer-match-face-4)
  3487. (face :tag "Other face"))))
  3488. (defun ivy--minibuffer-face (n)
  3489. "Return Nth face from `ivy-minibuffer-faces'.
  3490. N wraps around, but skips the first element of the list."
  3491. (let ((tail (cdr ivy-minibuffer-faces)))
  3492. (nth (mod (+ n 2) (length tail)) tail)))
  3493. (defun ivy--flx-propertize (x)
  3494. "X is (cons (flx-score STR ...) STR)."
  3495. (let ((str (copy-sequence (cdr x)))
  3496. (i 0)
  3497. (last-j -2))
  3498. (dolist (j (cdar x))
  3499. (unless (eq j (1+ last-j))
  3500. (cl-incf i))
  3501. (setq last-j j)
  3502. (add-face-text-property j (1+ j) (ivy--minibuffer-face i) nil str))
  3503. str))
  3504. (defun ivy--flx-sort (name cands)
  3505. "Sort according to closeness to string NAME the string list CANDS."
  3506. (condition-case nil
  3507. (let* ((bolp (= (string-to-char name) ?^))
  3508. ;; An optimized regex for fuzzy matching
  3509. ;; "abc" → "^[^a]*a[^b]*b[^c]*c"
  3510. (fuzzy-regex (concat "\\`"
  3511. (and bolp (regexp-quote (substring name 1 2)))
  3512. (mapconcat
  3513. (lambda (x)
  3514. (setq x (char-to-string x))
  3515. (concat "[^" x "]*" (regexp-quote x)))
  3516. (if bolp (substring name 2) name)
  3517. "")))
  3518. ;; Strip off the leading "^" for flx matching
  3519. (flx-name (if bolp (substring name 1) name))
  3520. cands-left
  3521. cands-to-sort)
  3522. ;; Filter out non-matching candidates
  3523. (dolist (cand cands)
  3524. (when (string-match-p fuzzy-regex cand)
  3525. (push cand cands-left)))
  3526. ;; pre-sort the candidates by length before partitioning
  3527. (setq cands-left (cl-sort cands-left #'< :key #'length))
  3528. ;; partition the candidates into sorted and unsorted groups
  3529. (dotimes (_ (min (length cands-left) ivy-flx-limit))
  3530. (push (pop cands-left) cands-to-sort))
  3531. (nconc
  3532. ;; Compute all of the flx scores in one pass and sort
  3533. (mapcar #'car
  3534. (sort (mapcar
  3535. (lambda (cand)
  3536. (cons cand
  3537. (car (flx-score cand flx-name ivy--flx-cache))))
  3538. cands-to-sort)
  3539. (lambda (c1 c2)
  3540. ;; Break ties by length
  3541. (if (/= (cdr c1) (cdr c2))
  3542. (> (cdr c1)
  3543. (cdr c2))
  3544. (< (length (car c1))
  3545. (length (car c2)))))))
  3546. ;; Add the unsorted candidates
  3547. cands-left))
  3548. (error cands)))
  3549. (defun ivy--truncate-string (str width)
  3550. "Truncate STR to WIDTH."
  3551. (truncate-string-to-width str width nil nil t))
  3552. (defun ivy--format-function-generic (selected-fn other-fn cands separator)
  3553. "Transform candidates into a string for minibuffer.
  3554. SELECTED-FN is called for the selected candidate, OTHER-FN for the others.
  3555. Both functions take one string argument each. CANDS is a list of candidates
  3556. and SEPARATOR is used to join them."
  3557. (let ((i -1))
  3558. (mapconcat
  3559. (lambda (str)
  3560. (let ((curr (eq (cl-incf i) ivy--window-index)))
  3561. (if curr
  3562. (funcall selected-fn str)
  3563. (funcall other-fn str))))
  3564. cands
  3565. separator)))
  3566. (defun ivy-format-function-default (cands)
  3567. "Transform CANDS into a string for minibuffer."
  3568. (ivy--format-function-generic
  3569. (lambda (str)
  3570. (ivy--add-face str 'ivy-current-match))
  3571. #'identity
  3572. cands
  3573. "\n"))
  3574. (defun ivy-format-function-arrow (cands)
  3575. "Transform CANDS into a string for minibuffer."
  3576. (ivy--format-function-generic
  3577. (lambda (str)
  3578. (concat "> " (ivy--add-face str 'ivy-current-match)))
  3579. (lambda (str)
  3580. (concat " " str))
  3581. cands
  3582. "\n"))
  3583. (defun ivy-format-function-line (cands)
  3584. "Transform CANDS into a string for minibuffer.
  3585. Note that since Emacs 27, `ivy-current-match' needs to have :extend t attribute.
  3586. It has it by default, but the current theme also needs to set it."
  3587. (ivy--format-function-generic
  3588. (lambda (str)
  3589. (ivy--add-face (concat str "\n") 'ivy-current-match))
  3590. (lambda (str)
  3591. (concat str "\n"))
  3592. cands
  3593. ""))
  3594. (defun ivy--highlight-ignore-order (str)
  3595. "Highlight STR, using the ignore-order method."
  3596. (when (consp ivy--old-re)
  3597. (let ((i 1))
  3598. (dolist (re ivy--old-re)
  3599. (when (string-match (car re) str)
  3600. (add-face-text-property
  3601. (match-beginning 0) (match-end 0)
  3602. (ivy--minibuffer-face i)
  3603. nil str))
  3604. (cl-incf i))))
  3605. str)
  3606. (defun ivy--highlight-fuzzy (str)
  3607. "Highlight STR, using the fuzzy method."
  3608. (if (and ivy--flx-featurep
  3609. (eq (ivy-alist-setting ivy-re-builders-alist) 'ivy--regex-fuzzy))
  3610. (let ((flx-name (string-remove-prefix "^" ivy-text)))
  3611. (ivy--flx-propertize
  3612. (cons (flx-score str flx-name ivy--flx-cache) str)))
  3613. (ivy--highlight-default str)))
  3614. (defcustom ivy-use-group-face-if-no-groups t
  3615. "If t, and the expression has no subgroups, highlight whole match as a group.
  3616. It will then use the second face (first of the \"group\" faces)
  3617. of `ivy-minibuffer-faces'. Otherwise, always use the first face
  3618. in this case."
  3619. :type 'boolean)
  3620. (defun ivy--highlight-default (str)
  3621. "Highlight STR, using the default method."
  3622. (unless ivy--old-re
  3623. (setq ivy--old-re ivy-regex))
  3624. (let ((regexps
  3625. (if (listp ivy--old-re)
  3626. (mapcar #'car (cl-remove-if-not #'cdr ivy--old-re))
  3627. (list ivy--old-re)))
  3628. start)
  3629. (dolist (re regexps)
  3630. (ignore-errors
  3631. (while (and (string-match re str start)
  3632. (> (- (match-end 0) (match-beginning 0)) 0))
  3633. (setq start (match-end 0))
  3634. (let ((i 0)
  3635. (n 0)
  3636. prev)
  3637. (while (<= i ivy--subexps)
  3638. (let ((beg (match-beginning i))
  3639. (end (match-end i)))
  3640. (when (and beg end)
  3641. (unless (or (and prev (= prev beg))
  3642. (zerop i))
  3643. (cl-incf n))
  3644. (let ((face
  3645. (cond ((and ivy-use-group-face-if-no-groups
  3646. (zerop ivy--subexps))
  3647. (cadr ivy-minibuffer-faces))
  3648. ((zerop i)
  3649. (car ivy-minibuffer-faces))
  3650. (t
  3651. (ivy--minibuffer-face n)))))
  3652. (add-face-text-property beg end face nil str))
  3653. (unless (zerop i)
  3654. (setq prev end))))
  3655. (cl-incf i)))))))
  3656. str)
  3657. (defun ivy--format-minibuffer-line (str)
  3658. "Format line STR for use in minibuffer."
  3659. (let* ((str (ivy-cleanup-string (copy-sequence str)))
  3660. (str (if (eq ivy-display-style 'fancy)
  3661. (if (memq (ivy-state-caller ivy-last)
  3662. ivy-highlight-grep-commands)
  3663. (let* ((start (if (string-match "\\`[^:]+:\\(?:[^:]+:\\)?" str)
  3664. (match-end 0) 0))
  3665. (file (substring str 0 start))
  3666. (match (substring str start)))
  3667. (concat file (funcall ivy--highlight-function match)))
  3668. (funcall ivy--highlight-function str))
  3669. str))
  3670. (olen (length str))
  3671. (annot (or (completion-metadata-get ivy--minibuffer-metadata 'annotation-function)
  3672. (plist-get completion-extra-properties :annotation-function))))
  3673. (add-text-properties
  3674. 0 olen
  3675. '(mouse-face
  3676. ivy-minibuffer-match-highlight
  3677. help-echo
  3678. (format
  3679. (if tooltip-mode
  3680. "mouse-1: %s\nmouse-3: %s"
  3681. "mouse-1: %s mouse-3: %s")
  3682. ivy-mouse-1-tooltip ivy-mouse-3-tooltip))
  3683. str)
  3684. (when annot
  3685. (setq str (concat str (funcall annot str)))
  3686. (add-face-text-property
  3687. olen (length str) 'ivy-completions-annotations nil str))
  3688. str))
  3689. (defun ivy-read-file-transformer (str)
  3690. "Transform candidate STR when reading files."
  3691. (if (ivy--dirname-p str)
  3692. (propertize str 'face 'ivy-subdir)
  3693. str))
  3694. (defun ivy--minibuffer-index-bounds (idx len wnd-len)
  3695. (let* ((half-height (/ wnd-len 2))
  3696. (start (max 0
  3697. (min (- idx half-height)
  3698. (- len (1- wnd-len)))))
  3699. (end (min (+ start (1- wnd-len)) len)))
  3700. (list start end (- idx start))))
  3701. (defun ivy--format (cands)
  3702. "Return a string for CANDS suitable for display in the minibuffer.
  3703. CANDS is a list of candidates that :display-transformer can turn into strings."
  3704. (setq ivy--length (length cands))
  3705. (when (>= ivy--index ivy--length)
  3706. (ivy-set-index (max (1- ivy--length) 0)))
  3707. (if (null cands)
  3708. (setf (ivy-state-current ivy-last) "")
  3709. (let ((cur (nth ivy--index cands)))
  3710. (setf (ivy-state-current ivy-last) (if (stringp cur)
  3711. (copy-sequence cur)
  3712. cur)))
  3713. (let* ((bnd (ivy--minibuffer-index-bounds
  3714. ivy--index ivy--length ivy-height))
  3715. (wnd-cands (cl-subseq cands (car bnd) (cadr bnd)))
  3716. (case-fold-search (ivy--case-fold-p ivy-text))
  3717. transformer-fn)
  3718. (setq ivy--window-index (nth 2 bnd))
  3719. (when (setq transformer-fn (ivy-state-display-transformer-fn ivy-last))
  3720. (with-ivy-window
  3721. (with-current-buffer (ivy-state-buffer ivy-last)
  3722. (setq wnd-cands (mapcar transformer-fn wnd-cands)))))
  3723. (ivy--wnd-cands-to-str wnd-cands))))
  3724. (defun ivy--wnd-cands-to-str (wnd-cands)
  3725. (let ((str (concat "\n"
  3726. (funcall (ivy-alist-setting ivy-format-functions-alist)
  3727. (condition-case nil
  3728. (mapcar
  3729. #'ivy--format-minibuffer-line
  3730. wnd-cands)
  3731. (error wnd-cands))))))
  3732. (put-text-property 0 (length str) 'read-only nil str)
  3733. str))
  3734. (defvar recentf-list)
  3735. (defvar bookmark-alist)
  3736. (defcustom ivy-virtual-abbreviate 'name
  3737. "The mode of abbreviation for virtual buffer names."
  3738. :type '(choice
  3739. (const :tag "Only name" name)
  3740. (const :tag "Abbreviated path" abbreviate)
  3741. (const :tag "Full path" full)
  3742. ;; eventually, uniquify
  3743. ))
  3744. (declare-function bookmark-maybe-load-default-file "bookmark")
  3745. (declare-function bookmark-get-filename "bookmark")
  3746. (defun ivy--virtual-buffers ()
  3747. "Adapted from `ido-add-virtual-buffers-to-list'."
  3748. (require 'bookmark)
  3749. (unless recentf-mode
  3750. (recentf-mode 1))
  3751. (bookmark-maybe-load-default-file)
  3752. (let* ((vb-bkm (delete " - no file -"
  3753. (delq nil (mapcar #'bookmark-get-filename
  3754. bookmark-alist))))
  3755. (vb-list (cond ((eq ivy-use-virtual-buffers 'recentf)
  3756. recentf-list)
  3757. ((eq ivy-use-virtual-buffers 'bookmarks)
  3758. vb-bkm)
  3759. (ivy-use-virtual-buffers
  3760. (append recentf-list vb-bkm))
  3761. (t nil)))
  3762. virtual-buffers)
  3763. (dolist (head vb-list)
  3764. (let* ((file-name (if (stringp head)
  3765. head
  3766. (cdr head)))
  3767. (name (cond ((eq ivy-virtual-abbreviate 'name)
  3768. (file-name-nondirectory file-name))
  3769. ((eq ivy-virtual-abbreviate 'abbreviate)
  3770. (abbreviate-file-name file-name))
  3771. (t
  3772. (expand-file-name file-name)))))
  3773. (when (equal name "")
  3774. (setq name
  3775. (if (consp head)
  3776. (car head)
  3777. (file-name-nondirectory (directory-file-name file-name)))))
  3778. (unless (or (equal name "")
  3779. (get-file-buffer file-name)
  3780. (assoc name virtual-buffers))
  3781. (push (cons (copy-sequence name) file-name) virtual-buffers))))
  3782. (when virtual-buffers
  3783. (dolist (comp virtual-buffers)
  3784. (put-text-property 0 (length (car comp))
  3785. 'face 'ivy-virtual
  3786. (car comp)))
  3787. (setq ivy--virtual-buffers (nreverse virtual-buffers))
  3788. (mapcar #'car ivy--virtual-buffers))))
  3789. (defcustom ivy-ignore-buffers '("\\` " "\\`\\*tramp/")
  3790. "List of regexps or functions matching buffer names to ignore."
  3791. :type '(repeat (choice regexp function)))
  3792. (defvar ivy-switch-buffer-faces-alist '((dired-mode . ivy-subdir)
  3793. (org-mode . ivy-org))
  3794. "Store face customizations for `ivy-switch-buffer'.
  3795. Each KEY is `major-mode', each VALUE is a face name.")
  3796. (defun ivy--buffer-list (str &optional virtual predicate)
  3797. "Return the buffers that match STR.
  3798. If VIRTUAL is non-nil, add virtual buffers.
  3799. If optional argument PREDICATE is non-nil, use it to test each
  3800. possible match. See `all-completions' for further information."
  3801. (delete-dups
  3802. (nconc
  3803. (all-completions str #'internal-complete-buffer predicate)
  3804. (and virtual
  3805. (ivy--virtual-buffers)))))
  3806. (defvar ivy-views (and nil
  3807. `(("ivy + *scratch* {}"
  3808. (vert
  3809. (file ,(expand-file-name "ivy.el"))
  3810. (buffer "*scratch*")))
  3811. ("swiper + *scratch* {}"
  3812. (horz
  3813. (file ,(expand-file-name "swiper.el"))
  3814. (buffer "*scratch*")))))
  3815. "Store window configurations selectable by `ivy-switch-buffer'.
  3816. The default value is given as an example.
  3817. Each element is a list of (NAME VIEW). NAME is a string, it's
  3818. recommended to end it with a distinctive snippet e.g. \"{}\" so
  3819. that it's easy to distinguish the window configurations.
  3820. VIEW is either a TREE or a window-configuration (see
  3821. `ivy--get-view-config').
  3822. TREE is a nested list with the following valid cars:
  3823. - vert: split the window vertically
  3824. - horz: split the window horizontally
  3825. - file: open the specified file
  3826. - buffer: open the specified buffer
  3827. TREE can be nested multiple times to have multiple window splits.")
  3828. (defun ivy-default-view-name ()
  3829. "Return default name for new view."
  3830. (let* ((default-view-name
  3831. (concat "{} "
  3832. (mapconcat #'identity
  3833. (sort
  3834. (mapcar (lambda (w)
  3835. (let* ((b (window-buffer w))
  3836. (f (buffer-file-name b)))
  3837. (if f
  3838. (file-name-nondirectory f)
  3839. (buffer-name b))))
  3840. (window-list))
  3841. #'string-lessp)
  3842. " ")))
  3843. (view-name-re (concat "\\`"
  3844. (regexp-quote default-view-name)
  3845. " \\([0-9]+\\)"))
  3846. old-view)
  3847. (cond ((setq old-view
  3848. (cl-find-if
  3849. (lambda (x)
  3850. (string-match view-name-re (car x)))
  3851. ivy-views))
  3852. (format "%s %d"
  3853. default-view-name
  3854. (1+ (string-to-number
  3855. (match-string 1 (car old-view))))))
  3856. ((assoc default-view-name ivy-views)
  3857. (concat default-view-name " 1"))
  3858. (t
  3859. default-view-name))))
  3860. (defun ivy--get-view-config ()
  3861. "Get `current-window-configuration' for `ivy-views'."
  3862. (dolist (w (window-list))
  3863. (set-window-parameter w 'ivy-view-data
  3864. (with-current-buffer (window-buffer w)
  3865. (cond (buffer-file-name
  3866. (list 'file buffer-file-name (point)))
  3867. ((eq major-mode 'dired-mode)
  3868. (list 'file default-directory (point)))
  3869. (t
  3870. (list 'buffer (buffer-name) (point)))))))
  3871. (let ((window-persistent-parameters
  3872. (append window-persistent-parameters
  3873. (list (cons 'ivy-view-data t)))))
  3874. (current-window-configuration)))
  3875. (defun ivy-push-view (&optional arg)
  3876. "Push the current window tree on `ivy-views'.
  3877. When ARG is non-nil, replace a selected item on `ivy-views'.
  3878. Currently, the split configuration (i.e. horizontal or vertical)
  3879. and point positions are saved, but the split positions aren't.
  3880. Use `ivy-pop-view' to delete any item from `ivy-views'."
  3881. (interactive "P")
  3882. (let* ((view (ivy--get-view-config))
  3883. (view-name
  3884. (if arg
  3885. (ivy-read "Update view: " ivy-views)
  3886. (ivy-read "Name view: " nil
  3887. :initial-input (ivy-default-view-name)))))
  3888. (when view-name
  3889. (let ((x (assoc view-name ivy-views)))
  3890. (if x
  3891. (setcdr x (list view))
  3892. (push (list view-name view) ivy-views))))))
  3893. (defun ivy-pop-view-action (view)
  3894. "Delete VIEW from `ivy-views'."
  3895. (setq ivy-views (delete view ivy-views))
  3896. (setq ivy--all-candidates
  3897. (delete (car view) ivy--all-candidates))
  3898. (setq ivy--old-cands nil))
  3899. (defun ivy-pop-view ()
  3900. "Delete a view to delete from `ivy-views'."
  3901. (interactive)
  3902. (ivy-read "Pop view: " ivy-views
  3903. :preselect (caar ivy-views)
  3904. :action #'ivy-pop-view-action
  3905. :caller 'ivy-pop-view))
  3906. (defun ivy-source-views ()
  3907. "Return the name of the views saved in `ivy-views'."
  3908. (mapcar #'car ivy-views))
  3909. (ivy-set-sources
  3910. 'ivy-switch-buffer
  3911. '((original-source)
  3912. (ivy-source-views)))
  3913. (defun ivy-set-view-recur (view)
  3914. "Set VIEW recursively."
  3915. (cond ((window-configuration-p view)
  3916. (set-window-configuration view)
  3917. (dolist (w (window-list))
  3918. (with-selected-window w
  3919. (ivy-set-view-recur
  3920. (window-parameter w 'ivy-view-data)))))
  3921. ((eq (car view) 'vert)
  3922. (let* ((wnd1 (selected-window))
  3923. (wnd2 (split-window-vertically))
  3924. (views (cdr view))
  3925. (v (pop views))
  3926. (temp-wnd))
  3927. (with-selected-window wnd1
  3928. (ivy-set-view-recur v))
  3929. (while (setq v (pop views))
  3930. (with-selected-window wnd2
  3931. (when views
  3932. (setq temp-wnd (split-window-vertically)))
  3933. (ivy-set-view-recur v)
  3934. (when views
  3935. (setq wnd2 temp-wnd))))))
  3936. ((eq (car view) 'horz)
  3937. (let* ((wnd1 (selected-window))
  3938. (wnd2 (split-window-horizontally))
  3939. (views (cdr view))
  3940. (v (pop views))
  3941. (temp-wnd))
  3942. (with-selected-window wnd1
  3943. (ivy-set-view-recur v))
  3944. (while (setq v (pop views))
  3945. (with-selected-window wnd2
  3946. (when views
  3947. (setq temp-wnd (split-window-horizontally)))
  3948. (ivy-set-view-recur v)
  3949. (when views
  3950. (setq wnd2 temp-wnd))))))
  3951. ((eq (car view) 'file)
  3952. (let* ((name (nth 1 view))
  3953. (virtual (assoc name ivy--virtual-buffers))
  3954. buffer)
  3955. (cond ((setq buffer (get-buffer name))
  3956. (switch-to-buffer buffer nil 'force-same-window))
  3957. (virtual
  3958. (find-file (cdr virtual)))
  3959. ((file-exists-p name)
  3960. (find-file name))))
  3961. (when (and (> (length view) 2)
  3962. (numberp (nth 2 view)))
  3963. (goto-char (nth 2 view))))
  3964. ((eq (car view) 'buffer)
  3965. (switch-to-buffer (nth 1 view))
  3966. (when (and (> (length view) 2)
  3967. (numberp (nth 2 view)))
  3968. (goto-char (nth 2 view))))
  3969. ((eq (car view) 'sexp)
  3970. (eval (nth 1 view)))))
  3971. (defun ivy--switch-buffer-action (buffer)
  3972. "Switch to BUFFER.
  3973. BUFFER may be a string or nil."
  3974. (if (zerop (length buffer))
  3975. (switch-to-buffer
  3976. ivy-text nil 'force-same-window)
  3977. (let ((virtual (assoc buffer ivy--virtual-buffers))
  3978. (view (assoc buffer ivy-views)))
  3979. (cond ((and virtual
  3980. (not (get-buffer buffer)))
  3981. (find-file (cdr virtual)))
  3982. (view
  3983. (delete-other-windows)
  3984. (let (
  3985. ;; silence "Directory has changed on disk"
  3986. (inhibit-message t))
  3987. (ivy-set-view-recur (cadr view))))
  3988. (t
  3989. (switch-to-buffer
  3990. buffer nil 'force-same-window))))))
  3991. (defun ivy--switch-buffer-other-window-action (buffer)
  3992. "Switch to BUFFER in other window.
  3993. BUFFER may be a string or nil."
  3994. (if (zerop (length buffer))
  3995. (switch-to-buffer-other-window ivy-text)
  3996. (let ((virtual (assoc buffer ivy--virtual-buffers)))
  3997. (if (and virtual
  3998. (not (get-buffer buffer)))
  3999. (find-file-other-window (cdr virtual))
  4000. (switch-to-buffer-other-window buffer)))))
  4001. (defun ivy--rename-buffer-action (buffer)
  4002. "Rename BUFFER."
  4003. (let ((new-name (read-string "Rename buffer (to new name): ")))
  4004. (with-current-buffer buffer
  4005. (rename-buffer new-name))))
  4006. (defun ivy--find-file-action (buffer)
  4007. "Find file from BUFFER's directory."
  4008. (let* ((virtual (assoc buffer ivy--virtual-buffers))
  4009. (default-directory (if virtual
  4010. (file-name-directory (cdr virtual))
  4011. (buffer-local-value 'default-directory
  4012. (or (get-buffer buffer)
  4013. (current-buffer))))))
  4014. (call-interactively (if (functionp 'counsel-find-file)
  4015. #'counsel-find-file
  4016. #'find-file))))
  4017. (defun ivy--kill-buffer-or-virtual (buffer)
  4018. (if (get-buffer buffer)
  4019. (kill-buffer buffer)
  4020. (setq recentf-list (delete
  4021. (cdr (assoc buffer ivy--virtual-buffers))
  4022. recentf-list))))
  4023. (defun ivy--kill-current-candidate ()
  4024. (setf (ivy-state-preselect ivy-last) ivy--index)
  4025. (setq ivy--old-re nil)
  4026. (setq ivy--all-candidates (delete (ivy-state-current ivy-last) ivy--all-candidates))
  4027. (let ((ivy--recompute-index-inhibit t))
  4028. (ivy--exhibit)))
  4029. (defun ivy--kill-current-candidate-buffer ()
  4030. (setf (ivy-state-preselect ivy-last) ivy--index)
  4031. (setq ivy--old-re nil)
  4032. (setq ivy--all-candidates (ivy--buffer-list "" ivy-use-virtual-buffers
  4033. (ivy-state-predicate ivy-last)))
  4034. (let ((ivy--recompute-index-inhibit t))
  4035. (ivy--exhibit)))
  4036. (defun ivy--kill-buffer-action (buffer)
  4037. "Kill BUFFER."
  4038. (ivy--kill-buffer-or-virtual buffer)
  4039. (unless (buffer-live-p (ivy-state-buffer ivy-last))
  4040. (setf (ivy-state-buffer ivy-last)
  4041. (with-ivy-window (current-buffer))))
  4042. (ivy--kill-current-candidate-buffer))
  4043. (defvar ivy-switch-buffer-map
  4044. (let ((map (make-sparse-keymap)))
  4045. (ivy-define-key map (kbd "C-k") 'ivy-switch-buffer-kill)
  4046. map))
  4047. (defun ivy-switch-buffer-kill ()
  4048. "When at end-of-line, kill the current buffer in `ivy-switch-buffer'.
  4049. Otherwise, forward to `ivy-kill-line'."
  4050. (interactive)
  4051. (if (not (eolp))
  4052. (ivy-kill-line)
  4053. (ivy--kill-buffer-action
  4054. (ivy-state-current ivy-last))))
  4055. (ivy-set-actions
  4056. 'ivy-switch-buffer
  4057. '(("f"
  4058. ivy--find-file-action
  4059. "find file")
  4060. ("j"
  4061. ivy--switch-buffer-other-window-action
  4062. "other window")
  4063. ("k"
  4064. ivy--kill-buffer-action
  4065. "kill")
  4066. ("r"
  4067. ivy--rename-buffer-action
  4068. "rename")))
  4069. (ivy-set-actions
  4070. t
  4071. '(("i" ivy--action-insert "insert")
  4072. ("w" ivy--action-copy "copy")))
  4073. (defun ivy--trim-grep-line-number (x)
  4074. (if (string-match ":[0-9]+:" x)
  4075. (substring x (match-end 0))
  4076. x))
  4077. (defun ivy--action-insert (x)
  4078. (insert
  4079. (if (stringp x)
  4080. (ivy--trim-grep-line-number x)
  4081. x (car x))))
  4082. (defun ivy--action-copy (x)
  4083. (kill-new
  4084. (if (stringp x)
  4085. (ivy--trim-grep-line-number x)
  4086. (car x))))
  4087. (defun ivy--switch-buffer-matcher (regexp candidates)
  4088. "Return REGEXP matching CANDIDATES.
  4089. Skip buffers that match `ivy-ignore-buffers'."
  4090. (if (string-match-p "^:" ivy-text)
  4091. (delete-dups
  4092. (cl-remove-if-not
  4093. (lambda (s)
  4094. (let ((b (get-buffer s)))
  4095. (and b
  4096. (string-match-p regexp (buffer-local-value 'default-directory b))
  4097. (not (string-match-p "^\\*" s)))))
  4098. candidates))
  4099. (let ((res (ivy--re-filter regexp candidates)))
  4100. (if (or (null ivy-use-ignore)
  4101. (null ivy-ignore-buffers))
  4102. res
  4103. (or (cl-remove-if
  4104. (lambda (buf)
  4105. (cl-find-if
  4106. (lambda (f-or-r)
  4107. (if (functionp f-or-r)
  4108. (funcall f-or-r buf)
  4109. (string-match-p f-or-r buf)))
  4110. ivy-ignore-buffers))
  4111. res)
  4112. (and (eq ivy-use-ignore t)
  4113. res))))))
  4114. (defun ivy-append-face (str face)
  4115. "Append to STR the property FACE."
  4116. (when face
  4117. (setq str (copy-sequence str))
  4118. (add-face-text-property 0 (length str) face t str))
  4119. str)
  4120. (defun ivy--remote-buffer-p (buffer)
  4121. "Return non-nil if BUFFER object is visiting a remote file.
  4122. If that is the case, value is a string identifying the remote
  4123. connection."
  4124. (let ((dir (buffer-local-value 'default-directory buffer)))
  4125. (ignore-errors (file-remote-p dir))))
  4126. (defun ivy-switch-buffer-transformer (str)
  4127. "Transform candidate STR when switching buffers."
  4128. (let ((buf (get-buffer str)))
  4129. (cond ((not buf) str)
  4130. ((let ((remote (ivy--remote-buffer-p buf)))
  4131. (when remote
  4132. (format "%s (%s)" (ivy-append-face str 'ivy-remote) remote))))
  4133. ((not (verify-visited-file-modtime buf))
  4134. (ivy-append-face str 'ivy-modified-outside-buffer))
  4135. ((buffer-modified-p buf)
  4136. (ivy-append-face str 'ivy-modified-buffer))
  4137. (t
  4138. (let* ((mode (buffer-local-value 'major-mode buf))
  4139. (face (cdr (assq mode ivy-switch-buffer-faces-alist))))
  4140. (ivy-append-face str face))))))
  4141. (defun ivy-switch-buffer-occur (cands)
  4142. "Occur function for `ivy-switch-buffer' using `ibuffer'.
  4143. CANDS are the candidates to be displayed."
  4144. (unless cands
  4145. (setq cands (all-completions ivy-text #'internal-complete-buffer)))
  4146. (ibuffer
  4147. nil (buffer-name)
  4148. `((or ,@(cl-mapcan
  4149. (lambda (cand)
  4150. (unless (eq (get-text-property 0 'face cand) 'ivy-virtual)
  4151. `((name . ,(format "\\_<%s\\_>" (regexp-quote cand))))))
  4152. cands)))))
  4153. ;;;###autoload
  4154. (defun ivy-switch-buffer ()
  4155. "Switch to another buffer."
  4156. (interactive)
  4157. (ivy-read "Switch to buffer: " #'internal-complete-buffer
  4158. :keymap ivy-switch-buffer-map
  4159. :preselect (buffer-name (other-buffer (current-buffer)))
  4160. :action #'ivy--switch-buffer-action
  4161. :matcher #'ivy--switch-buffer-matcher
  4162. :caller 'ivy-switch-buffer))
  4163. (ivy-configure 'ivy-switch-buffer
  4164. :parent 'internal-complete-buffer
  4165. :occur #'ivy-switch-buffer-occur)
  4166. ;;;###autoload
  4167. (defun ivy-switch-view ()
  4168. "Switch to one of the window views stored by `ivy-push-view'."
  4169. (interactive)
  4170. (let ((ivy-initial-inputs-alist
  4171. '((ivy-switch-buffer . "{}"))))
  4172. (ivy-switch-buffer)))
  4173. ;;;###autoload
  4174. (defun ivy-switch-buffer-other-window ()
  4175. "Switch to another buffer in another window."
  4176. (interactive)
  4177. (ivy-read "Switch to buffer in other window: " #'internal-complete-buffer
  4178. :matcher #'ivy--switch-buffer-matcher
  4179. :preselect (buffer-name (other-buffer (current-buffer)))
  4180. :action #'ivy--switch-buffer-other-window-action
  4181. :keymap ivy-switch-buffer-map
  4182. :caller 'ivy-switch-buffer-other-window))
  4183. (ivy-configure 'ivy-switch-buffer-other-window
  4184. :parent 'ivy-switch-buffer)
  4185. (defun ivy--yank-handle-case-fold (text)
  4186. (if (and (> (length ivy-text) 0)
  4187. (string= (downcase ivy-text) ivy-text))
  4188. (downcase text)
  4189. text))
  4190. (defun ivy--yank-by (fn &rest args)
  4191. "Pull buffer text from current line into search string.
  4192. The region to extract is determined by the respective values of
  4193. point before and after applying FN to ARGS."
  4194. (let (text)
  4195. (with-ivy-window
  4196. (let ((beg (point))
  4197. (bol (line-beginning-position))
  4198. (eol (line-end-position))
  4199. end)
  4200. (unwind-protect
  4201. (progn (apply fn args)
  4202. (setq end (goto-char (max bol (min (point) eol))))
  4203. (setq text (buffer-substring-no-properties beg end))
  4204. (ivy--pulse-region beg end))
  4205. (unless text
  4206. (goto-char beg)))))
  4207. (when text
  4208. (insert (replace-regexp-in-string
  4209. " +" " "
  4210. (ivy--yank-handle-case-fold text)
  4211. t t)))))
  4212. (defun ivy-yank-word (&optional arg)
  4213. "Pull next word from buffer into search string.
  4214. If optional ARG is non-nil, pull in the next ARG
  4215. words (previous if ARG is negative)."
  4216. (interactive "p")
  4217. (ivy--yank-by #'forward-word arg))
  4218. (defun ivy-yank-symbol (&optional arg)
  4219. "Pull next symbol from buffer into search string.
  4220. If optional ARG is non-nil, pull in the next ARG
  4221. symbols (previous if ARG is negative)."
  4222. (interactive "p")
  4223. (ivy--yank-by #'forward-symbol (or arg 1)))
  4224. (defun ivy-yank-char (&optional arg)
  4225. "Pull next character from buffer into search string.
  4226. If optional ARG is non-nil, pull in the next ARG
  4227. characters (previous if ARG is negative)."
  4228. (interactive "p")
  4229. (ivy--yank-by #'forward-char arg))
  4230. (defvar ivy--pulse-overlay nil
  4231. "Overlay used to highlight yanked word.")
  4232. (defvar ivy--pulse-timer nil
  4233. "Timer used to dispose of `ivy--pulse-overlay'.")
  4234. (defcustom ivy-pulse-delay 0.5
  4235. "Number of seconds to display `ivy-yanked-word' highlight.
  4236. When nil, disable highlighting."
  4237. :type '(choice
  4238. (number :tag "Delay in seconds")
  4239. (const :tag "Disable" nil)))
  4240. (defun ivy--pulse-region (start end)
  4241. "Temporarily highlight text between START and END.
  4242. The \"pulse\" duration is determined by `ivy-pulse-delay'."
  4243. (when ivy-pulse-delay
  4244. (if ivy--pulse-overlay
  4245. (let ((ostart (overlay-start ivy--pulse-overlay))
  4246. (oend (overlay-end ivy--pulse-overlay)))
  4247. (when (< end start)
  4248. (cl-rotatef start end))
  4249. ;; Extend the existing overlay's region to include START..END,
  4250. ;; but only if the two regions are contiguous.
  4251. (move-overlay ivy--pulse-overlay
  4252. (if (= start oend) ostart start)
  4253. (if (= end ostart) oend end)))
  4254. (setq ivy--pulse-overlay (make-overlay start end))
  4255. (overlay-put ivy--pulse-overlay 'face 'ivy-yanked-word))
  4256. (when ivy--pulse-timer
  4257. (cancel-timer ivy--pulse-timer))
  4258. (setq ivy--pulse-timer
  4259. (run-at-time ivy-pulse-delay nil #'ivy--pulse-cleanup))))
  4260. (defun ivy--pulse-cleanup ()
  4261. "Cancel `ivy--pulse-timer' and delete `ivy--pulse-overlay'."
  4262. (when ivy--pulse-timer
  4263. (cancel-timer ivy--pulse-timer)
  4264. (setq ivy--pulse-timer nil))
  4265. (when ivy--pulse-overlay
  4266. (delete-overlay ivy--pulse-overlay)
  4267. (setq ivy--pulse-overlay nil)))
  4268. (defun ivy-kill-ring-save ()
  4269. "Store the current candidates into the kill ring.
  4270. If the region is active, forward to `kill-ring-save' instead."
  4271. (interactive)
  4272. (if (region-active-p)
  4273. (call-interactively 'kill-ring-save)
  4274. (kill-new
  4275. (mapconcat
  4276. #'identity
  4277. ivy--old-cands
  4278. "\n"))))
  4279. (defun ivy-insert-current ()
  4280. "Make the current candidate into current input.
  4281. Don't finish completion."
  4282. (interactive)
  4283. (delete-minibuffer-contents)
  4284. (let ((end (and ivy--directory
  4285. (ivy--dirname-p (ivy-state-current ivy-last))
  4286. -1)))
  4287. (insert (substring-no-properties
  4288. (ivy-state-current ivy-last) 0 end))))
  4289. (defun ivy-insert-current-full ()
  4290. "Insert the full Yank the current directory into the minibuffer."
  4291. (interactive)
  4292. (insert ivy--directory))
  4293. (defcustom ivy-preferred-re-builders
  4294. '((ivy--regex-plus . "ivy")
  4295. (ivy--regex-ignore-order . "order")
  4296. (ivy--regex-fuzzy . "fuzzy"))
  4297. "Alist of preferred re-builders with display names.
  4298. This list can be rotated with `ivy-rotate-preferred-builders'."
  4299. :type '(alist :key-type function :value-type string))
  4300. (defun ivy-rotate-preferred-builders ()
  4301. "Switch to the next re builder in `ivy-preferred-re-builders'."
  4302. (interactive)
  4303. (when ivy-preferred-re-builders
  4304. (setq ivy--old-re nil)
  4305. (setq ivy--regex-function
  4306. (let ((cell (assq ivy--regex-function ivy-preferred-re-builders)))
  4307. (car (or (cadr (memq cell ivy-preferred-re-builders))
  4308. (car ivy-preferred-re-builders)))))))
  4309. (defun ivy-toggle-fuzzy ()
  4310. "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
  4311. (interactive)
  4312. (setq ivy--old-re nil)
  4313. (if (eq ivy--regex-function 'ivy--regex-fuzzy)
  4314. (setq ivy--regex-function 'ivy--regex-plus)
  4315. (setq ivy--regex-function 'ivy--regex-fuzzy)))
  4316. (defun ivy--label-and-delete-dups (entries)
  4317. "Label ENTRIES with history indices."
  4318. (let ((ht (make-hash-table :test 'equal))
  4319. (idx 0)
  4320. entry
  4321. accum)
  4322. (while (setq entry (pop entries))
  4323. (unless (gethash entry ht)
  4324. (puthash entry t ht)
  4325. (push `(,entry . ,idx) accum))
  4326. (cl-incf idx))
  4327. (nreverse accum)))
  4328. (defvar ivy--reverse-i-search-symbol nil
  4329. "Store the history symbol.")
  4330. (defun ivy-reverse-i-search-kill ()
  4331. "Remove the current item from history"
  4332. (interactive)
  4333. (if (not (eolp))
  4334. (ivy-kill-line)
  4335. (let ((current (ivy-state-current ivy-last)))
  4336. (if (symbolp ivy--reverse-i-search-symbol)
  4337. (set
  4338. ivy--reverse-i-search-symbol
  4339. (delete current (symbol-value ivy--reverse-i-search-symbol)))
  4340. (ring-remove
  4341. ivy--reverse-i-search-symbol
  4342. (ring-member ivy--reverse-i-search-symbol (ivy-state-current ivy-last)))))
  4343. (ivy--kill-current-candidate)))
  4344. (defvar ivy-reverse-i-search-map
  4345. (let ((map (make-sparse-keymap)))
  4346. (ivy-define-key map (kbd "C-k") 'ivy-reverse-i-search-kill)
  4347. map))
  4348. (defun ivy-history-contents (history)
  4349. "Copy contents of HISTORY.
  4350. A copy is necessary so that we don't clobber any string attributes.
  4351. Also set `ivy--reverse-i-search-symbol' to HISTORY."
  4352. (setq ivy--reverse-i-search-symbol history)
  4353. (cond ((symbolp history)
  4354. (ivy--label-and-delete-dups
  4355. (copy-sequence (symbol-value history))))
  4356. ((ring-p history)
  4357. (ivy--label-and-delete-dups
  4358. (when (> (ring-size history) 0)
  4359. (ring-elements history))))
  4360. ((sequencep history)
  4361. (ivy--label-and-delete-dups
  4362. (copy-sequence history)))
  4363. (t
  4364. (error "Expected a symbol, ring, or sequence: %S" history))))
  4365. (defun ivy-reverse-i-search ()
  4366. "Enter a recursive `ivy-read' session using the current history.
  4367. The selected history element will be inserted into the minibuffer.
  4368. \\<ivy-reverse-i-search-map>
  4369. You can also delete an element from history with \\[ivy-reverse-i-search-kill]."
  4370. (interactive)
  4371. (cond
  4372. ((= (minibuffer-depth) 0)
  4373. (user-error
  4374. "This command is intended to be called from within `ivy-read'"))
  4375. ;; don't recur
  4376. ((and (> (minibuffer-depth) 1)
  4377. (eq (ivy-state-caller ivy-last) 'ivy-reverse-i-search)))
  4378. (t
  4379. (let ((enable-recursive-minibuffers t)
  4380. (old-last ivy-last))
  4381. (ivy-read "Reverse-i-search: "
  4382. (ivy-history-contents (ivy-state-history ivy-last))
  4383. :keymap ivy-reverse-i-search-map
  4384. :action (lambda (x)
  4385. (ivy--reset-state
  4386. (setq ivy-last old-last))
  4387. (delete-minibuffer-contents)
  4388. (insert (substring-no-properties (car x)))
  4389. (ivy--cd-maybe))
  4390. :caller 'ivy-reverse-i-search)))))
  4391. (defun ivy-restrict-to-matches ()
  4392. "Restrict candidates to current input and erase input."
  4393. (interactive)
  4394. (delete-minibuffer-contents)
  4395. (if (ivy-state-dynamic-collection ivy-last)
  4396. (progn
  4397. (setf (ivy-state-dynamic-collection ivy-last) nil)
  4398. (setf (ivy-state-collection ivy-last)
  4399. (setq ivy--all-candidates ivy--old-cands)))
  4400. (setq ivy--all-candidates
  4401. (ivy--filter ivy-text ivy--all-candidates))))
  4402. ;;* Occur
  4403. (defvar-local ivy-occur-last nil
  4404. "Buffer-local value of `ivy-last'.
  4405. Can't re-use `ivy-last' because using e.g. `swiper' in the same
  4406. buffer would modify `ivy-last'.")
  4407. (defvar ivy-occur-mode-map
  4408. (let ((map (make-sparse-keymap)))
  4409. (ivy-define-key map [mouse-1] 'ivy-occur-click)
  4410. (ivy-define-key map (kbd "RET") 'ivy-occur-press-and-switch)
  4411. (ivy-define-key map (kbd "j") 'ivy-occur-next-line)
  4412. (ivy-define-key map (kbd "k") 'ivy-occur-previous-line)
  4413. (define-key map (kbd "h") 'backward-char)
  4414. (define-key map (kbd "l") 'forward-char)
  4415. (ivy-define-key map (kbd "f") 'ivy-occur-press)
  4416. (ivy-define-key map (kbd "g") 'ivy-occur-revert-buffer)
  4417. (ivy-define-key map (kbd "a") 'ivy-occur-read-action)
  4418. (ivy-define-key map (kbd "o") 'ivy-occur-dispatch)
  4419. (ivy-define-key map (kbd "c") 'ivy-occur-toggle-calling)
  4420. (define-key map (kbd "q") 'quit-window)
  4421. (define-key map (kbd "R") 'read-only-mode)
  4422. (ivy-define-key map (kbd "C-d") 'ivy-occur-delete-candidate)
  4423. map)
  4424. "Keymap for Ivy Occur mode.")
  4425. (defun ivy-occur-toggle-calling ()
  4426. "Toggle `ivy-calling'."
  4427. (interactive)
  4428. (if (setq ivy-calling (not ivy-calling))
  4429. (progn
  4430. (setq mode-name "Ivy-Occur [calling]")
  4431. (ivy-occur-press))
  4432. (setq mode-name "Ivy-Occur"))
  4433. (force-mode-line-update))
  4434. (defun ivy--find-occur-buffer ()
  4435. (let ((cb (current-buffer)))
  4436. (cl-find-if
  4437. (lambda (b)
  4438. (with-current-buffer b
  4439. (and (eq major-mode 'ivy-occur-grep-mode)
  4440. (equal cb (ivy-state-buffer ivy-occur-last)))))
  4441. (buffer-list))))
  4442. (defun ivy--select-occur-buffer ()
  4443. (let* ((ob (ivy--find-occur-buffer))
  4444. (ow (cl-find-if (lambda (w) (equal ob (window-buffer w)))
  4445. (window-list))))
  4446. (if ow
  4447. (select-window ow)
  4448. (pop-to-buffer ob))))
  4449. (defun ivy-occur-next-line (&optional arg)
  4450. "Move the cursor down ARG lines.
  4451. When `ivy-calling' isn't nil, call `ivy-occur-press'."
  4452. (interactive "p")
  4453. (let ((offset (cond ((derived-mode-p 'ivy-occur-grep-mode) 5)
  4454. ((derived-mode-p 'ivy-occur-mode) 2))))
  4455. (if offset
  4456. (progn
  4457. (if (< (line-number-at-pos) offset)
  4458. (progn
  4459. (goto-char (point-min))
  4460. (forward-line (1- offset)))
  4461. (forward-line arg)
  4462. (when (eolp)
  4463. (forward-line -1)))
  4464. (when ivy-calling
  4465. (ivy-occur-press)))
  4466. (ivy--select-occur-buffer)
  4467. (ivy-occur-next-line arg)
  4468. (ivy-occur-press-and-switch))))
  4469. (defun ivy-occur-previous-line (&optional arg)
  4470. "Move the cursor up ARG lines.
  4471. When `ivy-calling' isn't nil, call `ivy-occur-press'."
  4472. (interactive "p")
  4473. (let ((offset (cond ((derived-mode-p 'ivy-occur-grep-mode) 5)
  4474. ((derived-mode-p 'ivy-occur-mode) 2))))
  4475. (if offset
  4476. (progn
  4477. (forward-line (- arg))
  4478. (when (< (line-number-at-pos) offset)
  4479. (goto-char (point-min))
  4480. (forward-line (1- offset)))
  4481. (when ivy-calling
  4482. (ivy-occur-press)))
  4483. (ivy--select-occur-buffer)
  4484. (ivy-occur-previous-line arg)
  4485. (ivy-occur-press-and-switch))))
  4486. (defun ivy-occur-next-error (n &optional reset)
  4487. "A `next-error-function' for `ivy-occur-mode'."
  4488. (interactive "p")
  4489. (when reset
  4490. (goto-char (point-min)))
  4491. (setq n (or n 1))
  4492. (let ((ivy-calling t))
  4493. (cond ((< n 0) (ivy-occur-previous-line (- n)))
  4494. (t (ivy-occur-next-line n))))
  4495. ;; The window's point overrides the buffer's point every time it's redisplayed
  4496. (dolist (window (get-buffer-window-list nil nil t))
  4497. (set-window-point window (point))))
  4498. (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
  4499. "Major mode for output from \\[ivy-occur].
  4500. \\{ivy-occur-mode-map}"
  4501. (setq-local view-read-only nil))
  4502. (defvar ivy-occur-grep-mode-map
  4503. (let ((map (copy-keymap ivy-occur-mode-map)))
  4504. (ivy-define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
  4505. (ivy-define-key map "w" 'ivy-wgrep-change-to-wgrep-mode)
  4506. map)
  4507. "Keymap for Ivy Occur Grep mode.")
  4508. (defun ivy-occur-delete-candidate ()
  4509. (interactive)
  4510. (let ((inhibit-read-only t))
  4511. (delete-region (line-beginning-position)
  4512. (1+ (line-end-position)))))
  4513. (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
  4514. "Major mode for output from \\[ivy-occur].
  4515. \\{ivy-occur-grep-mode-map}"
  4516. (setq-local view-read-only nil)
  4517. (when (fboundp 'wgrep-setup)
  4518. (wgrep-setup)))
  4519. (defun ivy--starts-with-dotslash (str)
  4520. (string-match-p "\\`\\.[/\\]" str))
  4521. (defun ivy--occur-insert-lines (cands)
  4522. "Insert CANDS into `ivy-occur' buffer."
  4523. (font-lock-mode -1)
  4524. (dolist (cand cands)
  4525. (setq cand
  4526. (if (string-match "\\`\\(.*:[0-9]+:\\)\\(.*\\)\\'" cand)
  4527. (let ((file-and-line (match-string 1 cand))
  4528. (grep-line (match-string 2 cand)))
  4529. (concat
  4530. (propertize file-and-line 'face 'ivy-grep-info)
  4531. (ivy--highlight-fuzzy grep-line)))
  4532. (ivy--highlight-fuzzy (copy-sequence cand))))
  4533. (add-text-properties
  4534. 0 (length cand)
  4535. '(mouse-face
  4536. highlight
  4537. help-echo "mouse-1: call ivy-action")
  4538. cand)
  4539. (insert (if (ivy--starts-with-dotslash cand) "" " ")
  4540. cand ?\n)))
  4541. (defun ivy--occur-default (cands)
  4542. "Insert CANDS into the current occur buffer."
  4543. (unless cands
  4544. (let ((coll (ivy-state-collection ivy-last)))
  4545. (when (arrayp coll)
  4546. (setq coll (all-completions "" coll (ivy-state-predicate ivy-last))))
  4547. (setq cands (ivy--filter (ivy-state-text ivy-last) coll))))
  4548. (ivy-occur-mode)
  4549. (insert (format "%d candidates:\n" (length cands)))
  4550. (ivy--occur-insert-lines cands)
  4551. (read-only-mode))
  4552. (defun ivy-occur ()
  4553. "Stop completion and put the current candidates into a new buffer.
  4554. The new buffer remembers current action(s).
  4555. While in the *ivy-occur* buffer, selecting a candidate with RET or
  4556. a mouse click will call the appropriate action for that candidate.
  4557. There is no limit on the number of *ivy-occur* buffers."
  4558. (interactive)
  4559. (if (not (window-minibuffer-p))
  4560. (user-error "No completion session is active")
  4561. (let* ((caller (ivy-state-caller ivy-last))
  4562. (occur-fn (or (plist-get ivy--occurs-list caller)
  4563. #'ivy--occur-default))
  4564. (buffer
  4565. (generate-new-buffer
  4566. (format "*ivy-occur%s \"%s\"*"
  4567. (if caller
  4568. (concat " " (prin1-to-string caller))
  4569. "")
  4570. ivy-text))))
  4571. (with-current-buffer buffer
  4572. (funcall occur-fn ivy--old-cands)
  4573. (setf (ivy-state-text ivy-last) ivy-text)
  4574. (setq ivy-occur-last ivy-last))
  4575. (ivy-exit-with-action
  4576. (lambda (_)
  4577. (pop-to-buffer buffer)
  4578. (setq next-error-last-buffer buffer)
  4579. (setq-local next-error-function #'ivy-occur-next-error))))))
  4580. (defun ivy-occur-revert-buffer ()
  4581. "Refresh the buffer making it up-to date with the collection.
  4582. Currently only works for `swiper'. In that specific case, the
  4583. *ivy-occur* buffer becomes nearly useless as the original buffer
  4584. is updated, since the line numbers no longer match.
  4585. Calling this function is as if you called `ivy-occur' on the
  4586. updated original buffer."
  4587. (interactive)
  4588. (let ((caller (ivy-state-caller ivy-occur-last))
  4589. (ivy-last ivy-occur-last))
  4590. (let ((inhibit-read-only t)
  4591. (line (line-number-at-pos)))
  4592. (erase-buffer)
  4593. (funcall (or (plist-get ivy--occurs-list caller)
  4594. #'ivy--occur-default) nil)
  4595. (goto-char (point-min))
  4596. (forward-line (1- line)))
  4597. (setq ivy-occur-last ivy-last)))
  4598. (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
  4599. (defun ivy-wgrep-change-to-wgrep-mode ()
  4600. "Forward to `wgrep-change-to-wgrep-mode'."
  4601. (interactive)
  4602. (if (require 'wgrep nil 'noerror)
  4603. (wgrep-change-to-wgrep-mode)
  4604. (error "Package wgrep isn't installed")))
  4605. (defun ivy-occur-read-action ()
  4606. "Select one of the available actions as the current one."
  4607. (interactive)
  4608. (let ((ivy-last ivy-occur-last))
  4609. (ivy-read-action)))
  4610. (defun ivy-occur-dispatch ()
  4611. "Call one of the available actions on the current item."
  4612. (interactive)
  4613. (let* ((state-action (ivy-state-action ivy-occur-last))
  4614. (actions (if (symbolp state-action)
  4615. state-action
  4616. (copy-sequence state-action))))
  4617. (unwind-protect
  4618. (progn
  4619. (ivy-occur-read-action)
  4620. (ivy-occur-press))
  4621. (setf (ivy-state-action ivy-occur-last) actions))))
  4622. (defun ivy-occur-click (event)
  4623. "Execute action for the current candidate.
  4624. EVENT gives the mouse position."
  4625. (interactive "e")
  4626. (let ((window (posn-window (event-end event)))
  4627. (pos (posn-point (event-end event))))
  4628. (with-current-buffer (window-buffer window)
  4629. (goto-char pos)
  4630. (ivy-occur-press))))
  4631. (declare-function swiper--cleanup "swiper")
  4632. (declare-function swiper--add-overlays "swiper")
  4633. (defvar ivy-occur-timer nil)
  4634. (defun ivy--occur-press-update-window ()
  4635. (cond
  4636. ((memq (ivy-state-caller ivy-occur-last)
  4637. (append '(swiper swiper-isearch) ivy-highlight-grep-commands))
  4638. (let ((window (ivy-state-window ivy-occur-last))
  4639. (buffer (ivy-state-buffer ivy-occur-last)))
  4640. (when (buffer-live-p buffer)
  4641. (cond ((or (not (window-live-p window))
  4642. (equal window (selected-window)))
  4643. (save-selected-window
  4644. (setf (ivy-state-window ivy-occur-last)
  4645. (display-buffer buffer))))
  4646. ((not (equal (window-buffer window) buffer))
  4647. (with-selected-window window
  4648. (switch-to-buffer buffer)))))))
  4649. ((memq (ivy-state-caller ivy-occur-last)
  4650. '(counsel-describe-function
  4651. counsel-describe-variable
  4652. counsel-describe-symbol))
  4653. (setf (ivy-state-window ivy-occur-last)
  4654. (selected-window))
  4655. (selected-window))))
  4656. (defun ivy--occur-press-buffer ()
  4657. (let ((buffer (ivy-state-buffer ivy-last)))
  4658. (if (buffer-live-p buffer)
  4659. buffer
  4660. (current-buffer))))
  4661. (defun ivy-occur-press ()
  4662. "Execute action for the current candidate."
  4663. (interactive)
  4664. (ivy--occur-press-update-window)
  4665. (when (save-excursion
  4666. (beginning-of-line)
  4667. (looking-at "\\(?:.[/\\]\\| \\)\\(.*\\)$"))
  4668. (let* ((ivy-last ivy-occur-last)
  4669. (ivy-text (ivy-state-text ivy-last))
  4670. (str (buffer-substring
  4671. (match-beginning 1)
  4672. (match-end 1)))
  4673. (offset (or (get-text-property 0 'offset str) 0))
  4674. (coll (ivy-state-collection ivy-last))
  4675. (action (ivy--get-action ivy-last))
  4676. (ivy-exit 'done))
  4677. (with-ivy-window
  4678. (with-current-buffer (ivy--occur-press-buffer)
  4679. (save-restriction
  4680. (widen)
  4681. (funcall action
  4682. (if (and (consp coll)
  4683. (consp (car coll)))
  4684. (assoc str coll)
  4685. (substring str offset)))))
  4686. (if (memq (ivy-state-caller ivy-last)
  4687. (append '(swiper swiper-isearch) ivy-highlight-grep-commands))
  4688. (with-current-buffer (window-buffer (selected-window))
  4689. (swiper--cleanup)
  4690. (swiper--add-overlays
  4691. (ivy--regex ivy-text)
  4692. (line-beginning-position)
  4693. (line-end-position)
  4694. (selected-window))
  4695. (when (timerp ivy-occur-timer)
  4696. (cancel-timer ivy-occur-timer))
  4697. (setq ivy-occur-timer
  4698. (run-at-time 1.0 nil 'swiper--cleanup))))))))
  4699. (defun ivy-occur-press-and-switch ()
  4700. "Execute action for the current candidate and switch window."
  4701. (interactive)
  4702. (ivy-occur-press)
  4703. (select-window (ivy--get-window ivy-occur-last)))
  4704. (defun ivy--marked-p ()
  4705. (member (ivy-state-current ivy-last) ivy-marked-candidates))
  4706. (defun ivy--unmark (cand)
  4707. (setcar (member cand ivy--all-candidates)
  4708. (setcar (member cand ivy--old-cands)
  4709. (substring cand (length ivy-mark-prefix))))
  4710. (setq ivy-marked-candidates
  4711. (delete cand ivy-marked-candidates)))
  4712. (defun ivy--mark (cand)
  4713. (let ((marked-cand (concat ivy-mark-prefix cand)))
  4714. (setcar (member cand ivy--all-candidates)
  4715. (setcar (member cand ivy--old-cands) marked-cand))
  4716. (setq ivy-marked-candidates
  4717. (append ivy-marked-candidates (list marked-cand)))))
  4718. (defun ivy-mark ()
  4719. "Mark the selected candidate and move to the next one.
  4720. In `ivy-call', :action will be called in turn for all marked
  4721. candidates.
  4722. However, if :multi-action was supplied to `ivy-read', then it
  4723. will be called with `ivy-marked-candidates'. This way, it can
  4724. make decisions based on the whole marked list."
  4725. (interactive)
  4726. (unless (ivy--marked-p)
  4727. (ivy--mark (ivy-state-current ivy-last)))
  4728. (ivy-next-line))
  4729. (defun ivy-unmark ()
  4730. "Unmark the selected candidate and move to the next one."
  4731. (interactive)
  4732. (when (ivy--marked-p)
  4733. (ivy--unmark (ivy-state-current ivy-last)))
  4734. (ivy-next-line))
  4735. (defun ivy-unmark-backward ()
  4736. "Move to the previous candidate and unmark it."
  4737. (interactive)
  4738. (ivy-previous-line)
  4739. (ivy--exhibit)
  4740. (when (ivy--marked-p)
  4741. (ivy--unmark (ivy-state-current ivy-last))))
  4742. (defun ivy-toggle-marks ()
  4743. "Toggle mark for all narrowed candidates."
  4744. (interactive)
  4745. (dolist (cand ivy--old-cands)
  4746. (if (member cand ivy-marked-candidates)
  4747. (ivy--unmark cand)
  4748. (ivy--mark cand))))
  4749. (defconst ivy-help-file (let ((default-directory
  4750. (if load-file-name
  4751. (file-name-directory load-file-name)
  4752. default-directory)))
  4753. (if (file-exists-p "ivy-help.org")
  4754. (expand-file-name "ivy-help.org")
  4755. (if (file-exists-p "doc/ivy-help.org")
  4756. (expand-file-name "doc/ivy-help.org"))))
  4757. "The file for `ivy-help'.")
  4758. (defvar org-hide-emphasis-markers)
  4759. (defun ivy-help ()
  4760. "Help for `ivy'."
  4761. (interactive)
  4762. (let ((buf (get-buffer "*Ivy Help*"))
  4763. (inhibit-read-only t))
  4764. (unless buf
  4765. (setq buf (get-buffer-create "*Ivy Help*"))
  4766. (cl-letf (((symbol-function #'help-buffer) (lambda () buf)))
  4767. (describe-mode))
  4768. (with-current-buffer buf
  4769. (goto-char (point-min))
  4770. (insert "* describe-mode\n")
  4771. (goto-char (point-min))
  4772. (insert-file-contents ivy-help-file)
  4773. (org-mode)
  4774. (setq-local org-hide-emphasis-markers t)
  4775. (view-mode)
  4776. (goto-char (point-min))
  4777. (let ((inhibit-message t))
  4778. (org-cycle '(64)))))
  4779. (if (eq this-command 'ivy-help)
  4780. (switch-to-buffer buf)
  4781. (with-ivy-window
  4782. (pop-to-buffer buf)))
  4783. (view-mode)
  4784. (goto-char (point-min))))
  4785. (declare-function ffap-url-p "ffap")
  4786. (defvar ffap-url-fetcher)
  4787. (defun ivy-ffap-url-p (string)
  4788. "Forward to `ffap-url-p'."
  4789. (require 'ffap)
  4790. (ffap-url-p string))
  4791. (defun ivy-ffap-url-fetcher (url)
  4792. "Calls `ffap-url-fetcher'."
  4793. (require 'ffap)
  4794. (funcall ffap-url-fetcher url))
  4795. (ivy-configure 'read-file-name-internal
  4796. :sort-fn #'ivy-sort-file-function-default
  4797. :display-transformer-fn #'ivy-read-file-transformer
  4798. :alt-done-fn #'ivy--directory-done)
  4799. (ivy-configure 'internal-complete-buffer
  4800. :display-transformer-fn #'ivy-switch-buffer-transformer)
  4801. (ivy-configure 'Info-read-node-name-1
  4802. :alt-done-fn #'ivy--info-alt-done)
  4803. (provide 'ivy)
  4804. ;;; ivy.el ends here