index rss mastodon twitter github linkedin email
Álvaro Ramírez
sponsor

Álvaro Ramírez

07 July 2017 Search/insert one-liners with Emacs helm-ag

Emacs helm is awesome. helm-ag is double awesome. Searching for one-liners in your codebase, narrowing down with helm, and easily inserting is triple awesome.

helm-ag-insert.gif

(defun ar/helm-ag (arg)
  "Helm-ag search remembering last location.  With ARG, forget the last location."
  (interactive "P")
  (defvar ar/helm-ag--default-locaction nil)
  (setq ar/helm-ag--default-locaction
                 (read-directory-name "search in: " (if arg
                                                        default-directory
                                                      ar/helm-ag--default-locaction) nil t))
  (helm-do-ag ar/helm-ag--default-locaction))

(defun ar/helm-ag-insert (arg)
  ;; Helm-ag and insert match.
  (interactive "P")
  (let* ((actions (helm-make-actions
                   "Insert"
                   (lambda (candidate)
                     ;; Drop file:line:column. For example:
                     ;; arc_hostlink.c:13:2:#include <linux/fs.h>
                     ;; => #include <linux/fs.h>
                     (insert (replace-regexp-in-string "^[^ ]*:" "" candidate)))))
         (helm-source-do-ag (helm-build-async-source "The Silver Searcher"
                              :init 'helm-ag--do-ag-set-command
                              :candidates-process 'helm-ag--do-ag-candidate-process
                              :persistent-action  'helm-ag--persistent-action
                              :action actions
                              :nohighlight t
                              :requires-pattern 3
                              :candidate-number-limit 9999
                              :keymap helm-do-ag-map
                              :follow (and helm-follow-mode-persistent 1))))
    (call-interactively #'ar/helm-ag)))