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.

5056 lines
184 KiB

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