0

I have created this custom grep command in Emacs to search for contacts:

 '(grep-command
   "grep --color -nH --null grep -ie '^name' -A 1 ~/diary/*.org")

I would like to be able to position my cursor automatically in the minibuffer at the start of ^name rather than at the end of the string. Is this possible?

1
  • 1
    If I understand correctly what you want, then I think the best solution is to write your own interactive function (command) which will prompt for a regexp to match, build the command-line options and pass them to the grep command. What you have already done is not really what the grep-command variable is for, since it constrains the grep command to searching just one specific file. Feb 24 '21 at 11:41
1

Set your grep command to a cons cell whose car is the string you are now using, and whose cadr is the character index where you want the cursor:

 '(grep-command (cons "grep --color -nH --null grep -ie '^name' -A 1 ~/diary/*.org" 35))

One thing to look out for is, (I don’t use customize) if the expression has to be evaluated when you set it (because evaluation would break when it is executed) then you would replace the single quote with a back-tick and put a comma before the ‘cons form so that it is immediately evaluated.

0
1

This doesn't precisely answer your question, but it shows how to position the cursor in the interactive prompt and maybe a different way you might like to solve your original problem:

(defun my/current-path ()
  (or (buffer-file-name) default-directory))

(defun my/git-root ()
  (let ((dir-path (my/current-path)))
    (and dir-path
         (file-truename (locate-dominating-file dir-path ".git")))))

(defun my/symbol-name-at-point-or-empty ()
  (if (symbol-at-point)
      (symbol-name (symbol-at-point))
    ""))

(defun my/ag-grep-find (command-args)
  (interactive
   (progn
     (grep-compute-defaults)
     (let* (
            (cmd (concat "do-search " (my/symbol-name-at-point-or-empty)))
            (one-based-cursor-position (+ (length cmd) 1)))
       (list (read-shell-command "Run find (like this): " (cons cmd one-based-cursor-position) (cons 'grep-find-history 1))))))
  (when command-args
    (let (
          (null-device nil) ; see grep
          (default-directory (my/git-root)))
      (grep command-args))))

The command do-search is a little script I made that basically does (it's actually a python script because it also adds a bunch of --exclude flags, I'm translating to bash here without testing it, sorry):

#!/bin/bash
set -e
exec rg --color=never --line-number --smart-case --no-heading --stats -M 512 --max-columns-preview -- "$@" .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.