The eval
solution will work, but this is a lot of stuff to type on the command-line if you use this search frequently. We can actually change the command-line parameters so that --search <string>
starts up with Emacs. Just modify your initialization file with this (if you are using lexical-binding
):
(add-to-list 'command-switch-alist '("--search" . command-line-search))
(defun command-line-search (_switch)
(let ((search-text (pop command-line-args-left)))
(add-hook ; Use a hook that runs after files load. Otherwise, your CLI
; option will have to be given AFTER any buffers that you wish to
; search, which is not great.
'window-setup-hook
#'(lambda ()
(isearch-forward
nil ; This should be t if you want regex searching.
t) ; This must be t, or the call will block, preventing the next
; line.
(isearch-yank-string search-text)))))
If you have not set lexical-binding
(the default), you have to live with a global variable, but this will do the trick:
(add-to-list 'command-switch-alist '("--search" . command-line-search))
(defvar search-text nil
"Initial text given from the CLI that will be searched.")
(defun command-line-search (_switch)
(setq search-text (pop command-line-args-left))
(add-hook ; Use a hook that runs after files load. Otherwise, your CLI option
; will have to be given AFTER any buffers that you wish to search,
; which is not great.
'window-setup-hook
#'(lambda ()
(isearch-forward
nil ; This should be t if you want regex searching.
t) ; This must be t, or the call will block, preventing the next line.
(isearch-yank-string search-text))))
Now all you have to do is emacs --search <search_term> <file>
like you wanted.