Klimi's new dotfiles with stow.
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.

4944 lines
181 KiB

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