Fetching contributors…
Cannot retrieve contributors at this time
6492 lines (5786 sloc) 273 KB
;;; helm.el --- Emacs incremental and narrowing framework -*- lexical-binding: t -*-
;; Copyright (C) 2007 Tamas Patrovics
;; 2008 ~ 2011 rubikitch <>
;; 2011 ~ 2018 Thierry Volpiatto <>
;; This is a fork of anything.el wrote by Tamas Patrovics.
;; Authors of anything.el: Tamas Patrovics
;; rubikitch <>
;; Thierry Volpiatto <>
;; Author: Thierry Volpiatto <>
;; URL:
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <>.
;;; Code:
(require 'cl-lib)
(require 'async)
(require 'advice) ; Shutup byte compiler about ad-deactivate.
(require 'helm-lib)
(require 'helm-multi-match)
(require 'helm-source)
;;; Multi keys
(defun helm-define-multi-key (keymap key functions &optional delay)
"In KEYMAP, define key sequence KEY for function list FUNCTIONS.
Each function runs sequentially for each KEY press.
If DELAY is specified, switch back to initial function of FUNCTIONS list
after DELAY seconds.
The functions in FUNCTIONS list take no args.
(defun foo ()
(message \"Run foo\"))
(defun bar ()
(message \"Run bar\"))
(defun baz ()
(message \"Run baz\"))
\(helm-define-multi-key global-map (kbd \"<f5> q\") '(foo bar baz) 2)
Each time \"<f5> q\" is pressed, the next function is executed. Waiting
more than 2 seconds between key presses switches back to executing the first
function on the next hit."
(define-key keymap key (helm-make-multi-command functions delay)))
(defmacro helm-multi-key-defun (name docstring funs &optional delay)
"Define NAME as a multi-key command running FUNS.
After DELAY seconds, the FUNS list is reinitialized.
See `helm-define-multi-key'."
(declare (indent 2))
(setq docstring (if docstring (concat docstring "\n\n")
"This is a helm-ish multi-key command."))
`(defalias (quote ,name) (helm-make-multi-command ,funs ,delay) ,docstring))
(defun helm-make-multi-command (functions &optional delay)
"Return an anonymous multi-key command running FUNCTIONS.
Run each function in the FUNCTIONS list in turn when called within DELAY seconds."
(declare (indent 1))
(let ((funs functions)
(iter (cl-gensym "helm-iter-key"))
(timeout delay))
(eval (list 'defvar iter nil))
(lambda ()
(helm-run-multi-key-command funs iter timeout))))
(defun helm-run-multi-key-command (functions iterator delay)
(let ((fn (lambda ()
(cl-loop for count from 1 to (length functions)
collect count)))
(unless (and (symbol-value iterator)
;; Reset iterator when another key is pressed.
(eq this-command real-last-command))
(set iterator (helm-iter-list (funcall fn))))
(setq next (helm-iter-next (symbol-value iterator)))
(unless next
(set iterator (helm-iter-list (funcall fn)))
(setq next (helm-iter-next (symbol-value iterator))))
(and next (symbol-value iterator)
(call-interactively (nth (1- next) functions)))
(when delay (run-with-idle-timer
delay nil (lambda ()
(set iterator nil))))))
(helm-multi-key-defun helm-toggle-resplit-and-swap-windows
"Multi key command to re-split and swap helm window.
First call runs `helm-toggle-resplit-window',
and second call within 0.5s runs `helm-swap-windows'."
'(helm-toggle-resplit-window helm-swap-windows) 1)
(put 'helm-toggle-resplit-and-swap-windows 'helm-only t)
(defun helm-define-key-with-subkeys (map key subkey command
&optional other-subkeys prompt exit-fn)
"Defines in MAP a KEY and SUBKEY to COMMAND.
This allows typing KEY to call COMMAND the first time and
type only SUBKEY on subsequent calls.
Arg MAP is the keymap to use, SUBKEY is the initial short key-binding to
Arg OTHER-SUBKEYS is an alist specifying other short key-bindings
to use once started e.g:
\(helm-define-key-with-subkeys global-map
\(kbd \"C-x v n\") ?n 'git-gutter:next-hunk '((?p . git-gutter:previous-hunk))\)
In this example, `C-x v n' will run `git-gutter:next-hunk'
subsequent \"n\"'s run this command again
and subsequent \"p\"'s run `git-gutter:previous-hunk'.
If specified PROMPT can be displayed in minibuffer to
Arg EXIT-FN specifies a function to run on exit.
For any other keys pressed, run their assigned command as defined
in MAP and then exit the loop running EXIT-FN, if specified.
NOTE: SUBKEY and OTHER-SUBKEYS bindings support only char syntax and
vectors, so don't use strings to define them."
(declare (indent 1))
(define-key map key
(lambda ()
(call-interactively command)
(while (let ((input (read-key prompt)) other kb com)
(setq last-command-event input)
((eq input subkey)
(call-interactively command)
((setq other (assoc input other-subkeys))
(call-interactively (cdr other))
(setq kb (vector last-command-event))
(setq com (lookup-key map kb))
(if (commandp com)
(call-interactively com)
(setq unread-command-events
(nconc (mapcar 'identity kb)
(and exit-fn (funcall exit-fn))))))
;;; Keymap
(defvar helm-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map minibuffer-local-map)
(define-key map (kbd "<down>") 'helm-next-line)
(define-key map (kbd "<up>") 'helm-previous-line)
(define-key map (kbd "C-n") 'helm-next-line)
(define-key map (kbd "C-p") 'helm-previous-line)
(define-key map (kbd "<C-down>") 'helm-follow-action-forward)
(define-key map (kbd "<C-up>") 'helm-follow-action-backward)
(define-key map (kbd "<prior>") 'helm-previous-page)
(define-key map (kbd "<next>") 'helm-next-page)
(define-key map (kbd "M-v") 'helm-previous-page)
(define-key map (kbd "C-v") 'helm-next-page)
(define-key map (kbd "M-<") 'helm-beginning-of-buffer)
(define-key map (kbd "M->") 'helm-end-of-buffer)
(define-key map (kbd "C-g") 'helm-keyboard-quit)
(define-key map (kbd "<right>") 'helm-next-source)
(define-key map (kbd "<left>") 'helm-previous-source)
(define-key map (kbd "<RET>") 'helm-maybe-exit-minibuffer)
(define-key map (kbd "C-i") 'helm-select-action)
(define-key map (kbd "C-z") 'helm-execute-persistent-action)
(define-key map (kbd "C-j") 'helm-execute-persistent-action)
(define-key map (kbd "C-o") 'helm-next-source)
(define-key map (kbd "M-o") 'helm-previous-source)
(define-key map (kbd "C-l") 'helm-recenter-top-bottom-other-window)
(define-key map (kbd "M-C-l") 'helm-reposition-window-other-window)
(define-key map (kbd "C-c &") 'helm-restore-last-frame-position)
(define-key map (kbd "C-M-v") 'helm-scroll-other-window)
(define-key map (kbd "M-<next>") 'helm-scroll-other-window)
(define-key map (kbd "C-M-y") 'helm-scroll-other-window-down)
(define-key map (kbd "C-M-S-v") 'helm-scroll-other-window-down)
(define-key map (kbd "M-<prior>") 'helm-scroll-other-window-down)
(define-key map (kbd "<C-M-down>") 'helm-scroll-other-window)
(define-key map (kbd "<C-M-up>") 'helm-scroll-other-window-down)
(define-key map (kbd "C-@") 'helm-toggle-visible-mark)
(define-key map (kbd "C-SPC") 'helm-toggle-visible-mark)
(define-key map (kbd "M-SPC") 'helm-toggle-visible-mark)
(define-key map (kbd "M-[") nil)
(define-key map (kbd "M-(") 'helm-prev-visible-mark)
(define-key map (kbd "M-)") 'helm-next-visible-mark)
(define-key map (kbd "C-k") 'helm-delete-minibuffer-contents)
(define-key map (kbd "C-x C-f") 'helm-quit-and-find-file)
(define-key map (kbd "M-m") 'helm-toggle-all-marks)
(define-key map (kbd "M-a") 'helm-mark-all)
(define-key map (kbd "M-U") 'helm-unmark-all)
(define-key map (kbd "C-M-a") 'helm-show-all-in-this-source-only)
(define-key map (kbd "C-M-e") 'helm-display-all-sources)
(define-key map (kbd "C-s") 'undefined)
(define-key map (kbd "M-s") 'undefined)
(define-key map (kbd "C-}") 'helm-narrow-window)
(define-key map (kbd "C-{") 'helm-enlarge-window)
(define-key map (kbd "C-c -") 'helm-swap-windows)
(define-key map (kbd "C-c _") 'helm-toggle-full-frame)
(define-key map (kbd "C-c C-y") 'helm-yank-selection)
(define-key map (kbd "C-c C-k") 'helm-kill-selection-and-quit)
(define-key map (kbd "C-c C-i") 'helm-copy-to-buffer)
(define-key map (kbd "C-c C-f") 'helm-follow-mode)
(define-key map (kbd "C-c C-u") 'helm-refresh)
(define-key map (kbd "C-c >") 'helm-toggle-truncate-line)
(define-key map (kbd "M-p") 'previous-history-element)
(define-key map (kbd "M-n") 'next-history-element)
(define-key map (kbd "C-!") 'helm-toggle-suspend-update)
(define-key map (kbd "C-x b") 'helm-resume-previous-session-after-quit)
(define-key map (kbd "C-x C-b") 'helm-resume-list-buffers-after-quit)
(helm-define-key-with-subkeys map (kbd "C-c n") ?n 'helm-run-cycle-resume)
;; Disable `file-cache-minibuffer-complete'.
(define-key map (kbd "<C-tab>") 'undefined)
;; Multi keys
(define-key map (kbd "C-t") 'helm-toggle-resplit-and-swap-windows)
;; Debugging command
(define-key map (kbd "C-h C-d") 'undefined)
(define-key map (kbd "C-h C-d") 'helm-enable-or-switch-to-debug)
(define-key map (kbd "C-h c") 'helm-customize-group)
;; Allow to eval keymap without errors.
(define-key map [f1] nil)
(define-key map (kbd "C-h C-h") 'undefined)
(define-key map (kbd "C-h h") 'undefined)
(helm-define-key-with-subkeys map
(kbd "C-w") ?\C-w 'helm-yank-text-at-point
'((?\C-_ . helm-undo-yank-text-at-point)))
;; Use `describe-mode' key in `global-map'.
(cl-dolist (k (where-is-internal 'describe-mode global-map))
(define-key map k 'helm-help))
(define-key map (kbd "C-c ?") 'helm-help)
;; Bind all actions from 1 to 12 to their corresponding nth index+1.
(cl-loop for n from 0 to 12 do
(define-key map (kbd (format "<f%s>" (1+ n)))
`(lambda ()
(helm-select-nth-action ,n))))
"Keymap for helm.")
(defun helm-customize-group ()
"Jump to customization group of current source.
Default to `helm' when group is not defined in source."
(helm-run-after-exit 'customize-group (helm-attr 'group)))
(put 'helm-customize-group 'helm-only t)
(defun helm--action-at-nth-set-fn-1 (value &optional negative)
(cl-loop for n from 1 to 9
for key = (format value n)
for sym = (make-symbol (format "helm-execute-selection-action-at-nth-+%d" n))
for fn = `(lambda ()
(helm-execute-selection-action-at-nth ,(if negative (- n) n)))
do (progn
(defalias sym fn)
(define-key helm-map (kbd key) sym))))
(defun helm--action-at-nth-set-fn- (var val)
(set var val)
(helm--action-at-nth-set-fn-1 val 'negative))
(defun helm--action-at-nth-set-fn+ (var val)
(set var val)
(helm--action-at-nth-set-fn-1 val))
(defcustom helm-action-at-nth-negative-prefix-key "C-x %d"
"The prefix key to execute default action on nth <-n> candidate.
This is a format spec where %d will be replaced by the candidate
NOTE: `setq' have no effect until you restart emacs, use customize for
immediate effect."
:group 'helm
:type 'string
:set #'helm--action-at-nth-set-fn-)
(defcustom helm-action-at-nth-positive-prefix-key "C-c %d"
"The prefix key to execute default action on nth <+n> candidate.
This is a format spec where %d will be replaced by the candidate
NOTE: `setq' have no effect until you restart emacs, use customize for
immediate effect."
:group 'helm
:type 'string
:set #'helm--action-at-nth-set-fn+)
(defgroup helm nil
"Open helm."
:prefix "helm-" :group 'convenience)
(defcustom helm-completion-window-scroll-margin 5
" `scroll-margin' to use for helm completion window.
Set to 0 to disable.
NOTE: This has no effect when `helm-display-source-at-screen-top'
id is non-`nil'."
:group 'helm
:type 'integer)
(defcustom helm-display-source-at-screen-top t
"Display candidates at the top of screen.
This happens with `helm-next-source' and `helm-previous-source'.
NOTE: When non-`nil' (default), disable `helm-completion-window-scroll-margin'."
:group 'helm
:type 'boolean)
(defcustom helm-candidate-number-limit 100
"Global limit for number of candidates displayed.
When the pattern is empty, the number of candidates shown will be
as set here instead of the entire list, which may be hundreds or
thousands. Since narrowing and filtering rapidly reduces
available candidates, having a small list will keep the interface
Set this value to nil for no limit."
:group 'helm
:type '(choice (const :tag "Disabled" nil) integer))
(defcustom helm-input-idle-delay 0.01
"Idle time before updating, specified in seconds."
:group 'helm
:type 'float)
(defcustom helm-exit-idle-delay 0
"Idle time before exiting minibuffer while helm is updating.
Has no affect when helm-buffer is up to date \(i.e exit without
delay in this condition\)."
:group 'helm
:type 'float)
(defcustom helm-full-frame nil
"Use current window for showing candidates.
If t, then Helm does not pop-up new window."
:group 'helm
:type 'boolean)
(defvaralias 'helm-samewindow 'helm-full-frame)
(make-obsolete-variable 'helm-samewindow 'helm-full-frame "")
(defcustom helm-candidate-separator
"Candidates separator of `multiline' source."
:group 'helm
:type 'string)
(defcustom helm-save-configuration-functions
'(set-window-configuration . current-window-configuration)
"Functions used to restore or save configurations for frames and windows.
Specified as a pair of functions, where car is the restore function and cdr
is the save function.
To save and restore frame configuration, set this variable to
'\(set-frame-configuration . current-frame-configuration\)
NOTE: This may not work properly with own-frame minibuffer
settings. Older versions saves/restores frame configuration, but
the default has changed now to avoid flickering."
:group 'helm
:type 'sexp)
(defcustom helm-display-function 'helm-default-display-buffer
"Function used to display `helm-buffer'.
Local value in `helm-buffer' will take precedence on this default
value. Commands that are in `helm-commands-using-frame' will have
`helm-buffer' displayed in frame, `helm-display-function' being
If no local value found and current command is not one of
`helm-commands-using-frame' use this default value.
Function in charge of deciding which value use is
To set it locally to `helm-buffer' in helm sources use
`helm-set-local-variable' in init function or use
:display-function slot in `helm' call."
:group 'helm
:type 'symbol)
(defcustom helm-case-fold-search 'smart
"Adds 'smart' option to `case-fold-search'.
Smart option ignores case for searches as long as there are no
upper case characters in the pattern.
Use nil or t to turn off smart behavior and use
`case-fold-search' behavior.
Default is smart.
NOTE: Case fold search has no effect when searching asynchronous
sources, which rely on customized features implemented directly
into their execution process. See helm-grep.el for an example."
:group 'helm
:type '(choice (const :tag "Ignore case" t)
(const :tag "Respect case" nil)
(other :tag "Smart" 'smart)))
(defcustom helm-file-name-case-fold-search
(if (memq system-type
'(cygwin windows-nt ms-dos darwin))
"Local setting of `helm-case-fold-search' for reading filenames.
See `helm-case-fold-search' for more info."
:group 'helm
:type 'symbol)
(defcustom helm-reuse-last-window-split-state nil
"Use the same state of window split, vertical or horizontal.
`helm-toggle-resplit-window' for the next helm session will use
the same window scheme as the previous session unless
`helm-split-window-default-side' is 'same or 'other."
:group 'helm
:type 'boolean)
(defcustom helm-split-window-preferred-function 'helm-split-window-default-fn
"Default function used for splitting window."
:group 'helm
:type 'function)
(defcustom helm-split-window-default-side 'below
"The default side to display `helm-buffer'.
Must be one acceptable arg for `split-window' SIDE,
that is `below', `above', `left' or `right'.
Other acceptable values are `same' which always display
`helm-buffer' in current window and `other' that display
`helm-buffer' below if only one window or in
`other-window-for-scrolling' when available.
A nil value has same effect as `below'.
If `helm-full-frame' is non-`nil', it take precedence over this setting.
See also `helm-split-window-inside-p' and `helm-always-two-windows' that
take precedence over this.
NOTE: this have no effect if `helm-split-window-preferred-function' is not
`helm-split-window-default-fn' unless this new function can handle this."
:group 'helm
:type 'symbol)
(defcustom helm-display-buffer-default-height nil
"Initial height of `helm-buffer', specified as an integer or a function.
The function should take one arg and the responsibility for
re-sizing the window; function's return value is ignored.
Note that this have no effect when the split is vertical.
See `display-buffer' for more info."
:group 'helm
:type '(choice integer function))
(defcustom helm-display-buffer-default-width nil
"Initial width of `helm-buffer', specified as an integer or a function.
The function should take one arg and the responsibility for
re-sizing the window; function's return value is ignored.
Note that this have no effect when the split is horizontal.
See `display-buffer' for more info."
:group 'helm
:type '(choice integer function))
(defcustom helm-split-window-inside-p nil
"Forces split inside selected window when non-`nil'.
See also `helm-split-window-default-side'.
NOTE: this has no effect if
`helm-split-window-preferred-function' is not
`helm-split-window-default-fn' unless this new function can
handle this."
:group 'helm
:type 'boolean)
(defvaralias 'helm-split-window-in-side-p 'helm-split-window-inside-p)
(make-obsolete-variable 'helm-split-window-in-side-p 'helm-split-window-inside-p "2.8.6")
(defcustom helm-always-two-windows nil
"When non-`nil' helm uses two windows in this frame.
To display `helm-buffer' in one window and `helm-current-buffer'
in the other.
Note: this has no effect when `helm-split-window-inside-p' is non-`nil',
or when `helm-split-window-default-side' is set to 'same.
When `helm-autoresize-mode' is enabled, setting this to nil
will have no effect.
Also when non-`nil' it overrides the effect of `helm-split-window-default-side'
set to `other'."
:group 'helm
:type 'boolean)
(defcustom helm-sources-using-default-as-input '(helm-source-imenu
"List of helm sources that need to use `helm--maybe-use-default-as-input'.
When a source is a member of this list, default `thing-at-point'
will be used as input."
:group 'helm
:type '(repeat (choice symbol)))
(defcustom helm-delete-minibuffer-contents-from-point t
"When non-`nil', `helm-delete-minibuffer-contents' delete region from `point'.
Otherwise delete `minibuffer-contents'.
See documentation for `helm-delete-minibuffer-contents'."
:group 'helm
:type 'boolean)
(defcustom helm-follow-mode-persistent nil
"When non-`nil', save last state of `helm-follow-mode' for the next emacs sessions.
Each time you turn on or off `helm-follow-mode', the current source name will be stored
or removed from `helm-source-names-using-follow'.
Note that this may be disabled in some places where it is unsafe to use
because persistent action is changing according to context."
:group 'helm
:type 'boolean)
(defcustom helm-source-names-using-follow nil
"A list of source names to have follow enabled.
This list of source names will be used only
when `helm-follow-mode-persistent' is non-nil.
You don't have to customize this yourself unless you really want and
know what you are doing, instead just set
`helm-follow-mode-persistent' to non-nil and as soon you turn on or
off `helm-follow-mode' (C-c C-f) in a source, helm will save or remove
source name in this variable."
:group 'helm
:type '(repeat (choice string)))
(defcustom helm-prevent-escaping-from-minibuffer t
"Prevent escaping from minibuffer with `other-window' during the helm session."
:group 'helm
:type 'boolean)
(defcustom helm-allow-mouse nil
"Allow mouse usage during the helm session when non-nil.
Note that this also allow moving out of minibuffer when clicking
outside of `helm-buffer', up to you to get back to helm by clicking
back in `helm-buffer' of minibuffer."
:group 'helm
:type 'boolean)
(defcustom helm-move-to-line-cycle-in-source nil
"Cycle to the beginning or end of the list after reaching the bottom or top.
This applies when using `helm-next/previous-line'."
:group 'helm
:type 'boolean)
(defcustom helm-fuzzy-match-fn 'helm-fuzzy-match
"The function for fuzzy matching in `helm-source-sync' based sources."
:group 'helm
:type 'function)
(defcustom helm-fuzzy-search-fn 'helm-fuzzy-search
"The function for fuzzy matching in `helm-source-in-buffer' based sources."
:group 'helm
:type 'function)
(defcustom helm-fuzzy-sort-fn 'helm-fuzzy-matching-default-sort-fn
"The sort transformer function used in fuzzy matching.
When nil, sorting is not done."
:group 'helm
:type 'function)
(defcustom helm-fuzzy-matching-highlight-fn 'helm-fuzzy-default-highlight-match
"The function to highlight fuzzy matches.
When nil, no highlighting is done."
:group 'helm
:type 'function)
(defcustom helm-autoresize-max-height 40
"Specifies maximum height and defaults to percent of helm window's frame height.
See `fit-window-to-buffer' for more infos."
:group 'helm
:type 'integer)
(defcustom helm-autoresize-min-height 10
"Specifies minimum height and defaults to percent of helm window's frame height.
If nil, `window-min-height' is used.
See `fit-window-to-buffer' for details."
:group 'helm
:type 'integer)
(defcustom helm-input-method-verbose-flag nil
"The default value for `input-method-verbose-flag' used in helm minibuffer.
It is nil by default, which does not turn off input method. Helm
updates and exits without interruption -- necessary for complex methods.
If set to any other value as per `input-method-verbose-flag',
then use `C-\\' to disable the `current-input-method' to exit or update helm"
:group 'helm
:type '(radio :tag "A flag to control extra guidance for input methods in helm."
(const :tag "Never provide guidance" nil)
(const :tag "Always provide guidance" t)
(const :tag "Provide guidance only for complex methods" complex-only)))
(defcustom helm-display-header-line t
"Display header-line when non nil."
:group 'helm
:type 'boolean)
(defcustom helm-inherit-input-method t
"Inherit `current-input-method' from `current-buffer' when non-`nil'.
The default is to enable this by default and then toggle
:group 'helm
:type 'boolean)
(defcustom helm-echo-input-in-header-line nil
"Send current input in header-line when non-nil."
:group 'helm
:type 'boolean)
(defcustom helm-header-line-space-before-prompt 'left-fringe
"Specify the space before prompt in header-line.
This will be used when `helm-echo-input-in-header-line' is non-nil.
Value can be one of the symbols 'left-fringe or 'left-margin or an
integer specifying the number of spaces before prompt.
Note that on input longer that `window-width' the continuation string
will be shown on left side of window without taking care of this."
:group 'helm
:type '(choice
(const :tag "Fringe" 'left-fringe)
(const :tag "Margin" 'left-margin))
(defcustom helm-tramp-connection-min-time-diff 5
"Value of `tramp-connection-min-time-diff' for helm remote processes.
If set to zero helm remote processes are not delayed.
Setting this to a value less than 5 or disabling it with a zero value
is risky, however on emacs versions starting at 24.5 it seems
it is now possible to disable it.
Anyway at any time in helm you can suspend your processes while typing
by hitting \\<helm-map> `\\[helm-toggle-suspend-update]'.
Only async sources than use a sentinel calling
`helm-process-deferred-sentinel-hook' are affected by this."
:type 'integer
:group 'helm)
(defcustom helm-debug-root-directory nil
"When non-`nil', saves helm log messages to a file in this directory.
When `nil' log messages are saved to a buffer instead.
Log message are saved only when `helm-debug' is non-nil, so setting this
doesn't enable debugging by itself.
See `helm-log-save-maybe' for more info."
:type 'string
:group 'helm)
(defcustom helm-show-action-window-other-window nil
"Show action buffer beside `helm-buffer' when non-nil.
If nil don't split and replace helm-buffer by the action buffer
in same window.
If left display the action buffer at the left of helm-buffer.
If right or any other value, split at right.
Note that this may not fit well with some helm window configurations,
so it have only effect when `helm-always-two-windows' is non-nil."
:group 'helm
:type '(choice
(const :tag "Split at left" left)
(const :tag "Don't split" nil)
(other :tag "Split at right" right)))
(defcustom helm-cycle-resume-delay 1.0
"Delay used before resuming in `helm-run-cycle-resume'."
:type 'float
:group 'helm)
(defcustom helm-display-buffer-width 60
"Frame width when displaying helm-buffer in own frame."
:group 'helm
:type 'integer)
(defcustom helm-display-buffer-height 20
"Frame height when displaying helm-buffer in own frame."
:group 'helm
:type 'integer)
(defcustom helm-display-buffer-reuse-frame nil
"When non nil helm frame is not deleted and reused in next sessions.
Probably you don't need to change this unless you use emacs-26+ where
frame displaying is much more slower than on emacs-24/25 series (emacs
:group 'helm
:type 'boolean)
(defcustom helm-commands-using-frame nil
"A list of commands where `helm-buffer' is displayed in a frame."
:group 'helm
:type '(repeat symbol))
(defcustom helm-actions-inherit-frame-settings nil
"Actions inherit frame settings of initial command when non nil.
The actions running from commands that are in
`helm-commands-using-frame' that are themselves running helm will have
a frame to display their `helm-buffer' when non nil."
:group 'helm
:type 'boolean)
(defcustom helm-use-undecorated-frame-option nil
"Display helm frame undecorated when non nil.
This option have no effect with emacs versions lower than 26."
:group 'helm
:type 'boolean)
;;; Faces
(defgroup helm-faces nil
"Customize the appearance of helm."
:prefix "helm-"
:group 'faces
:group 'helm)
(defface helm-source-header
'((((background dark))
:background "#22083397778B"
:foreground "white"
:weight bold :height 1.3 :family "Sans Serif")
(((background light))
:background "#abd7f0"
:foreground "black"
:weight bold :height 1.3 :family "Sans Serif"))
"Face for source header in the helm buffer."
:group 'helm-faces)
(defface helm-visible-mark
'((((min-colors 88) (background dark))
(:background "green1" :foreground "black"))
(((background dark))
(:background "green" :foreground "black"))
(((background light)) :background "#d1f5ea")
(((min-colors 88))
(:background "green1"))
(t (:background "green")))
"Face for visible mark."
:group 'helm-faces)
(defface helm-header
'((t (:inherit header-line)))
"Face for header lines in the helm buffer."
:group 'helm-faces)
(defface helm-candidate-number
'((((background dark)) :background "Yellow" :foreground "black")
(((background light)) :background "#faffb5" :foreground "black"))
"Face for candidate number in mode-line."
:group 'helm-faces)
(defface helm-candidate-number-suspended
'((t (:inherit helm-candidate-number :inverse-video t)))
"Face for candidate number in mode-line when helm is suspended."
:group 'helm-faces)
(defface helm-selection
'((((background dark)) :background "ForestGreen"
:distant-foreground "black")
(((background light)) :background "#b5ffd1"
:distant-foreground "black"))
"Face for currently selected item in the helm buffer."
:group 'helm-faces)
(defface helm-separator
'((((background dark)) :foreground "red")
(((background light)) :foreground "#ffbfb5"))
"Face for multiline source separator."
:group 'helm-faces)
(defface helm-action
'((t (:underline t)))
"Face for action lines in the helm action buffer."
:group 'helm-faces)
(defface helm-prefarg
'((((background dark)) :foreground "green")
(((background light)) :foreground "red"))
"Face for showing prefix arg in mode-line."
:group 'helm-faces)
(defface helm-match
'((((background light)) :foreground "#b00000")
(((background dark)) :foreground "gold1"))
"Face used to highlight matches."
:group 'helm-faces)
(defface helm-header-line-left-margin
'((t (:foreground "black" :background "yellow")))
"Face used to highlight helm-header sign in left-margin."
:group 'helm-faces)
;;; Variables.
(defvar helm-selection-overlay nil
"Overlay used to highlight the currently selected item.")
(defvar helm-async-processes nil
"List of information about asynchronous processes managed by helm.")
(defvar helm-before-initialize-hook nil
"Runs before helm initialization.
This hook runs before init functions in `helm-sources', which is
before creation of `helm-buffer'. Set local variables for
`helm-buffer' that need a value from `current-buffer' with
(defvar helm-after-initialize-hook nil
"Runs after helm initialization.
This hook runs after `helm-buffer' is created but not from
`helm-buffer'. The hook needs to specify in which buffer to run.")
(defvaralias 'helm-update-hook 'helm-after-update-hook)
(make-obsolete-variable 'helm-update-hook 'helm-after-update-hook "1.9.9")
(defvar helm-after-update-hook nil
"Runs after updating the helm buffer with the new input pattern.")
(defvar helm-cleanup-hook nil
"Runs after exiting the minibuffer and before performing an
This hook runs even if helm exits the minibuffer abnormally (e.g.
via `helm-keyboard-quit').")
(defvar helm-select-action-hook nil
"Runs when opening the action buffer.")
(defvar helm-before-action-hook nil
"Runs before executing action.
Unlike `helm-cleanup-hook', this hook runs before helm closes the
minibuffer and also before performing an action.")
(defvar helm-after-action-hook nil
"Runs after executing action.")
(defvar helm-exit-minibuffer-hook nil
"Runs just before exiting the minibuffer.
This hook runs when helm exits the minibuffer normally (e.g. via
candidate selection), but does NOT run if helm exits the
minibuffer abnormally (e.g. via `helm-keyboard-quit').")
(defvar helm-after-persistent-action-hook nil
"Runs after executing persistent action.")
(defvar helm-move-selection-before-hook nil
"Runs before moving selection in `helm-buffer'.")
(defvar helm-move-selection-after-hook nil
"Runs after moving selection in `helm-buffer'.")
(defvar helm-after-preselection-hook nil
"Runs after pre-selection in `helm-buffer'.")
(defvar helm-window-configuration-hook nil
"Runs when switching to and from the action buffer.")
(defvar helm-execute-action-at-once-if-one nil
"When non--nil executes the default action and then exits if only one candidate.
If symbol 'current-source is given as value exit if only one candidate
in current source.
This variable accepts a function with no args that should returns a boolean
value or 'current-source.")
(defvar helm-quit-if-no-candidate nil
"When non-`nil', quits if there are no candidates.
This variable accepts a function.")
(defvar helm-debug-variables nil
"A list of helm variables that `helm-debug-output' displays.
If `nil', `helm-debug-output' includes only variables with
`helm-' prefixes.")
(defvar helm-debug-buffer "*Debug Helm Log*")
(defvar helm-debug nil
"If non-`nil', write log message to `helm-debug-buffer'.
Default is `nil', which disables writing log messages because the
size of `helm-debug-buffer' grows quickly.")
(defvar helm-mode-line-string "\
\\[helm-help]:Help \
\\[helm-select-action]:Act \
f1/f2/f-n:NthAct \
"Help string displayed by helm in the mode-line.
It is either a string or a list of two string arguments where the
first string is the name and the second string is displayed in
the mode-line. When `nil', uses default `mode-line-format'.")
(defvar helm-minibuffer-set-up-hook nil
"Hook that runs at minibuffer initialization.
A hook useful for modifying minibuffer settings in helm.
An example that hides the minibuffer when using
(add-hook 'helm-minibuffer-set-up-hook #'helm-hide-minibuffer-maybe)
Note that we check `helm-echo-input-in-header-line' value
from `helm-buffer' which allow detecting possible local
value of this var.")
(defvar helm-help-message
"* Helm Generic Help
** Basics
Helm narrows down the list of candidates as you type a filter pattern.
Helm accepts multiple space-separated patterns.
Helm also supports fuzzy matching in some places when specified.
Helm generally uses familiar Emacs keys to navigate the list.
Here follow some of the less obvious bindings:
- `\\[helm-maybe-exit-minibuffer]' selects the candidate from the list, executes the default action
upon exiting the Helm session.
- `\\[helm-execute-persistent-action]' executes the default action but without exiting the Helm session.
Not all sources support this.
- `\\[helm-select-action]' displays a list of actions available on current candidate or all marked candidates.
The default binding <tab> is ordinarily used for completion, but that would be
redundant since Helm completes upon every character entered in the prompt.
See [[][Helm wiki]].
Note: In addition to the default actions list, additional actions appear
depending of the type of the selected candidate(s). They are called filtered
** Helm mode
`helm-mode' toggles Helm completion in native Emacs functions,
so when you turn `helm-mode' on, commands like `switch-to-buffer' will use
Helm completion instead of the usual Emacs completion buffer.
*** What gets or does not get \"helmized\" when `helm-mode' is enabled?
Helm provides generic completion on all Emacs functions using `completing-read',
`completion-in-region' and their derivatives, e.g. `read-file-name'. Helm
exposes a user variable to control which function to use for a specific Emacs
command: `helm-completing-read-handlers-alist'. If the function for a specific
command is nil, it turns off Helm completion. See the variable documentation
for more infos.
*** Helm functions vs helmized Emacs functions
While there are Helm functions that perform the same completion as other
helmized Emacs functions, e.g. `switch-to-buffer' and `helm-buffers-list', the
native Helm functions like `helm-buffers-list' can receive new features, the
allow marking candidates, they have several actions, etc. Whereas the helmized
Emacs functions only have Helm completion, one action and no more then Emacs can
provide for this function. This is the intended behavior.
Generally you are better off using the native Helm command
than the helmized Emacs equivalent.
** Helm help
\\[helm-documentation]: Show all helm documentations concatenated in one org file.
From a Helm session, just hit \\<helm-map>\\[helm-help] to have the
documentation for the current source followed by the global Helm documentation.
While in the help buffer, most of the regular keybindings are available in an
Emacs buffers; the most important ones are shown in minibuffer. However due to
the implementation restrictions, no regular Emacs keymap is used (it runs in a
loop when reading the help buffer) they are hardcoded and not modifiable.
The hard-coded documentation bindings are:
| Key | Alternative keys | Command |
| C-v | Space next | Scroll up |
| M-v | b prior | Scroll down |
| C-s | | Isearch forward |
| C-r | | Isearch backward |
| C-a | | Beginning of line |
| C-e | | End of line |
| C-f | right | Forward char |
| C-b | left | Backward char |
| C-n | down | Next line |
| C-p | up | Previous line |
| M-a | | Backward sentence |
| M-e | | Forward sentence |
| M-f | | Forward word |
| M-b | | Backward word |
| M-> | | End of buffer |
| M-< | | Beginning of buffer |
| C-<SPACE> | | Toggle mark |
| TAB | | Org cycle |
| M-<TAB> | | Toggle visibility |
| M-w | | Copy region |
| q | | Quit |
** Customize Helm
Helm provides a lot of user variables for extensive customization.
From any Helm session, type \\<helm-map>\\[helm-customize-group] to jump to the current source `custom' group.
Helm also has a special group for faces you can access via `M-x customize-group RET helm-faces'.
Note: Some sources may not have their group set and default to the `helm' group.
** Helm's basic operations and default key bindings
| Key | Alternative Keys | Command |
| C-p | Up | Previous line |
| C-n | Down | Next line |
| M-v | prior | Previous page |
| C-v | next | Next page |
| Enter | | Execute first (default) action / Select |
| M-< | | First line |
| M-> | | Last line |
| C-M-S-v | M-prior, C-M-y | Previous page (other-window) |
| C-M-v | M-next | Next page (other-window) |
| Tab | C-i | Show action list |
| Left | | Previous source |
| Right | C-o | Next source |
| C-k | | Delete pattern (with prefix arg delete from point to end or all [1]) |
| C-j | C-z | Persistent action (Execute and keep Helm session) |
\[1] Delete from point to end or all depending on the value of
** Shortcuts for n-th action
f1-f12: Execute n-th action where n is 1 to 12.
** Shortcuts for executing the default action on the n-th candidate
C-x <n>: Execute default action on the n-th candidate before currently selected candidate.
C-c <n>: Execute default action on the n-th candidate after current selected candidate.
\"n\" is limited to 1-9. For larger jumps use other navigation keys. Helm does
not display line numbers by default: enable them with the
\[[][linum-relative]] package and
** Mouse control in Helm
A basic support for the mouse is provided when the user sets `helm-allow-mouse' to non-nil.
- mouse-1 selects the candidate.
- mouse-2 executes the default action on selected candidate.
- mouse-3 pops up the action menu.
Note: When mouse control is enabled in Helm, it also lets you click around and lose
the minibuffer focus: you'll have to click on the Helm buffer or the minibuffer
to retrieve control of your Helm session.
** Marked candidates
You can mark candidates to execute an action on all of them instead of the
current selected candidate only. (See bindings below.) Most Helm actions
operate on marked candidates unless candidate-marking is explicitely forbidden
for a specific source.
- To mark/unmark a candidate, use \\[helm-toggle-visible-mark]. (See bindings below.)
With a numeric prefix arg mark ARG candidates forward, if ARG is negative
mark ARG candidates backward.
- To mark all visible unmarked candidates at once in current source use \\[helm-mark-all].
With a prefix argument, mark all candidates in all sources.
- To unmark all visible marked candidates at once use \\[helm-unmark-all].
- To mark/unmark all candidates at once use \\[helm-toggle-all-marks].
With a prefix argument, mark/unmark all candidates in all sources.
Note: When multiple candidates are selected across different sources, only the
candidates of the current source will be used when executing most actions (as
different sources can have different actions). Some actions support
multi-source marking however.
** Follow candidates
When `helm-follow-mode' is on (\\<helm-map>\\[helm-follow-mode] to toggle it),
moving up and down the Helm session or updating the list of candidates will
automatically execute the persistent-action as specified for the current source.
If `helm-follow-mode-persistent' is non-nil, the state of the mode will be
restored for the following Helm sessions.
If you just want to follow candidates occasionally without enabling
`helm-follow-mode', you can use \\<helm-map>\\[helm-follow-action-forward] or \\[helm-follow-action-backward] instead.
Conversely, when `helm-follow-mode' is enabled, those commands
go to previous/next line without executing the persistent action.
** Frequently Used Commands
\\[helm-toggle-resplit-and-swap-windows]\t\tToggle vertical/horizontal split on first hit and swap Helm window on second hit.
\\[helm-quit-and-find-file]\t\tDrop into `helm-find-files'.
\\[helm-kill-selection-and-quit]\t\tKill display value of candidate and quit (with prefix arg, kill the real value).
\\[helm-yank-selection]\t\tYank current selection into pattern.
\\[helm-copy-to-buffer]\t\tCopy selected candidate at point in current buffer.
\\[helm-follow-mode]\t\tToggle automatic execution of persistent action.
\\[helm-follow-action-forward]\tRun persistent action then select next line.
\\[helm-follow-action-backward]\t\tRun persistent action then select previous line.
\\[helm-refresh]\t\tRecalculate and redisplay candidates.
\\[helm-toggle-suspend-update]\t\tToggle candidate updates.
** Moving in `helm-buffer'
You can move in `helm-buffer' with the usual commands used in Emacs:
\(\\<helm-map>\\[helm-next-line], \\<helm-map>\\[helm-previous-line], etc. See above basic commands.
When `helm-buffer' contains more than one source, change source with \\<helm-map>\\[helm-next-source].
Note: When reaching the end of a source, \\<helm-map>\\[helm-next-line] will *not* go to the next source unless
variable `helm-move-to-line-cycle-in-source' is non-nil, so you will have to use \\<helm-map>\\[helm-next-source].
** Resume previous session from current Helm session
You can use `C-c n' (`helm-run-cycle-resume') to cycle in resumables sources.
`C-c n' is a special key set with `helm-define-key-with-subkeys' which, after pressing it, allows you
to keep cycling with further `n'.
Tip: You can bound the same key in `global-map' to `helm-cycle-resume'
with `helm-define-key-with-subkeys' to let you transparently cycle
sessions, Helm fired up or not.
You can also bind the cycling commands to single key presses (e.g. `S-<f1>') this time
with a simple `define-key'. (Note that `S-<f1>' is not available in terminals.)
Note: `helm-define-key-with-subkeys' is available only once Helm is loaded.
You can also use \\<helm-map>\\[helm-resume-previous-session-after-quit] to resume
the previous session, or \\<helm-map>\\[helm-resume-list-buffers-after-quit]
to have completion on all resumable buffers.
** Global commands
*** Resume Helm session from outside Helm
\\<global-map>\\[helm-resume] revives the last `helm' session. Binding a key to
this command will greatly improve `helm' interactivity, e.g. when quitting Helm
You can call \\<global-map>\\[helm-resume] with a prefix argument to choose
\(with completion!) which session you'd like to resume. You can also cycle in
these sources with `helm-cycle-resume' (see above).
** Debugging Helm
Helm exposes the special variable `helm-debug': setting it to non-nil
will enable Helm logging in a special outline-mode buffer.
Helm resets the variable to nil at the end of each session.
For convenience, \\<helm-map>\\[helm-enable-or-switch-to-debug]
allows you to turn on debugging for this session only.
To avoid accumulating log entries while you are typing patterns, you can use
\\<helm-map>\\[helm-toggle-suspend-update] to turn off updating. When you
are ready turn it on again to resume logging.
Once you exit your Helm session you can access the debug buffer with
`helm-debug-open-last-log'. It is possible to save logs to dated files when
`helm-debug-root-directory' is set to a valid directory.
Note: Be aware that Helm log buffers grow really fast, so use `helm-debug' only
when needed.
** Writing your own Helm sources
Writing simple sources for your own usage is easy. When calling the `helm'
function, the sources are added the :sources slot which can be a symbol or a
list of sources. Sources can be built with different EIEIO classes depending
what you want to do. To simplify this, several `helm-build-*' macros are
provided. Below, simple examples to start with.
We will not go further here, see [[][Helm wiki]] and the source
code for more information and more complex exapmles.
#+begin_src elisp
;; Candidates are stored in a list.
(helm :sources (helm-build-sync-source \"test\"
;; A function can be used as well
;; to provide candidates.
:candidates '(\"foo\" \"bar\" \"baz\"))
:buffer \"*helm test*\")
;; Candidates are stored in a buffer.
;; Generally faster but doesn't allow a dynamic updating
;; of the candidates list i.e the list is fixed on start.
(helm :sources (helm-build-in-buffer-source \"test\"
:data '(\"foo\" \"bar\" \"baz\"))
:buffer \"*helm test*\")
** Helm Map
"Message string containing detailed help for `helm'.
It also accepts function or variable symbol.")
(defvar helm-autoresize-mode) ;; Undefined in `helm-default-display-buffer'.
(defvar helm-async-outer-limit-hook nil
"A hook that run in async sources when process output comes out of `candidate-number-limit'.
Should be set locally to `helm-buffer' with `helm-set-local-variable'.")
(defvar helm-quit-hook nil
"A hook that run when quitting helm.")
;;; Internal Variables
(defvar helm-source-filter nil
"A list of source names to be displayed.
Other sources won't appear in the search results.
If nil, no filtering is done.
Don't set this directly, use `helm-set-source-filter' during helm session
to modify it.")
(defvar helm-current-prefix-arg nil
"Record `current-prefix-arg' when exiting minibuffer.")
(defvar helm-saved-action nil
"Saved value of the currently selected action by key.")
(defvar helm-saved-current-source nil
"Value of the current source when the action list is shown.")
(defvar helm-compiled-sources nil
"Compiled version of `helm-sources'.")
(defvar helm-in-persistent-action nil
"Flag whether in persistent-action or not.")
(defvar helm-last-buffer nil
"`helm-buffer' of previously `helm' session.")
(defvar helm-saved-selection nil
"Value of the currently selected object when the action list is shown.")
(defvar helm-sources nil
"[INTERNAL] Value of current sources in use, a list.")
(defvar helm-buffer-file-name nil
"Variable `buffer-file-name' when `helm' is invoked.")
(defvar helm-candidate-cache (make-hash-table :test 'equal)
"Holds the available candidate within a single helm invocation.")
(defvar helm--candidate-buffer-alist nil)
(defvar helm-input ""
"The input typed in the candidates panel.")
(defvar helm-input-local nil
"Internal, store locally `helm-pattern' value for later use in `helm-resume'.")
(defvar helm--source-name nil)
(defvar helm-current-source nil)
(defvar helm-tick-hash (make-hash-table :test 'equal))
(defvar helm-issued-errors nil)
(defvar helm--last-log-file nil
"The name of the log file of the last helm session.")
(defvar helm--local-variables nil)
(defvar helm-split-window-state nil)
(defvar helm--window-side-state nil)
(defvar helm-selection-point nil)
(defvar helm-alive-p nil)
(defvar helm-visible-mark-overlays nil)
(defvar helm-update-blacklist-regexps '("^" "^ *" "$" "!" " " "\\b"
"\\<" "\\>" "\\_<" "\\_>" ".*"
"??" "?*" "*?" "?"))
(defvar helm--force-updating-p nil
"[INTERNAL] Don't use this in your programs.")
(defvar helm-exit-status 0
"Flag to inform if helm did exit or quit.
0 means helm did exit when executing an action.
1 means helm did quit with \\[keyboard-quit]
Knowing this exit-status could help restore a window config when helm aborts
in some special circumstances.
See `helm-exit-minibuffer' and `helm-keyboard-quit'.")
(defvar helm-minibuffer-confirm-state nil)
(defvar helm-quit nil)
(defvar helm-buffers nil
"Helm buffers listed in order of most recently used.")
(defvar helm-current-position nil
"Cons of \(point . window-start\) when `helm' is invoked.
`helm-current-buffer' uses this to restore position after
(defvar helm-last-frame-or-window-configuration nil
"Used to store window or frame configuration at helm start.")
(defvar helm-onewindow-p nil)
(defvar helm-types nil)
(defvar helm--mode-line-string-real nil) ; The string to display in mode-line.
(defvar helm-persistent-action-display-window nil)
(defvar helm-marked-candidates nil
"Marked candadates. List of \(source . real\) pair.")
(defvar helm--mode-line-display-prefarg nil)
(defvar helm--temp-follow-flag nil
"[INTERNAL] A simple flag to notify persistent action we are following.")
(defvar helm--reading-passwd-or-string nil)
(defvar helm--in-update nil)
(defvar helm--in-fuzzy nil)
(defvar helm--maybe-use-default-as-input nil
"Flag to notify the use of use-default-as-input.
Use only in let-bindings.
Use :default arg of `helm' as input to update display.
Note that if also :input is specified as `helm' arg, it will take
precedence on :default.")
(defvar helm--temp-hooks nil
"Store temporary hooks added by `with-helm-temp-hook'.")
(defvar helm-truncate-lines nil
"[Internal] Don't set this globally, it is used as a local var.")
(defvar helm--prompt nil)
(defvar helm--file-completion-sources
'("Find Files" "Read File Name")
"Sources that use the *find-files mechanism can be added here.
Sources generated by `helm-mode' don't need to be added here
because they are automatically added.
You should not modify this yourself unless you know what you are doing.")
(defvar helm--completing-file-name nil
"Non nil when `helm-read-file-name' is running.
Used for `helm-file-completion-source-p'.")
;; Same as `ffap-url-regexp' but keep it here to ensure `ffap-url-regexp' is not nil.
(defvar helm--url-regexp "\\`\\(news\\(post\\)?:\\|mailto:\\|file:\\|\\(ftp\\|https?\\|telnet\\|gopher\\|www\\|wais\\)://\\)")
(defvar helm--ignore-errors nil
"Flag to prevent helm popping up errors in candidates functions.
Should be set in candidates functions if needed, will be restored
at end of session.")
(defvar helm--action-prompt "Select action: ")
(defvar helm--cycle-resume-iterator nil)
(defvar helm--buffer-in-new-frame-p nil)
(defvar helm-initial-frame nil
"The selected frame before starting helm.")
(defvar helm-popup-frame nil
"The frame where helm is displayed.
This is only used when helm is using
`helm-display-buffer-in-own-frame' as `helm-display-function' and
`helm-display-buffer-reuse-frame' is non nil.")
(defvar helm--nested nil)
(defvar helm--last-frame-position nil)
;; Utility: logging
(defun helm-log (format-string &rest args)
"Log message `helm-debug' is non-`nil'.
Messages are written to the `helm-debug-buffer' buffer.
Argument FORMAT-STRING is a string to use with `format'.
Use optional arguments ARGS like in `format'."
(when helm-debug
(with-current-buffer (get-buffer-create helm-debug-buffer)
(let ((inhibit-read-only t))
(goto-char (point-max))
(insert (let ((tm (current-time)))
(format (concat (if (string-match "Start session" format-string)
"* " "** ")
"%s.%06d (%s)\n %s\n")
(format-time-string "%H:%M:%S" tm)
(nth 2 tm)
(apply #'format (cons format-string args)))))))))
(defun helm-log-run-hook (hook)
"Run HOOK like `run-hooks' but write these actions to helm log buffer."
(helm-log "Executing %s with value = %S" hook (symbol-value hook))
(helm-log "Executing %s with global value = %S" hook (default-value hook))
(run-hooks hook)
(helm-log "executed %s" hook))
(defun helm-log-get-current-function ()
"Get name of function that is calling `helm-log'.
The original idea is from `tramp-debug-message'."
(cl-loop with exclude-func-re = "^helm-\\(?:interpret\\|log\\|.*funcall\\)"
for btn from 1 to 40
for btf = (cl-second (backtrace-frame btn))
for fn = (if (symbolp btf) (symbol-name btf) "")
if (and (string-match "^helm" fn)
(not (string-match exclude-func-re fn)))
return fn))
(defun helm-log-error (&rest args)
"Accumulate error messages into `helm-issued-errors'.
ARGS are args given to `format'.
e.g (helm-log-error \"Error %s: %s\" (car err) (cdr err))."
(apply 'helm-log (concat "ERROR: " (car args)) (cdr args))
(let ((msg (apply 'format args)))
(unless (member msg helm-issued-errors)
(cl-pushnew msg helm-issued-errors :test 'equal))))
(defun helm-log-save-maybe ()
"Save log buffer if `helm-debug-root-directory' is set to a valid directory.
Messages are logged to a file named with todays date and time in this directory."
(when (and (stringp helm-debug-root-directory)
(file-directory-p helm-debug-root-directory)
(let ((logdir (expand-file-name (concat "helm-debug-"
(format-time-string "%Y%m%d"))
(make-directory logdir t)
(with-current-buffer (get-buffer-create helm-debug-buffer)
(write-region (point-min) (point-max)
(setq helm--last-log-file
(format-time-string "%Y%m%d-%H%M%S")
nil 'silent)
(setq helm-debug nil))
(defun helm-debug-open-last-log ()
"Open helm log file or buffer of last helm session."
(if helm--last-log-file
(find-file helm--last-log-file)
(outline-mode) (view-mode 1) (visual-line-mode 1))
(switch-to-buffer helm-debug-buffer)
(view-mode 1) (visual-line-mode 1)))
(defun helm-print-error-messages ()
"Print error messages in `helm-issued-errors'."
(and helm-issued-errors
(message "Helm issued errors: %s"
(mapconcat 'identity (reverse helm-issued-errors) "\n"))))
;; Test tools
(defmacro with-helm-time-after-update (&rest body)
(helm-with-gensyms (start-time time-elapsed)
`(let ((,start-time (float-time)) ,time-elapsed)
(add-hook 'helm-after-update-hook
(lambda ()
(setq ,time-elapsed (- (float-time) ,start-time))
(unwind-protect ,@body
(remove-hook 'helm-after-update-hook
(lambda ()
(setq ,time-elapsed (- (float-time) ,start-time))
;; Helm API
(defmacro with-helm-default-directory (directory &rest body)
(declare (indent 2) (debug t))
`(let ((default-directory (or (and ,directory
(file-name-as-directory ,directory))
(defun helm-default-directory ()
"Return the local value of `default-directory' in `helm-buffer'."
(buffer-local-value 'default-directory (get-buffer helm-buffer)))
(defmacro with-helm-temp-hook (hook &rest body)
"Execute temporarily BODY as a function for HOOK."
(declare (indent 1) (debug t))
(helm-with-gensyms (helm--hook)
(defun ,helm--hook ()
(progn ,@body)
(remove-hook ,hook (quote ,helm--hook))
(fmakunbound (quote ,helm--hook))))
(push (cons ',helm--hook ,hook) helm--temp-hooks)
(add-hook ,hook (quote ,helm--hook)))))
(defmacro with-helm-after-update-hook (&rest body)
"Execute BODY at end of `helm-update'."
(declare (indent 0) (debug t))
`(with-helm-temp-hook 'helm-after-update-hook ,@body))
(defmacro with-helm-alive-p (&rest body)
"Return error when BODY run outside helm context."
(declare (indent 0) (debug t))
(if helm-alive-p
(progn ,@body)
(error "Running helm command outside of context"))))
;;; helm-attributes
(defun helm-attr (attribute-name &optional source compute)
"Get the value of ATTRIBUTE-NAME of SRC.
If SRC is omitted, use current source.
If COMPUTE is non-`nil' compute value of ATTRIBUTE-NAME with
`helm-interpret-value'. COMPUTE can have also 'ignorefn as value, in
this case `helm-interpret-value' will return a function as value
unchanged, but will eval a symbol which is bound.
You can use `setf' to modify value of ATTRIBUTE-NAME unless COMPUTE is
specified, if attribute ATTRIBUTE-NAME is not found in SOURCE `setf'
will create new attribute ATTRIBUTE-NAME with specified value.
You can also use `helm-attrset' to modify ATTRIBUTE-NAME."
(declare (gv-setter
(lambda (val)
`(let* ((src (or ,source (helm-get-current-source)))
(attr (assq ,attribute-name src)))
(cl-assert (null ,compute) nil
"`setf' can't set the computed value of attribute `%s'"
(if attr
(setcdr attr ,val)
(and (setcdr src (cons (cons ,attribute-name ,val)
(cdr src)))
(let ((src (or source (helm-get-current-source))))
(helm-aif (assq attribute-name src)
(if compute
(helm-interpret-value (cdr it) src compute)
(cdr it)))))
(cl-defun helm-attrset (attribute-name value
(src (helm-get-current-source)))
"Set the value of ATTRIBUTE-NAME of source SRC to VALUE.
If ATTRIBUTE-NAME doesn't exists in source it is created with value VALUE..
If SRC is omitted, use current source.
If operation succeed, return value, otherwise nil.
Note that `setf' on `helm-attr' can be used instead of this function."
(setf (helm-attr attribute-name src) value))
(defun helm-add-action-to-source (name fn source &optional index)
"Add new action NAME linked to function FN to SOURCE.
Function FN should be a valid function that takes one arg i.e candidate,
argument NAME is a string that will appear in action menu
and SOURCE should be an existing helm source already loaded.
If INDEX is specified, action is added to the action list at INDEX,
otherwise added at end.
This allows users to add specific actions to an existing source
without modifying source code."
(let ((actions (helm-attr 'action source 'ignorefn))
(new-action (list (cons name fn))))
(when (functionp actions)
(setq actions (list (cons "Default action" actions))))
(helm-attrset 'action
(if index
(helm-append-at-nth actions new-action index)
(append actions new-action))
(defun helm-delete-action-from-source (action-or-name source)
ACTION-OR-NAME can either be the name of action or the symbol function
associated to name."
(let* ((actions (helm-attr 'action source 'ignorefn))
(del-action (if (symbolp action-or-name)
(rassoc action-or-name actions)
(assoc action-or-name actions))))
(helm-attrset 'action (delete del-action actions) source)))
(cl-defun helm-add-action-to-source-if (name fn source predicate
&optional (index 4) test-only)
"Add new action NAME linked to function FN to SOURCE.
Action NAME will be available when the current candidate matches PREDICATE.
This function adds an entry in the `action-transformer' attribute
of SOURCE (or creates one if not found).
Function PREDICATE must take one candidate as arg.
Function FN should be a valid function that takes one arg i.e. candidate,
argument NAME is a string that will appear in action menu
and SOURCE should be an existing helm source already loaded.
If INDEX is specified, action is added in action list at INDEX.
Value of INDEX should be always >=1, default to 4.
This allow user to add a specific `action-transformer'
to an existing source without modifying source code.
Add the action \"Byte compile file async\" linked to
function 'async-byte-compile-file to source `helm-source-find-files'
only when predicate helm-ff-candidates-lisp-p return non-`nil':
\(helm-add-action-to-source-if \"Byte compile file async\"
(let* ((actions (helm-attr 'action source 'ignorefn))
(action-transformers (helm-attr 'action-transformer source))
(new-action (list (cons name fn)))
(transformer (lambda (actions candidate)
(cond ((funcall predicate candidate)
actions new-action index))
(t actions)))))
(when (functionp actions)
(helm-attrset 'action (list (cons "Default action" actions)) source))
(when (or (symbolp action-transformers) (functionp action-transformers))
(setq action-transformers (list action-transformers)))
(if test-only ; debug
(delq nil (append (list transformer) action-transformers))
(helm-attrset 'action-transformer
(delq nil (append (list transformer) action-transformers))
:test 'equal)
;;; Source filter
(defun helm-set-source-filter (sources)
"Set the value of `helm-source-filter' to SOURCES and update.
This function sets a filter for helm sources and it may be
called while helm is running. It can be used to toggle
displaying of sources dynamically. For example, additional keys
can be bound into `helm-map' to display only the file-related
results if there are too many matches from other sources and
you're after files only:
Shift+F shows only file results from some sources:
\(define-key helm-map \"F\" 'helm-my-show-files-only)
\(defun helm-my-show-files-only ()
(helm-set-source-filter '(\"File Name History\"
\"Files from Current Directory\")))
Shift+A shows all results:
\(define-key helm-map \"A\" 'helm-my-show-all)
\(defun helm-my-show-all ()
(helm-set-source-filter nil))
The -my- part is added to avoid collisions with
existing Helm function names."
(let ((cur-disp-sel (helm-get-selection nil t)))
(set (make-local-variable 'helm-source-filter)
(helm--normalize-filter-sources sources))
(helm-log "helm-source-filter = %S" helm-source-filter)
;; Use force-update to run init/update functions.
(helm-force-update (and (stringp cur-disp-sel)
(regexp-quote cur-disp-sel))))))
(defun helm--normalize-filter-sources (sources)
(cl-loop for s in sources collect
(cl-typecase s
(symbol (assoc-default 'name (symbol-value s)))
(list (assoc-default 'name s))
(string s))))
(defun helm-set-sources (sources &optional no-init no-update)
"Set SOURCES during `helm' invocation.
If NO-INIT is non-`nil', skip executing init functions of SOURCES.
If NO-UPDATE is non-`nil', skip executing `helm-update'."
(with-current-buffer helm-buffer
(setq helm-compiled-sources nil
helm-sources sources)
(helm-log "helm-compiled-sources = %S" helm-compiled-sources)
(helm-log "helm-sources = %S" helm-sources))
(unless no-init (helm-funcall-foreach 'init))
(unless no-update (helm-update)))
(defun helm-get-sources ()
"Return compiled `helm-sources', which is memoized."
;; action
((helm-action-window) helm-sources)
;; memoized
;; first time
(setq helm-compiled-sources
(mapcar (lambda (source)
(if (listp source) source (symbol-value source)))
(helm-log "helm-compiled-sources = %S" helm-compiled-sources)))))
(defun helm-get-selection (&optional buffer force-display-part source)
"Return the currently selected item or nil.
if BUFFER is nil or unspecified, use helm-buffer as default value.
If FORCE-DISPLAY-PART is non-`nil', return the display string.
If FORCE-DISPLAY-PART value is 'withprop the display string is returned
with its properties."
(setq buffer (or buffer helm-buffer))
(unless (helm-empty-buffer-p buffer)
(with-current-buffer buffer
(let* ((disp-fn (if (eq force-display-part 'withprop)
(or (and (not force-display-part)
(get-text-property (overlay-start
;; It is needed to return properties of DISP in some case,
;; e.g for `helm-confirm-and-exit-minibuffer',
;; so use `buffer-substring' here when 'withprop is specified.
(let ((disp (funcall
(overlay-start helm-selection-overlay)
(1- (overlay-end helm-selection-overlay))))
(src (or source (helm-get-current-source))))
(helm-aif (and (not force-display-part)
(assoc-default 'display-to-real src))
(helm-funcall-with-source source it disp)
(unless (equal selection "")
(helm-log "selection = %S" selection)
(defun helm-get-actions-from-current-source (&optional source)
"Return the associated action for the selected candidate.
It is a function symbol \(sole action\) or list
of \(action-display . function\)."
(unless (helm-empty-buffer-p (helm-buffer-get))
(let ((src (helm-get-current-source)))
(helm-aif (helm-attr 'action-transformer)
(or source src) it
(helm-attr 'action nil 'ignorefn)
;; Check if the first given transformer
;; returns the same set of actions for each
;; candidate in marked candidates.
;; If so use the car of marked to determine
;; the set of actions, otherwise use the selection.
(if (cl-loop with marked = (helm-marked-candidates)
with act = (car (helm-mklist it))
with acts = (funcall act nil (car marked))
for c in marked
always (equal (funcall act nil c) acts))
(car (helm-marked-candidates))
(helm-get-selection nil nil src)))
(helm-attr 'action nil 'ignorefn)))))
(defun helm-get-current-source ()
"Return the source for the current selection.
Return nil when `helm-buffer' is empty."
(or helm-current-source
(or (get-text-property (point) 'helm-cur-source)
;; This is needed to not loose selection.
(goto-char (overlay-start helm-selection-overlay))
(let ((header-pos (or (helm-get-previous-header-pos)
;; Return nil when no--candidates.
(when header-pos
(cl-loop with source-name = (save-excursion
(goto-char header-pos)
for source in (helm-get-sources) thereis
(and (equal (assoc-default 'name source) source-name)
(defun helm-buffer-is-modified (buffer)
"Return non-`nil' when BUFFER is modified since `helm' was invoked."
(let* ((buf (get-buffer buffer))
(key (concat (buffer-name buf) "/" (helm-attr 'name)))
(source-tick (or (gethash key helm-tick-hash) 0))
(buffer-tick (buffer-chars-modified-tick buf))
(modifiedp (/= source-tick buffer-tick)))
(puthash key buffer-tick helm-tick-hash)
(helm-log "buffer = %S" buffer)
(helm-log "modifiedp = %S" modifiedp)
(defun helm-current-buffer-is-modified ()
"Check if `helm-current-buffer' is modified since `helm' was invoked."
(helm-buffer-is-modified helm-current-buffer))
(defun helm-run-after-exit (function &rest args)
"Execute FUNCTION with ARGS after exiting `helm'.
The action is to call FUNCTION with arguments ARGS.
Unlike `helm-exit-and-execute-action', this can be used
to call non--actions functions with any ARGS or no ARGS at all.
Use this on commands invoked from key-bindings, but not
on action functions invoked as action from the action menu,
i.e. functions called with RET."
(helm-log "function = %S" function)
(helm-log "args = %S" args)
(lambda (_candidate)
(apply function args))))
(defun helm-exit-and-execute-action (action)
"Exit current helm session and execute ACTION.
Argument ACTION is a function called with one arg (candidate)
and part of the actions of current source.
Use this on commands invoked from key-bindings, but not
on action functions invoked as action from the action menu,
i.e functions called with RET."
(setq helm-saved-action action)
(setq helm-saved-selection (or (helm-get-selection) ""))
(defalias 'helm-run-after-quit 'helm-run-after-exit)
(make-obsolete 'helm-run-after-quit 'helm-run-after-exit "1.7.7")
(defalias 'helm-quit-and-execute-action 'helm-exit-and-execute-action)
(make-obsolete 'helm-quit-and-execute-action 'helm-exit-and-execute-action "1.7.7")
(defun helm-interpret-value (value &optional source compute)
"Interpret VALUE as variable, function or literal and return it.
If VALUE is a function, call it with no arguments and return the value
unless COMPUTE value is 'ignorefn.
If SOURCE compute VALUE for this source.
If VALUE is a variable, return the value.
If VALUE is a symbol, but it is not a function or a variable, cause an error.
Otherwise, return VALUE itself."
(cond ((and source (functionp value) (not (eq compute 'ignorefn)))
(helm-funcall-with-source source value))
((and (functionp value) (not (eq compute 'ignorefn)))
(funcall value))
((and (symbolp value) (boundp value))
(symbol-value value))
((and (symbolp value) (not (functionp value)))
"helm-interpret-value: Symbol must be a function or a variable"))
(defun helm-set-local-variable (&rest args)
"Bind each pair in ARGS locally to `helm-buffer'.
Use this to set local vars before calling helm.
When used from an init or update function
(i.e when `helm-force-update' is running) the variables are set
using `make-local-variable' within the `helm-buffer'.
Usage: helm-set-local-variable ([VAR VALUE]...)
Just like `setq' except that the vars are not set sequentially.
IOW Don't use VALUE of previous VAR to set the VALUE of next VAR.
\(fn VAR VALUE ...)"
(if helm--force-updating-p
(cl-loop for i on args by #'cddr
do (set (make-local-variable (car i)) (cadr i))))
(setq helm--local-variables
(append (cl-loop for i on args by #'cddr
collect (cons (car i) (cadr i)))
;; API helper
(cl-defun helm-empty-buffer-p (&optional (buffer helm-buffer))
"Check if BUFFER have candidates.
Default value for BUFFER is `helm-buffer'."
(zerop (buffer-size (and buffer (get-buffer buffer)))))
(defun helm-empty-source-p ()
"Check if current source contains candidates.
This could happen when for example the last element of a source
was deleted and the candidates list not updated."
(when (helm-window)
(or (helm-empty-buffer-p)
(and (helm-end-of-source-p)
(eq (point-at-bol) (point-at-eol))
(forward-line -1)
;; Tools
(defun helm-funcall-with-source (source functions &rest args)
FUNCTIONS is either a symbol or a list of functions, each function being
applied on ARGS and called on the result of the precedent function.
Return the result of last function call."
(let ((helm--source-name (assoc-default 'name source))
(helm-current-source source)
(funs (if (functionp functions) (list functions) functions)))
(helm-log "helm--source-name = %S" helm--source-name)
(helm-log "functions = %S" functions)
(helm-log "args = %S" args)
(cl-loop with result
for fn in funs
do (setq result (apply fn args))
when (and args (cdr funs))
;; In filter functions, ARGS is a list of one or two elements where
;; the first element is the list of candidates and the second
;; a list containing the source.
;; When more than one fn, set the candidates list to what returns
;; this fn to compute the modified candidates with the next fn
;; and so on.
do (setcar args result)
finally return result)))
(defun helm-funcall-foreach (sym &optional sources)
"Call the associated function(s) to SYM for each source if any."
(let ((sources (or sources (helm-get-sources))))
(cl-dolist (source sources)
(helm-aif (assoc-default sym source)
(helm-funcall-with-source source it)))))
(defun helm-normalize-sources (sources)
"If SOURCES is only one source, make a list of one element."
(cond ((or (and sources (symbolp sources))
(and (listp sources) (assq 'name sources)))
(list sources))
(t helm-sources)))
(defun helm-get-candidate-number (&optional in-current-source)
"Return candidates number in `helm-buffer'.
If IN-CURRENT-SOURCE is provided return number of candidates of current source
(if (or (helm-empty-buffer-p)
(helm-aif (and in-current-source (helm-get-previous-header-pos))
(goto-char it)
(goto-char (point-min)))
(forward-line 1)
(if (helm-pos-multiline-p)
(cl-loop with count-multi = 1
while (and (not (if in-current-source
(forward-line 2)
(or (helm-pos-header-line-p) (eobp)))
(search-forward helm-candidate-separator nil t))
do (cl-incf count-multi)
finally return count-multi)
(cl-loop with ln = 0
while (not (if in-current-source
(or (helm-pos-header-line-p) (eobp))
;; Don't count empty lines maybe added by popup (#1370).
unless (or (eq (point-at-bol) (point-at-eol))
do (cl-incf ln)
do (forward-line 1) finally return ln))))))
(defmacro with-helm-quittable (&rest body)
"If an error occurs in execution of BODY, safely quit helm."
(declare (indent 0) (debug t))
`(condition-case _v
(let (inhibit-quit)
(quit (setq quit-flag t)
(setq helm-quit t)
;; See comment about this in `with-local-quit'.
(eval '(ignore nil)))))
;; Entry point
;; `:allow-nest' is not in this list because it is treated before.
(defconst helm-argument-keys
'(:sources :input :prompt :resume
:preselect :buffer :keymap :default :history))
(defun helm (&rest plist)
"Main function to execute helm sources.
PLIST is a list like
\(:key1 val1 :key2 val2 ...\)
\(&optional sources input prompt resume preselect
buffer keymap default history allow-nest\).
** Keywords
Keywords supported:
- :sources
- :input
- :prompt
- :resume
- :preselect
- :buffer
- :keymap
- :default
- :history
- :allow-nest
Extra LOCAL-VARS keywords are supported, see the \"** Other
keywords\" section below.
Basic keywords are the following:
*** :sources
One of the following:
- List of sources
- Symbol whose value is a list of sources
- Alist representing a Helm source.
- In this case the source has no name and is referenced in
`helm-sources' as a whole alist.
*** :input
Initial input of minibuffer (temporary value of `helm-pattern')
*** :prompt
Minibuffer prompt. Default value is `helm--prompt'.
*** :resume
If t, allow resumption of the previous session of this Helm
command, skipping initialization.
If 'noresume, this instance of `helm' cannot be resumed.
*** :preselect
Initially selected candidate (string or regexp).
*** :buffer
Buffer name for this Helm session. `helm-buffer' will take this value.
*** :keymap
Keymap used at the start of this Helm session.
It is overridden by keymaps specified in sources, and is kept
only for backward compatibility.
Keymaps should be specified in sources using the :keymap slot
instead. See `helm-source'.
This keymap is not restored by `helm-resume'.
*** :default
Default value inserted into the minibuffer \ with
It can be a string or a list of strings, in this case
\\<minibuffer-local-map>\\[next-history-element] cycles through
the list items, starting with the first.
If nil, `thing-at-point' is used.
If `helm--maybe-use-default-as-input' is non-`nil', display is
updated using this value, unless :input is specified, in which
case that value is used instead.
*** :history
Minibuffer input, by default, is pushed to `minibuffer-history'.
When an argument HISTORY is provided, input is pushed to
HISTORY. HISTORY should be a valid symbol.
*** :allow-nest
Allow running this Helm command in a running Helm session.
** Other keywords
Other keywords are interpreted as local variables of this Helm
session. The `helm-' prefix can be omitted. For example,
\(helm :sources 'helm-source-buffers-list
:buffer \"*helm buffers*\"
:candidate-number-limit 10\)
starts a Helm session with the variable
`helm-candidate-number-limit' set to 10.
** Backward compatibility
For backward compatibility, positional parameters are
\(helm sources input prompt resume preselect
buffer keymap default history allow-nest\)
However, the use of non-keyword args is deprecated.
(let ((fn (cond ((or (and helm-alive-p (plist-get plist :allow-nest))
(and helm-alive-p (memq 'allow-nest plist)))
((keywordp (car plist))
(t #'helm-internal))))
(if (and helm-alive-p (eq fn #'helm))
(if (helm--alive-p)
;; A helm session is normally running.
(error "Error: Trying to run helm within a running helm session")
;; A helm session is already running and user jump somewhere else
;; without deactivating it.
(message "Aborting an helm session running in background")
;; `helm-alive-p' will be reset in unwind-protect forms.
(if (keywordp (car plist))
;; Parse `plist' and move not regular `helm-argument-keys'
;; to `helm--local-variables', then calling helm on itself
;; with normal arguments (the non--arguments-keys removed)
;; will end up in [1].
(setq helm--local-variables
(append helm--local-variables
;; Vars passed by keyword on helm call
;; take precedence on same vars
;; that may have been passed before helm call.
(helm-parse-keys plist)))
(apply fn (mapcar (lambda (key) (plist-get plist key))
(apply fn plist))))) ; [1] fn == helm-internal.
(defun helm--alive-p ()
"[Internal] Check if `helm' is alive.
An `helm' session is considered alive if `helm-alive-p' value is
non-`nil', the `helm-buffer' is visible, and cursor is in the
(and helm-alive-p
(get-buffer-window (helm-buffer-get) 'visible)
(minibuffer-window-active-p (minibuffer-window))
(minibufferp (current-buffer))))
(defun helm-parse-keys (keys)
"Parse the KEYS arguments of `helm'.
Return only those keys not in `helm-argument-keys', prefix them
with \"helm\", and then convert them to an alist. This allows
adding arguments that are not part of `helm-argument-keys', but
are valid helm variables nevertheless. For
example, :candidate-number-limit is bound to
`helm-candidate-number-limit' in the source.
(helm-parse-keys '(:sources ((name . \"test\")
(candidates . (a b c)))
:buffer \"toto\"
:candidate-number-limit 4))
==> ((helm-candidate-number-limit . 4))."
(cl-loop for (key value) on keys by #'cddr
for symname = (substring (symbol-name key) 1)
for sym = (intern (if (string-match "^helm-" symname)
(concat "helm-" symname)))
unless (memq key helm-argument-keys)
collect (cons sym value)))
;;; Entry point helper
(defun helm-internal (&optional
any-sources any-input
any-prompt any-resume
any-preselect any-buffer
any-keymap any-default any-history)
"The internal helm function called by `helm'.
(unless helm--nested (setq helm-initial-frame (selected-frame)))
;; Activate the advice for `tramp-read-passwd' and cua.
;; Advices will be available only in >=emacs-24.4, but
;; allow compiling without errors on lower emacs.
(when (fboundp 'advice-add)
(advice-add 'tramp-read-passwd :around #'helm--advice-tramp-read-passwd)
(advice-add 'ange-ftp-get-passwd :around #'helm--advice-ange-ftp-get-passwd)
(advice-add 'cua-delete-region :around #'cua-delete-region--advice)
(advice-add 'copy-region-as-kill :around #'copy-region-as-kill--advice))
(helm-log (concat "[Start session] " (make-string 41 ?+)))
(helm-log "any-prompt = %S" any-prompt)
(helm-log "any-preselect = %S" any-preselect)
(helm-log "any-buffer = %S" any-buffer)
(helm-log "any-keymap = %S" any-keymap)
(helm-log "any-default = %S" any-default)
(helm-log "any-history = %S" any-history)
(setq helm--prompt (or any-prompt "pattern: "))
(let ((non-essential t)
;; Prevent mouse jumping to the upper-right
;; hand corner of the frame (#1538).
(input-method-verbose-flag helm-input-method-verbose-flag)
(old--cua cua-mode)
(and (null any-input)
(or helm--maybe-use-default-as-input ; it is let-bounded so use it.
(cl-loop for s in (helm-normalize-sources any-sources)
thereis (memq s helm-sources-using-default-as-input))))))
;; cua-mode override local helm bindings.
;; disable this stupid thing if enabled.
(and cua-mode (cua-mode -1))
(condition-case-unless-debug _v
(let ( ;; `helm--source-name' is non-`nil'
;; when `helm' is invoked by action, reset it.
(helm-buffer (or any-buffer helm-buffer)))
any-resume any-input any-default any-sources)
(helm-display-buffer helm-buffer)
(select-window (helm-window))
;; We are now in helm-buffer.
(unless helm-allow-mouse
(helm--remap-mouse-mode 1)) ; Disable mouse bindings.
(add-hook 'post-command-hook 'helm--maybe-update-keymap)
;; Add also to update hook otherwise keymap is not updated
;; until a key is hitted (Issue #1670).
(add-hook 'helm-after-update-hook 'helm--maybe-update-keymap)
(add-hook 'post-command-hook 'helm--update-header-line)
(helm-log "show prompt")
any-prompt any-input any-preselect
any-resume any-keymap any-default any-history)
(unless helm-quit (helm-execute-selection-action))
(helm-log (concat "[End session] " (make-string 41 ?-)))))
(helm-log-run-hook 'helm-quit-hook)
(helm-log (concat "[End session (quit)] " (make-string 34 ?-)))
(when (fboundp 'advice-remove)
(advice-remove 'tramp-read-passwd #'helm--advice-tramp-read-passwd)
(advice-remove 'ange-ftp-get-passwd #'helm--advice-ange-ftp-get-passwd)
(advice-remove 'cua-delete-region #'cua-delete-region--advice)
(advice-remove 'copy-region-as-kill #'copy-region-as-kill--advice))
(helm-log "helm-alive-p = %S" (setq helm-alive-p nil))
(helm--remap-mouse-mode -1) ; Reenable mouse bindings.
(setq helm-alive-p nil)
(setq helm--buffer-in-new-frame-p nil)
;; Reset helm-pattern so that lambda's using it
;; before running helm will not start with its old value.
(setq helm-pattern "")
(setq helm-sources nil)
(setq helm--ignore-errors nil)
(and old--cua (cua-mode 1))
;;; Helm resume
(defun helm-resume (arg)
"Resume a previous `helm' session.
Call with a prefix arg to choose among existing helm
buffers (sessions). When calling from lisp, specify a buffer-name
as a string with ARG."
(interactive "P")
(let (any-buffer
(helm-full-frame (default-value 'helm-full-frame)))
(if arg
(if (and (stringp arg) (bufferp (get-buffer arg)))
(setq any-buffer arg)
(setq any-buffer (helm-resume-select-buffer)))
(setq any-buffer helm-last-buffer))
(cl-assert any-buffer nil
"helm-resume: No helm buffers found to resume")
;; Reset `cursor-type' to nil as it have been set to t
;; when quitting previous session.
(with-current-buffer any-buffer (setq cursor-type nil))
(setq helm-full-frame (buffer-local-value
'helm-full-frame (get-buffer any-buffer)))
(setq helm-compiled-sources nil)
(setq cur-dir (buffer-local-value
'default-directory (get-buffer any-buffer)))
(setq helm-saved-selection nil
helm-saved-action nil)
(unless (buffer-live-p helm-current-buffer)
;; `helm-current-buffer' may have been killed.
(setq helm-current-buffer (current-buffer)))
;; Restart with same `default-directory' value this session
;; was initially started with.
(with-helm-default-directory cur-dir
:sources (buffer-local-value
'helm-sources (get-buffer any-buffer))
:input (buffer-local-value 'helm-input-local (get-buffer any-buffer))
:prompt (buffer-local-value 'helm--prompt (get-buffer any-buffer))
:resume t
:buffer any-buffer))))
(defun helm-resume-previous-session-after-quit (arg)
"Resume previous helm session within a running helm."
(interactive "p")
(if (> (length helm-buffers) arg)
(helm-run-after-exit (lambda () (helm-resume (nth arg helm-buffers))))
(message "No previous helm sessions available for resuming!"))))
(put 'helm-resume-previous-session-after-quit 'helm-only t)
(defun helm-resume-list-buffers-after-quit ()
"List resumable helm buffers within running helm."
(if (> (length helm-buffers) 0)
(helm-run-after-exit (lambda () (helm-resume t)))
(message "No previous helm sessions available for resuming!"))))
(put 'helm-resume-list-buffers-after-quit 'helm-only t)
(defun helm-resume-p (any-resume)
"Whether current helm session is resumed or not."
(eq any-resume t))
(defun helm-resume-select-buffer ()
"Select an `helm-buffer' in `helm-buffers' list to resume a helm session.
Return nil if no `helm-buffer' found."
(when helm-buffers
(or (helm :sources (helm-build-sync-source "Resume helm buffer"
:candidates helm-buffers)
:resume 'noresume
:buffer "*helm resume*")
(defun helm-cycle-resume ()
"Cycle in `helm-buffers' list and resume when waiting more than 1.2s."
(cl-assert (and helm-buffers helm-last-buffer)
nil "No helm buffers to resume")
;; Setup a new iterator only on first hit on
;; `helm-run-cycle-resume', subsequents hits should reuse same
;; iterator.
(unless (and (eq last-command 'helm-cycle-resume)
(setq helm--cycle-resume-iterator
helm-buffers helm-last-buffer :test 'equal)))
(defun helm--resume-or-iter (&optional from-helm)
(message "Resuming helm buffer `%s'" helm-last-buffer)
(if (sit-for helm-cycle-resume-delay)
;; Delay expire, run helm-resume.
(if from-helm
(helm-run-after-exit (lambda () (helm-resume helm-last-buffer)))
(helm-resume helm-last-buffer))
;; key pressed before delay, cycle.
(unless from-helm ; cycling to next item already done.
(message "Resuming helm buffer `%s'"
(setq helm-last-buffer
(helm-iter-next helm--cycle-resume-iterator))))))
(defun helm-run-cycle-resume ()
"Same as `helm-cycle-resume' but intended to be called only from helm."
(when (cdr helm-buffers) ; only one session registered.
;; Setup a new iterator only on first hit on
;; `helm-run-cycle-resume', subsequents hits should reuse same
;; iterator.
(unless (and (eq last-command 'helm-run-cycle-resume)
(setq helm--cycle-resume-iterator
helm-buffers helm-last-buffer :test 'equal)))
;; start at next buffer as we already are at `helm-last-buffer'.
(setq helm-last-buffer
(helm-iter-next helm--cycle-resume-iterator))
(helm--resume-or-iter 'from-helm)))
(put 'helm-run-cycle-resume 'helm-only t)
(defun helm-other-buffer (any-sources any-buffer)
"Simplified `helm' interface with other `helm-buffer'.
Call `helm' only with ANY-SOURCES and ANY-BUFFER as args."
(helm :sources any-sources :buffer any-buffer))
;;; Nested sessions
(defun helm--nest (&rest same-as-helm)
"[internal]Allows calling `helm' within a running helm session.
Arguments SAME-AS-HELM are the same as `helm'.
Don't use this directly, use instead `helm' with the keyword
(let ((orig-helm-current-buffer helm-current-buffer)
(orig-helm-buffer helm-buffer)
(orig-helm--prompt helm--prompt)
(orig-helm--in-fuzzy helm--in-fuzzy)
(orig-helm--display-frame helm--buffer-in-new-frame-p)
(orig-one-window-p helm-onewindow-p)
(helm--nested t))
;; FIXME Using helm-full-frame here allow showing the new
;; helm-buffer in the same window as old helm-buffer, why?
(helm-set-local-variable 'helm-full-frame t)
(let (helm-current-position
(helm-buffer (or (cl-getf same-as-helm :buffer)
(nth 5 same-as-helm)
(enable-recursive-minibuffers t))
(apply #'helm same-as-helm))
(with-current-buffer orig-helm-buffer
(setq helm--nested nil)
(setq helm--buffer-in-new-frame-p orig-helm--display-frame)
(setq helm-alive-p t) ; Nested session set this to nil on exit.
(setq helm-buffer orig-helm-buffer)
(setq helm-full-frame nil)
(setq helm--prompt orig-helm--prompt)
(setq helm--in-fuzzy orig-helm--in-fuzzy)
(helm-initialize-overlays helm-buffer)
(unless (helm-empty-buffer-p) (helm-mark-current-line t))
(setq helm-last-frame-or-window-configuration
(setq cursor-type nil)
(setq helm-current-buffer orig-helm-current-buffer)
(setq helm-onewindow-p orig-one-window-p)
;; Be sure advices, hooks, and local modes keep running.
(if (fboundp 'advice-add)
(advice-add 'tramp-read-passwd
:around #'helm--advice-tramp-read-passwd)
(advice-add 'ange-ftp-get-passwd
:around #'helm--advice-ange-ftp-get-passwd))
(ad-activate 'tramp-read-passwd)
(ad-activate 'ange-ftp-get-passwd))
(unless helm-allow-mouse
(helm--remap-mouse-mode 1))
(unless (cl-loop for h in post-command-hook
thereis (memq h '(helm--maybe-update-keymap
(add-hook 'post-command-hook 'helm--maybe-update-keymap)
(add-hook 'post-command-hook 'helm--update-header-line))
(helm-display-mode-line (helm-get-current-source)))))))
;;; Accessors
(defun helm-current-position (save-or-restore)
"Save or restore current position in `helm-current-buffer'.
Argument SAVE-OR-RESTORE is either save or restore."
(cl-case save-or-restore
(helm-log "Save position at %S" (cons (point) (window-start)))
(setq helm-current-position (cons (point) (window-start))))
;; Maybe `helm-current-buffer' have been deleted
;; during helm session so check if it is here
;; otherwise position in underlying buffer will be lost.
(when (get-buffer-window helm-current-buffer 'visible)
(helm-log "Restore position at %S in buffer %s"
(buffer-name (current-buffer)))
(goto-char (car helm-current-position))
;; Fix this position with the NOFORCE arg of `set-window-start'
;; otherwise, if there is some other buffer than `helm-current-buffer'
;; one, position will be lost.
(set-window-start (selected-window) (cdr helm-current-position) t)))))
(defun helm-frame-or-window-configuration (save-or-restore)
"Save or restore last frame or window configuration.
Argument SAVE-OR-RESTORE is either save or restore of window or
frame configuration as per `helm-save-configuration-functions'."
(helm-log "helm-save-configuration-functions = %S"
(let ((window-persistent-parameters (append '((no-other-window . t))
(cl-case save-or-restore
(save (setq helm-last-frame-or-window-configuration
(funcall (cdr helm-save-configuration-functions))))
(restore (funcall (car helm-save-configuration-functions)
;; Restore frame focus.
;; This is needed for minibuffer own-frame config
;; when recursive minibuffers are in use.
;; e.g M-: + helm-minibuffer-history.
(cl-letf ((frame (if (minibufferp helm-current-buffer)
;; This is a workaround, because the i3 window
;; manager developers are refusing to fix their
;; broken timestamp and event handling.
;; We basically just disable the part of
;; select-frame-set-input-focus that would call
;; XSetInputFocus in Xlib (x-focus-frame), that
;; resets a timestamp in the xserver which the i3
;; developers fail to notice.
;; Since they don't know about the new timestamp,
;; their keyboard handling can break after a helm
;; user quits emacs, as reported in #1641.
;; Fortunately for us, we really don't need this
;; XSetInputFocus call, since we already have focus
;; for Emacs, the user is just using helm! We call
;; select-frame-set-input-focus for the other
;; side-effects, not for x-focus-frame.
((symbol-function 'x-focus-frame) #'ignore))
(select-frame-set-input-focus frame))))))
(defun helm-split-window-default-fn (window)
"Default function to split windows before displaying `helm-buffer'.
It is used as default value for
`helm-split-window-preferred-function' which is then the let-bounded
value of `split-window-preferred-function' in `helm-display-buffer'.
When `helm-display-function' which default to
`helm-default-display-buffer' is called from `helm-display-buffer' the
value of `split-window-preferred-function' will be used by `display-buffer'."
(let (split-width-threshold)
(if (and (fboundp 'window-in-direction)
;; Don't try to split when starting in a minibuffer
;; e.g M-: and try to use helm-show-kill-ring.
(not (minibufferp helm-current-buffer)))
(if (or (one-window-p t)
(selected-window) nil (if (eq helm-split-window-default-side 'other)
'below helm-split-window-default-side))
;; If more than one window reuse one of them.
(cl-case helm-split-window-default-side
(left (or (helm-window-in-direction 'left)
(helm-window-in-direction 'above)
(above (or (helm-window-in-direction 'above)
(helm-window-in-direction 'left)
(right (or (helm-window-in-direction 'right)
(helm-window-in-direction 'below)
(below (or (helm-window-in-direction 'below)
(helm-window-in-direction 'right)
(same (selected-window))
(other (other-window-for-scrolling))
(t (or (window-next-sibling) (selected-window)))))
(split-window-sensibly window))))
(defun helm-window-in-direction (direction)
"Same as `window-in-direction' but check if window is dedicated."
(helm-aif (window-in-direction direction)
(and (not (window-dedicated-p it)) it)))
;;; Display helm buffer
(defun helm-resolve-display-function (com)
"Decide which display function use according to `helm-commands-using-frame'.
The `helm-display-function' buffer local value takes precedence on
Fallback to global value of `helm-display-function' when no local
value found and current command is not in `helm-commands-using-frame'."
(or (with-helm-buffer helm-display-function)
(and (memq com helm-commands-using-frame)
(default-value 'helm-display-function)))
(defun helm-display-buffer (buffer)
"Display BUFFER.
The function used to display `helm-buffer' by calling
`helm-display-function' which split window with
(let ((split-window-preferred-function
(if (and (not helm-full-frame)
(cond ((eq helm-split-window-default-side 'same) 'same)
((eq helm-split-window-default-side 'other) 'other)
(t helm-split-window-default-side))
(disp-fn (with-current-buffer buffer
(if helm-actions-inherit-frame-settings
(helm-this-command) this-command)))))
(funcall disp-fn buffer)
(with-helm-buffer (setq-local helm-display-function disp-fn))
(setq helm-onewindow-p (one-window-p t))
;; Don't allow other-window and friends switching out of minibuffer.
(when helm-prevent-escaping-from-minibuffer
(cl-defun helm-prevent-switching-other-window (&key (enabled t))
"Allow setting `no-other-window' parameter for all windows.
Arg ENABLE is the value of `no-other-window' window property."
(lambda (w)
(unless (window-dedicated-p w)
(set-window-parameter w 'no-other-window enabled)))
(defun helm-default-display-buffer (buffer)
"Default function to display `helm-buffer' BUFFER.
It is the default value of `helm-display-function'
It uses `switch-to-buffer' or `display-buffer' depending on the
value of `helm-full-frame' or `helm-split-window-default-side'."
(let (pop-up-frames)
(if (or (buffer-local-value 'helm-full-frame (get-buffer buffer))
(and (eq helm-split-window-default-side 'same)
(one-window-p t)))
(progn (and (not (minibufferp helm-current-buffer))
(switch-to-buffer buffer))
(when (and (or helm-always-two-windows helm-autoresize-mode)
(not (eq helm-split-window-default-side 'same))
(not (minibufferp helm-current-buffer))
(not helm-split-window-inside-p))
buffer `(nil . ((window-height . ,helm-display-buffer-default-height)
(window-width . ,helm-display-buffer-default-width))))
(helm-log-run-hook 'helm-window-configuration-hook))))
(defun helm-display-buffer-in-own-frame (buffer)
"Display `helm-buffer' in a separate frame.
Function suitable for `helm-display-function',
and/or `helm-show-completion-default-display-function'.
See `helm-display-buffer-height' and `helm-display-buffer-width' to
configure frame size.
Note that this feature is available only with emacs-25+."
(cl-assert (and (fboundp 'window-absolute-pixel-edges)
(fboundp 'frame-geometry))
nil "Helm buffer in own frame is only available starting at emacs-25+")
(if (not (display-graphic-p))
;; Fallback to default when frames are not usable.
(helm-default-display-buffer buffer)
(setq helm--buffer-in-new-frame-p t)
(let* ((pos (window-absolute-pixel-position))
(half-screen-size (/ (display-pixel-height x-display-name) 2))
(frame-info (frame-geometry))
(prmt-size (length helm--prompt))
(line-height (frame-char-height))
`((width . ,helm-display-buffer-width)
(height . ,helm-display-buffer-height)
(tool-bar-lines . 0)
(left . ,(- (car pos)
(* (frame-char-width)
(if (< (- (point) (point-at-bol)) prmt-size)
(- (point) (point-at-bol))
;; Try to put frame at the best possible place.
;; Frame should be below point if enough
;; place, otherwise above point and
;; current line should not be hidden
;; by helm frame.
(top . ,(if (> (cdr pos) half-screen-size)
;; Above point
(- (cdr pos)
;; add 2 lines to make sure there is always a gap
(* (+ helm-display-buffer-height 2) line-height)
;; account for title bar height too
(cddr (assq 'title-bar-size frame-info)))
;; Below point
(+ (cdr pos) line-height)))
(title . "Helm")
(undecorated . ,helm-use-undecorated-frame-option)
(vertical-scroll-bars . nil)
(menu-bar-lines . 0)
(fullscreen . nil)
(visible . ,(null helm-display-buffer-reuse-frame))
(minibuffer . t)))
;; Add the hook inconditionally, if
;; helm-echo-input-in-header-line is nil helm-hide-minibuffer-maybe
;; will have anyway no effect so no need to remove the hook.
(add-hook 'helm-minibuffer-set-up-hook 'helm-hide-minibuffer-maybe)
(setq-local helm-echo-input-in-header-line
(not (> (cdr pos) half-screen-size))))
(helm-display-buffer-popup-frame buffer default-frame-alist))
(helm-log-run-hook 'helm-window-configuration-hook)))
(defun helm-display-buffer-popup-frame (buffer frame-alist)
(if helm-display-buffer-reuse-frame
(let* ((x (cdr (assoc 'left frame-alist)))
(y (cdr (assoc 'top frame-alist))))
(unless (and helm-popup-frame
(frame-live-p helm-popup-frame))
(setq helm-popup-frame (make-frame frame-alist)))
(select-frame helm-popup-frame)
(set-frame-position helm-popup-frame x y)
(switch-to-buffer buffer)
(raise-frame helm-popup-frame))
;; If user have changed `helm-display-buffer-reuse-frame' to nil
;; maybe kill the frame.
(when (and helm-popup-frame
(frame-live-p helm-popup-frame))
(delete-frame helm-popup-frame))
buffer '(display-buffer-pop-up-frame . nil))))
(defun helm-restore-last-frame-position ()
"Restore last helm frame position."
(set-frame-position (selected-frame)
(car helm--last-frame-position)
(cdr helm--last-frame-position)))))
(put 'helm-restore-last-frame-position 'helm-only t)
;;; Initialize
(defun helm-initialize (any-resume any-input any-default any-sources)
"Start initialization of `helm' session.
(helm-log "start initialization: any-resume=%S any-input=%S"
any-resume any-input)
(helm-frame-or-window-configuration 'save)
(setq helm-sources (helm-normalize-sources any-sources))
(setq helm--in-fuzzy
(cl-loop for s in helm-sources
for matchfns = (helm-match-functions
(if (symbolp s) (symbol-value s) s))
for searchfns = (helm-search-functions
(if (symbolp s) (symbol-value s) s))
when (or (memq 'helm-fuzzy-match matchfns)
(memq 'helm-fuzzy-search searchfns))
return t))
(helm-log "sources = %S" helm-sources)
(helm-current-position 'save)
(if (helm-resume-p any-resume)
(helm-initialize-overlays (helm-buffer-get))
(helm-initial-setup any-default))
(setq helm-alive-p t)
(unless (eq any-resume 'noresume)
(helm--recent-push helm-buffer 'helm-buffers)
(setq helm-last-buffer helm-buffer))
(when any-input
(setq helm-input any-input
helm-pattern any-input)
;; If a `resume' attribute is present `helm-funcall-foreach'
;; will run its function.
(when (helm-resume-p any-resume)
(helm-funcall-foreach 'resume))
(helm-log "end initialization"))
(defun helm-initialize-overlays (buffer)
"Initialize helm overlays in BUFFER."
(helm-log "overlay setup")
(if helm-selection-overlay
;; make sure the overlay belongs to the helm buffer if
;; it's newly created
(move-overlay helm-selection-overlay (point-min) (point-min)
(get-buffer buffer))
(setq helm-selection-overlay
(make-overlay (point-min) (point-min) (get-buffer buffer)))
(overlay-put helm-selection-overlay 'face 'helm-selection)
(overlay-put helm-selection-overlay 'priority 1)))
(defun helm-restore-position-on-quit ()
"Restore position in `helm-current-buffer' when quitting."
(helm-current-position 'restore))
(defun helm--recent-push (elm sym)
"Move ELM of SYM value on top and set SYM to this new value."
(pcase (symbol-value sym)
((and (pred (member elm)) l)
(set sym (delete elm l))))
(push elm (symbol-value sym)))
(defun helm--current-buffer ()
"[internal] Return `current-buffer' BEFORE `helm-buffer' is initialized.
Note that it returns the minibuffer in use after helm has started
and is intended for `helm-initial-setup'. To get the buffer where
helm was started, use `helm-current-buffer' instead."
(if (minibuffer-window-active-p (minibuffer-window))
;; If minibuffer is active be sure to use it's buffer
;; as `helm-current-buffer', this allow to use helm
;; from an already active minibuffer (M-: etc...)
(window-buffer (active-minibuffer-window))
;; Fix Issue #456
;; Use this instead of `current-buffer' to ensure
;; helm session started in helm-mode from a completing-read
;; Use really the buffer where we started and not the one
;; where the completing-read is wrapped. i.e
;; (with-current-buffer SOME-OTHER-BUFFER (completing-read [...])
(window-buffer (with-selected-window (minibuffer-window)
(defun helm--run-init-hooks (hook)
"Run after and before init hooks local to source.
See :after-init-hook and :before-init-hook in `helm-source'."
(cl-loop with sname = (cl-ecase hook
(before-init-hook "h-before-init-hook")
(after-init-hook "h-after-init-hook"))
with h = (cl-gensym sname)
for s in (helm-get-sources)
for hv = (assoc-default hook s)
if (and hv (not (symbolp hv)))
do (set h hv)
and do (helm-log-run-hook h)
else do (helm-log-run-hook hv)))
(defun helm-initial-setup (any-default)
"Initialize helm settings and set up the helm buffer."
;; Run global hook.
(helm-log-run-hook 'helm-before-initialize-hook)
;; Run local source hook.
(helm--run-init-hooks 'before-init-hook)
;; For initialization of helm locals vars that need
;; a value from current buffer, it is here.
(helm-set-local-variable 'current-input-method current-input-method)
(setq helm-current-prefix-arg nil
helm-saved-action nil
helm-saved-selection nil
helm-suspend-update-flag nil
;; Ensure this is called BEFORE selecting helm-window.
helm-current-buffer (helm--current-buffer)
helm-buffer-file-name buffer-file-name
helm-issued-errors nil
helm-compiled-sources nil
helm-saved-current-source nil)
(unless (and (or helm-split-window-state
(setq helm-split-window-state
(if (or (null split-width-threshold)
(and (integerp split-width-threshold)
(>= split-width-threshold (+ (frame-width) 4))))
'vertical 'horizontal))
(setq helm--window-side-state
(or helm-split-window-default-side 'below)))
;; Call the init function for sources where appropriate
(helm-funcall-foreach 'init)
(setq helm-pattern (or (and helm--maybe-use-default-as-input
(or (if (listp any-default)
(car any-default) any-default)
(thing-at-point 'symbol))))
(setq helm-input "")
(clrhash helm-candidate-cache)
;; Run global hook.
(helm-log-run-hook 'helm-after-initialize-hook)
;; Run local source hook.
(helm--run-init-hooks 'after-init-hook))
(define-derived-mode helm-major-mode
fundamental-mode "Hmm"
"[Internal] Provide major-mode name in helm buffers.
Unuseful when used outside helm, don't use it.")
(put 'helm-major-mode 'mode-class 'special)
(put 'helm-major-mode 'helm-only t)
(defun helm-create-helm-buffer ()
"Create and setup `helm-buffer'."
(let ((root-dir default-directory)
(inhibit-read-only t))
(with-current-buffer (get-buffer-create helm-buffer)
(helm-log "Enabling major-mode %S" major-mode)
(helm-log "kill local variables: %S" (buffer-local-variables))
(set (make-local-variable 'buffer-read-only) nil)
(set (make-local-variable 'helm-map) helm-map)
(set (make-local-variable 'helm-source-filter) nil)
(make-local-variable 'helm-sources)
(set (make-local-variable 'helm-display-function) nil)
(set (make-local-variable 'helm-selection-point) nil)
(set (make-local-variable 'scroll-margin)
(if helm-display-source-at-screen-top
0 helm-completion-window-scroll-margin))
(set (make-local-variable 'default-directory) root-dir)
(set (make-local-variable 'helm-marked-candidates) nil)
(set (make-local-variable 'helm--prompt) helm--prompt)
(helm-log "helm-display-function = %S" helm-display-function)
(helm-log "helm--local-variables = %S" helm--local-variables)
(cl-loop for (var . val) in helm--local-variables
do (set (make-local-variable var) val)
finally (setq helm--local-variables nil))
(setq truncate-lines helm-truncate-lines) ; already local.
(setq cursor-type nil))
(helm-initialize-overlays helm-buffer)
(get-buffer helm-buffer)))
(define-minor-mode helm--minor-mode
"[INTERNAL] Enable keymap in helm minibuffer.
Since this mode has no effect when run outside of helm context,
please don't use it outside helm.
:group 'helm
:keymap (and helm-alive-p helm-map)
(unless helm-alive-p (setq helm--minor-mode nil)))
(put 'helm--minor-mode 'helm-only t)
(defun helm--reset-default-pattern ()
(setq helm-pattern "")
(setq helm--maybe-use-default-as-input nil))
(defun helm-read-pattern-maybe (any-prompt any-input
any-preselect any-resume any-keymap
any-default any-history)
"Read pattern with prompt ANY-PROMPT and initial input ANY-INPUT.
(if (and (helm-resume-p any-resume)
;; When no source, helm-buffer is empty
;; or contain non--candidate lines (e.g grep exit status)
(helm-mark-current-line t)
(helm-update any-preselect))
(let* ((src (helm-get-current-source))
(src-keymap (assoc-default 'keymap src))
(hist (or (and any-history (symbolp any-history) any-history)
;; Needed for resuming.
(assoc-default 'history src)))
(timer nil)
(resize-mini-windows (and (null helm-echo-input-in-header-line)
(first-src (car helm-sources))
(first-src-val (if (symbolp first-src)
(symbol-value first-src)
(source-process-p (or (assq 'candidates-process src)
(assq 'candidates-process first-src-val))))
(helm-log "helm-get-candidate-number => %S"
(helm-log "helm-execute-action-at-once-if-one = %S"
(helm-log "helm-quit-if-no-candidate = %S" helm-quit-if-no-candidate)
(when (and src (helm-resume-p any-resume))
(helm-display-mode-line src))
;; Reset `helm-pattern' and update
;; display if no result found with precedent value of `helm-pattern'
;; unless `helm-quit-if-no-candidate' is non-`nil', in this case
;; Don't force update with an empty pattern.
;; Reset also `helm--maybe-use-default-as-input' as this checking
;; happen only on startup.
(when helm--maybe-use-default-as-input
;; Store value of `default' temporarily here waiting next update
;; to allow actions like helm-moccur-action matching pattern
;; at the place it jump to.
(setq helm-input helm-pattern)
(if source-process-p
;; Reset pattern to next update.
;; Reset pattern right now.
;; Ensure force-update when no candidates
;; when we start with an empty pattern.
(and (helm-empty-buffer-p)
(null helm-quit-if-no-candidate)
;; Handle `helm-execute-action-at-once-if-one' and
;; `helm-quit-if-no-candidate' now.
(cond ((and (if (functionp helm-execute-action-at-once-if-one)
(funcall helm-execute-action-at-once-if-one)
(= (helm-get-candidate-number
(eq helm-execute-action-at-once-if-one 'current-source)) 1))
(ignore)) ; Don't enter the minibuffer loop.
((and helm-quit-if-no-candidate
(= (helm-get-candidate-number) 0))
(setq helm-quit t)
(and (functionp helm-quit-if-no-candidate)
(funcall helm-quit-if-no-candidate)))
(t ; Enter now minibuffer and wait for input.
(let ((tap (or any-default
(thing-at-point 'symbol)))))
(lambda ()
;; Start minor-mode with global value of helm-map.
(helm--minor-mode 1)
;; Now override the global value of `helm-map' with
;; the local one which is in this order:
;; - The keymap of current source.
;; - The value passed in ANY-KEYMAP
;; - Or fallback to the global value of helm-map.
(or src-keymap any-keymap helm-map))
(helm-log-run-hook 'helm-minibuffer-set-up-hook)
(setq timer
(max (with-helm-buffer helm-input-idle-delay)
(lambda ()
;; Stop updating in persistent action
;; or when `helm-suspend-update-flag'
;; is non-`nil'.
(unless (or helm-in-persistent-action
;; minibuffer has already been filled here.
(read-from-minibuffer (or any-prompt "pattern: ")
any-input helm-map
nil hist tap
(when timer (cancel-timer timer) (setq timer nil)))))))))
(defun helm-toggle-suspend-update ()
"Enable or disable update of display in helm.
This can be useful for example for quietly writing a complex regexp
without helm constantly updating."
(when (setq helm-suspend-update-flag (not helm-suspend-update-flag))
(setq helm-pattern ""))
(message (if helm-suspend-update-flag
"Helm update suspended!"
"Helm update re-enabled!"))
(helm-aif (helm-get-current-source)
(with-helm-buffer (helm-display-mode-line it t)))))
(put 'helm-toggle-suspend-update 'helm-only t)
(defun helm--advice-tramp-read-passwd (old--fn &rest args)
;; Suspend update when prompting for a tramp password.
(setq helm-suspend-update-flag t)
(setq overriding-terminal-local-map nil)
(setq helm--reading-passwd-or-string t)
;; No need to suspend timer in emacs-24.4
;; it is fixed upstream.
(apply old--fn args)
(setq helm--reading-passwd-or-string nil)
(setq helm-suspend-update-flag nil)))
(defun helm--advice-ange-ftp-get-passwd (old--fn &rest args)
;; Suspend update when prompting for a ange password.
(setq helm-suspend-update-flag t)
(setq overriding-terminal-local-map nil)
(setq helm--reading-passwd-or-string t)
(apply old--fn args)
(setq helm--reading-passwd-or-string nil)
(setq helm-suspend-update-flag nil)))
;; CUA workaround
(defun cua-delete-region--advice (old--fn &rest args)
(apply old--fn args)))
(defun copy-region-as-kill--advice (old--fn &rest args)
(if cua-mode
(ignore-errors (apply old--fn args))
(apply old--fn args)))
(defun helm--maybe-update-keymap (&optional map)
"Handle different keymaps in multiples sources.
Overrides `helm-map' with the local map of current source. If no
map is found in current source, does nothing (keeps previous
(helm-aif (or map (assoc-default 'keymap (helm-get-current-source)))
;; We used a timer in the past to leave
;; enough time to helm to setup its keymap
;; when changing source from a recursive minibuffer.
;; e.g C-x C-f M-y C-g
;; => *find-files have now the bindings of *kill-ring.
;; It is no more true now we are using `minor-mode-overriding-map-alist'
;; and `helm--minor-mode' thus it fix issue #1076 for emacs-24.3
;; where concurrent timers are not supported.
;; i.e update keymap+check input.
(with-current-buffer (window-buffer (minibuffer-window))
(setq minor-mode-overriding-map-alist `((helm--minor-mode . ,it)))))))
;;; Prevent loosing focus when using mouse.
(defvar helm--remap-mouse-mode-map
(let ((map (make-sparse-keymap)))
(cl-loop for k in '([mouse-1] [mouse-2] [mouse-3]
[down-mouse-1] [down-mouse-2] [down-mouse-3]
[drag-mouse-1] [drag-mouse-2] [drag-mouse-3]
[double-mouse-1] [double-mouse-2] [double-mouse-3]
[triple-mouse-1] [triple-mouse-2] [triple-mouse-3])
do (define-key map k 'ignore))
(define-minor-mode helm--remap-mouse-mode
"[INTERNAL] Prevent escaping helm minibuffer with mouse clicks.
Do nothing when used outside of helm context.
WARNING: Do not use this mode yourself, it is internal to helm."
:group 'helm
:global t
:keymap helm--remap-mouse-mode-map
(unless helm-alive-p
(setq helm--remap-mouse-mode-map nil)))
(put 'helm--remap-mouse-mode 'helm-only t)
;; Clean up
(defun helm-cleanup ()
"Clean up the mess when helm exit or quit."
(helm-log "start cleanup")
(with-current-buffer helm-buffer
(setq cursor-type t)
;; bury-buffer from this window.
(bury-buffer) ;[1]
(remove-hook 'post-command-hook 'helm--maybe-update-keymap)
(remove-hook 'post-command-hook 'helm--update-header-line)
;; Be sure we call this from helm-buffer.
(helm-funcall-foreach 'cleanup)
(when (and helm--buffer-in-new-frame-p (null helm--nested))
(setq helm--last-frame-position (frame-position))
(if helm-display-buffer-reuse-frame
(make-frame-invisible) (delete-frame))))
;; Remove the temporary hooks added
;; by `with-helm-temp-hook' that
;; may not have been consumed.
(when helm--temp-hooks
(cl-loop for (fn . hook) in helm--temp-hooks
do (set hook (delete fn (symbol-value hook)))))
;; When running helm from a dedicated frame
;; with no minibuffer, helm will run in the main frame
;; which have a minibuffer, so be sure to disable
;; the `no-other-window' prop there.
(helm-prevent-switching-other-window :enabled nil)
(helm-log-run-hook 'helm-cleanup-hook)
(helm-frame-or-window-configuration 'restore)
;; [1] now bury-buffer from underlying windows otherwise,
;; if this window is killed the underlying buffer will
;; be a helm buffer.
(replace-buffer-in-windows helm-buffer)
(setq helm-alive-p nil)
(setq helm--buffer-in-new-frame-p nil)
;; This is needed in some cases where last input
;; is yielded infinitely in minibuffer after helm session.
(defun helm-clean-up-minibuffer ()
"Remove contents of minibuffer."
(let ((miniwin (minibuffer-window)))
;; Clean only current minibuffer used by helm.
;; i.e The precedent one is active.
(unless (minibuffer-window-active-p miniwin)
(with-current-buffer (window-buffer miniwin)
;;; Input handling
(defun helm-check-minibuffer-input ()
"Check minibuffer content."
(with-selected-window (or (active-minibuffer-window)
(helm-check-new-input (minibuffer-contents)))))
(defun helm-check-new-input (input)
"Check INPUT string and update the helm buffer if necessary."
(unless (equal input helm-pattern)
(setq helm-pattern input)
(unless (helm-action-window)
(setq helm-input helm-pattern))
(helm-log "helm-pattern = %S" helm-pattern)
(helm-log "helm-input = %S" helm-input)
(setq helm--in-update t)
(defun helm--reset-update-flag ()
helm-exit-idle-delay nil
(lambda () (setq helm--in-update nil))))
;; (add-hook 'helm-after-update-hook #'helm--reset-update-flag)
;; All candidates
(defun helm-get-candidates (source)
"Retrieve and return the list of candidates from SOURCE."
(let* (inhibit-quit
(candidate-fn (assoc-default 'candidates source))
(candidate-proc (assoc-default 'candidates-process source))
(lambda (&optional e)
"In `%s' source: `%s' %s %s"
(assoc-default 'name source)
(or candidate-fn candidate-proc)
(if e "\n" "must be a list, a symbol bound to a list, or a function returning a list")
(if e (prin1-to-string e) ""))))
(candidates (condition-case-unless-debug err
;; Process candidates-(process) function
;; It may return a process or a list of candidates.
(if candidate-proc
;; Calling `helm-interpret-value' with no
;; SOURCE arg force the use of `funcall'
;; and not `helm-funcall-with-source'.
(helm-interpret-value candidate-proc)
(helm-interpret-value candidate-fn source))
(error (helm-log "Error: %S" (setq cfn-error err)) nil))))
(cond ((and (processp candidates) (not candidate-proc))
(warn "Candidates function `%s' should be called in a `candidates-process' attribute"
((and candidate-proc (not (processp candidates)))
(error "Candidates function `%s' should run a process" candidate-proc)))
(cond ((processp candidates)
;; Candidates will be filtered later in process filter.
;; An error occured in candidates function.
(cfn-error (unless helm--ignore-errors
(funcall notify-error cfn-error)))
;; Candidates function returns no candidates.
((or (null candidates)
;; Can happen when the output of a process
;; is empty, and the candidates function call
;; something like (split-string (buffer-string) "\n")
;; which result in a list of one empty string (Issue #938).
;; e.g (completing-read "test: " '(""))
(equal candidates '("")))
((listp candidates)
;; Transform candidates with `candidate-transformer' functions or
;; `real-to-display' functions if those are found,
;; otherwise return candidates unmodified.
;; `filtered-candidate-transformer' is NOT called here.
(helm-transform-candidates candidates source))
(t (funcall notify-error)))))
(defmacro helm-while-no-input (&rest body)
"Same as `while-no-input' but without the `input-pending-p' test."
(declare (debug t) (indent 0))
(let ((catch-sym (make-symbol "input")))
(catch ',catch-sym
(let ((throw-on-input ',catch-sym))
(defun helm-get-cached-candidates (source)
"Return the cached value of candidates for SOURCE.
Cache the candidates if there is no cached value yet."
(let* ((name (assoc-default 'name source))
(candidate-cache (gethash name helm-candidate-cache)))
(helm-aif candidate-cache
(prog1 it (helm-log "Use cached candidates"))
(helm-log "No cached candidates, calculate candidates")
(let ((candidates (helm-get-candidates source)))
(cond ((processp candidates)
(push (cons candidates
(append source
(list (cons 'item-count 0)
(cons 'incomplete-line ""))))
(set-process-filter candidates 'helm-output-filter)
(setq candidates nil))
((not (assq 'volatile source))
(puthash name candidates helm-candidate-cache)))
;;; Candidate transformers
(defun helm-process-candidate-transformer (candidates source)
"Execute `candidate-transformer' function(s) on CANDIDATES in SOURCE."
(helm-aif (assoc-default 'candidate-transformer source)
(helm-funcall-with-source source it candidates)
(defun helm-process-filtered-candidate-transformer (candidates source)
"Execute `filtered-candidate-transformer' function(s) on CANDIDATES in SOURCE."
(helm-aif (assoc-default 'filtered-candidate-transformer source)
(helm-funcall-with-source source it candidates source)
(defmacro helm--maybe-process-filter-one-by-one-candidate (candidate source)
"Execute `filter-one-by-one' function(s) on real value of CANDIDATE in SOURCE."
`(helm-aif (assoc-default 'filter-one-by-one ,source)
(let ((real (if (consp ,candidate)
(cdr ,candidate)
(if (and (listp it)
(not (functionp it))) ;; Don't treat lambda's as list.
(cl-loop for f in it
do (setq ,candidate (funcall f real))
finally return ,candidate)
(setq ,candidate (funcall it real))))
(defun helm--initialize-one-by-one-candidates (candidates source)
"Process the CANDIDATES with the `filter-one-by-one' function in SOURCE.
Return CANDIDATES unchanged when pattern is not empty."
(helm-aif (and (string= helm-pattern "")
(assoc-default 'filter-one-by-one source))
(cl-loop for cand in candidates collect
(helm--maybe-process-filter-one-by-one-candidate cand source))
(defun helm-process-filtered-candidate-transformer-maybe
(candidates source process-p)
"Execute `filtered-candidate-transformer' function(s) on CANDIDATES in SOURCE.
When PROCESS-P is non-`nil' execute `filtered-candidate-transformer'
functions if some, otherwise return CANDIDATES."
(if process-p
;; When no filter return CANDIDATES unmodified.
(helm-process-filtered-candidate-transformer candidates source)
(defun helm-process-real-to-display (candidates source)
"Execute real-to-display function on all CANDIDATES of SOURCE."
(helm-aif (assoc-default 'real-to-display source)
(setq candidates (helm-funcall-with-source
source 'mapcar
(lambda (cand)
(if (consp cand)
;; override DISPLAY from candidate-transformer
(cons (funcall it (cdr cand)) (cdr cand))
(cons (funcall it cand) cand)))
(defun helm-transform-candidates (candidates source &optional process-p)
"Transform CANDIDATES from SOURCE according to candidate transformers.
When PROCESS-P is non-`nil' executes the
`filtered-candidate-transformer' functions, otherwise processes
`candidate-transformer' functions only,
`filtered-candidate-transformer' functions being processed later,
after the candidates have been narrowed by
`helm-candidate-number-limit', see `helm-compute-matches'. When
`real-to-display' attribute is present, execute its functions on all
maybe filtered CANDIDATES."
candidates source)
source process-p)
;; Narrowing candidates
(defun helm-candidate-number-limit (source)
"Apply candidate-number-limit attribute value.
This overrides `helm-candidate-number-limit' variable.
If \(candidate-number-limit\) is in SOURCE, show all candidates in SOURCE.
If \(candidate-number-limit . 123\) is in SOURCE limit candidate to 123."
(helm-aif (assq 'candidate-number-limit source)
;; When assoc value is nil use by default 99999999 otherwise use
;; the assoc value, when it is a symbol interpret its value (#1831).
(or (helm-aand (cdr it) (helm-interpret-value it)) 99999999)
(or helm-candidate-number-limit 99999999)))
(defun helm-candidate-get-display (candidate)
"Get searched display part from CANDIDATE.
CANDIDATE is either a string, a symbol, or a \(DISPLAY . REAL\)
cons cell."
(cond ((car-safe candidate))
((symbolp candidate)
(symbol-name candidate))
((numberp candidate)
(number-to-string candidate))
(t candidate)))
(defun helm-process-pattern-transformer (pattern source)
"Execute pattern-transformer attribute function(s) on PATTERN in SOURCE."
(helm-aif (assoc-default 'pattern-transformer source)
(helm-funcall-with-source source it pattern)
(defun helm-default-match-function (candidate)
"Check if `helm-pattern' match CANDIDATE.
Default function to match candidates according to `helm-pattern'."
(string-match helm-pattern candidate))
;;; Fuzzy matching
(defvar helm--fuzzy-regexp-cache (make-hash-table :test 'eq))
(defun helm--fuzzy-match-maybe-set-pattern ()
;; Computing helm-pattern with helm--mapconcat-pattern
;; is costly, so cache it once time for all and reuse it
;; until pattern change.
(when helm--in-fuzzy
(let ((fun (if (string-match "\\`\\^" helm-pattern)
(clrhash helm--fuzzy-regexp-cache)
;; FIXME: Splitted part are not handled here,
;; I must compute them in `helm-search-match-part'
;; when negation and in-buffer are used.
(if (string-match "\\`!" helm-pattern)
(puthash 'helm-pattern
(if (> (length helm-pattern) 1)
(list (funcall fun (substring helm-pattern 1 2))
(funcall fun (substring helm-pattern 1)))
'("" ""))
(puthash 'helm-pattern
(if (> (length helm-pattern) 0)
(list (funcall fun (substring helm-pattern 0 1))
(funcall fun helm-pattern))
'("" ""))
(defun helm-fuzzy-match (candidate)
"Check if `helm-pattern' fuzzy matches CANDIDATE.
This function is used with sources built with `helm-source-sync'."
(unless (string-match " " helm-pattern)
;; When pattern have one or more spaces, let
;; multi-match doing the job with no fuzzy matching.[1]
(let ((regexp (cadr (gethash 'helm-pattern helm--fuzzy-regexp-cache))))
(if (string-match "\\`!" helm-pattern)
(not (string-match regexp candidate))
(string-match regexp candidate)))))
(defun helm-fuzzy-search (pattern)
"Same as `helm-fuzzy-match' but for sources built with
(unless (string-match " " helm-pattern)
;; Same as in `helm-fuzzy-match' ref[1].
(let* ((regexps (gethash 'helm-pattern helm--fuzzy-regexp-cache))
(partial-regexp (car regexps))
(regexp (cadr regexps)))
(if (string-match "\\`!" pattern)
;; Don't try to search here, just return
;; the position of line and go ahead,
;; letting `helm-search-match-part' checking if
;; pattern match against this line.
(prog1 (list (point-at-bol) (point-at-eol))
(forward-line 1))
;; We could use here directly `re-search-forward'
;; on the regexp produced by `helm--mapconcat-pattern',
;; but it is very slow because emacs have to do an incredible
;; amount of loops to match e.g "[^f]*f[^o]*o..." in the whole buffer,
;; more the regexp is long more the amount of loops grow.
;; (Probably leading to a max-lisp-eval-depth error if both
;; regexp and buffer are too big)
;; So just search the first bit of pattern e.g "[^f]*f", and
;; then search the corresponding line with the whole regexp,
;; which increase dramatically the speed of the search.
(cl-loop while (re-search-forward partial-regexp nil t)
for bol = (point-at-bol)
for eol = (point-at-eol)
if (progn (goto-char bol)
(re-search-forward regexp eol t))
do (goto-char eol) and return t
else do (goto-char eol)
finally return nil)))))
(defun helm-score-candidate-for-pattern (candidate pattern)
"Assign score to CANDIDATE according to PATTERN.
Score is calculated for contiguous matches found with PATTERN.
Score is 100 (maximum) if PATTERN is fully matched in CANDIDATE.
One point bonus is added to score when PATTERN prefix matches
CANDIDATE. Contiguous matches get a coefficient of 2."
(let* ((cand (if (stringp candidate)
candidate (helm-stringify candidate)))
(pat-lookup (helm--collect-pairs-in-string pattern))
(str-lookup (helm--collect-pairs-in-string cand))
(bonus (cond ((equal (car pat-lookup) (car str-lookup))