How can I improve this Emacs lisp function? - emacs

The intent is to use git grep as the command for M-x grep, and all the buffer benefits that come along with it. Desired functionality:
It reads the word/thing at point as the default value (done, sort of)
It reads the current region as the default argument if a region is set.
The following is the code I have so far:
(defun bw-read-string-at-point ()
(interactive)
(let ((word (word-at-point)))
(set-text-properties 0 (length word) nil word)
word))
(defun bw-git-grep (search-str)
"Uses `git-grep` to find `search-str`"
(interactive
(list
(read-string (format "Search for (%s): " (bw-read-string-at-point)))))
(let ((search-str (if (= (length search-str) 0)
(bw-read-string-at-point) search-str)))
(grep (concat "git --no-pager grep -i -I -nH --no-color --extended-regexp " search-str))))
I feel like the interactive bit there is quite clumsy and could be made much better.

Actually, it looks pretty good. Except you should use the default' argument ofread-string, and the interactive in bw-read-string-at-point should not be there. Or better yet, just use grep-tag-default.
Here's how I'd tweak it:
(defun bw-git-grep (search-str)
"Uses `git-grep` to find `search-str`"
(interactive
(let ((default (grep-tag-default)))
(list
(read-string (format "Search for (default %s): " default)
nil nil default))))
(grep (concat "git --no-pager grep -i -I -nH --no-color --extended-regexp " search-str)))

I would use read-from-minibuffer instead of read-string:
(defun bw-git-grep (pattern)
(interactive
(list
(read-from-minibuffer
"Search for: "
(if (region-active-p)
(buffer-substring-no-properties (region-beginning) (region-end))
(thing-at-point 'word)))))
(let* ((grep-command "git --no-pager grep -i -I -nH --no-color --extended-regexp ")
(command (concat grep-command pattern))
(grep-use-null-device nil))
(grep command)))
Also, you probably need to ensure that grep-use-null-device is nil to avoid grep appending /dev/null to your command (which git doesn't seem to like much)

Related

How to switch to a specific directory before grepping in emacs?

I am grepping across all my projects:
(defun grep-all-projects(start end)
(interactive "r")
(if (and transient-mark-mode mark-active)
(setq my-word (buffer-substring-no-properties start end))
(setq my-word (thing-at-point 'word))
)
(let ((default-directory (getenv "REPOS_DIR")))
(message "===> Grepping '%s' in %s" my-word (getenv "REPOS_DIR"))
(grep (format "grep --exclude-dir target -r -ne '%s' ." my-word)))
)
But somehow the grepping is performed on the root directory (/), even though the grep buffer correctly says:
-*- mode: grep; default-directory: "/repos/" -*-
Grep started at Tue Jun 6 10:38:08
What is going on? Is emacs grep not respecting the default-directory?
EDIT
This workaround, without making use of default-directory, works:
(defun grep-all-projects(start end)
(interactive "r")
(if (and transient-mark-mode mark-active)
(setq my-word (buffer-substring-no-properties start end))
(setq my-word (thing-at-point 'word))
)
(message "===> Grepping '%s' in %s" my-word (getenv "REPOS_DIR"))
(grep (format "grep --exclude-dir target -r -ne '%s' %s" my-word (getenv "REPOS_DIR")))
)
I am still interested in knowing why the first implementation does not work as expected
M-x cd changes to a directory you input. It changes the value of buffer-local variable default-directory. C-h f cd tells you:
cd is an interactive compiled Lisp function in files.el.
(cd DIR)
Make DIR become the current buffer's default directory.
If your environment includes a CDPATH variable, try each one of
that list of directories (separated by occurrences of
path-separator) when resolving a relative directory name.
The path separator is colon in GNU and GNU-like systems.

how to specify multiple file extensions in rgrep?

I tried *.{cc,hh} but it doesn't work (this works for lgrep though). i also tried the method suggested her e http://compgroups.net/comp.emacs/searching-multiple-file-types-with-rgrep/95027 but it seems the interactive mode doesn't allow me to input space. Any idea?
*.cc *.hh is correct. The find command will then use something like:
\( -iname \*.cc -o -iname \*.hh \)
(If you supply a prefix argument, you can view/edit the command before it is executed.)
You can enter the space using quoted-insert: C-qSPC, or just-one-space: M-SPC
I was (in despair) rolling an elisp solution:
(defun mrgrep (pattern extensions dir)
(interactive "ssearch for: \nsextensions (space separated, no *): \nD")
(setq includes (mapconcat (lambda (ext)
(concat (format "--include=\"\\*%s\"" ext)))
(s-split " " extensions)
" "))
(setq cmd (format "grep -ir %s %s %s"
includes
pattern
(concat dir "*")))
(setq cmd (read-from-minibuffer "run grep like this: " cmd))
(compilation-start cmd 'grep-mode)
)
but phils explained how to enter the space !

Run commands in Emacs asynchronously, but display output incrementally

I have a utility function:
(defun execute-in-buffer (command-with-args buffer)
"Execute a string COMMAND-WITH-ARGS representing a shell command with arguments,
inserting the results in BUFFER."
(switch-to-buffer buffer)
(insert (format ">>> %s\n" command-with-args))
(let* ((command-args-list (s-split " " command-with-args))
(command (car command-args-list))
(args (cdr command-args-list)))
(apply 'call-process command nil buffer t args)))
This allows me to do things like (execute-in-buffer "ls /" (get-buffer-create "*my-output*"). However, it's not well suited for slow commands. If I call a series of slow commands, I don't get any output until the very end:
(let ((buf (get-buffer-create "*my-output")))
(execute-in-buffer "sleep 10" buf)
(execute-in-buffer "ls /" buf))
I want to be able to call synchronously, so the next command only runs after the previous one finishes. However, I want to see the output from my commands as they run. How would I do this?
(Example code is just for show, I'm happy to drop it in favour of something else.)
Using synchronous processes
If you want to stick with synchronous processes (e.g. using call-process), you need to call (redisplay) after each call to execute-in-buffer for the display to be updated and the output to be visible (also see this question for more details). However, the output of each command will not be visible until the process terminates, and emacs will hang while the external processes are running.
Using asynchronous processes
Using asynchronous processes is a bit more complicated, but avoids hanging Emacs while the commands are running, which also solves the redisplay issue. The tricky part here is to sequentially chain all commands. Here is a bit of elisp which should do the trick:
(defun execute-commands (buffer &rest commands)
"Execute a list of shell commands sequentially"
(with-current-buffer buffer
(set (make-local-variable 'commands-list) commands)
(start-next-command)))
(defun start-next-command ()
"Run the first command in the list"
(if (null commands-list)
(insert "\nDone.")
(let ((command (car commands-list)))
(setq commands-list (cdr commands-list))
(insert (format ">>> %s\n" command))
(let ((process (start-process-shell-command command (current-buffer) command)))
(set-process-sentinel process 'sentinel)))))
(defun sentinel (p e)
"After a process exited, call `start-next-command' again"
(let ((buffer (process-buffer p)))
(when (not (null buffer))
(with-current-buffer buffer
;(insert (format "Command `%s' %s" p e) )
(start-next-command)))))
;; Example use
(with-current-buffer (get-buffer-create "*output*") (erase-buffer))
(execute-commands "*output*"
"echo 1"
"sleep 1"
"echo 2; sleep 1; echo 3"
"ls /")
This works for me:
(async-shell-command "echo 1; sleep 10; echo 2; sleep 10; ls /" "*abcd*")
This can be adapted to do what you need?

Org-Mode Babel, switches for code blocks: Can I set defaults?

In org mode, I can insert source in my org files. There are many header arguments, and I found how to set defaults. So I am down to only switches (here -n -r -l "..")
#+BEGIN_SRC emacs-lisp -n -r -l ";(ref:%s)"
..
#+END_SRC
As I want to use these as site default: How can I set defaults for such switches?
Best in .emacs, but defaults valid for a file/buffer would be of help too.
You can start with this hack
(defadvice org-babel-parse-src-block-match (after org-babel-add-switches activate)
"Add extra-sw to 3th element of the return value"
(let ((extra-sw "-t -w 200"))
(setq v (vconcat ad-return-value))
(aset v 3 (concat (elt v 3) " " extra-sw))
(setq ad-return-value (append v nil))))

Update multi-term buffer name based on PWD

If I use konsole or other terminal, the terminal tag name can change based on PWD. But in multi-term, the buffer name is *terminal<number>*. This is not very nice. Because when I switch between them, the name is not very informative. So I want to rename it based on PWD.
I find that the Enter key is bind to term-send-raw, so I write a function
(defadvice term-send-raw (around rename-term-name activate)
(progn
(rename-buffer
(concat "⇒ "
(shell-command-to-string "pwd | xargs basename | tr -d '\n'")
(format-time-string " [%M ∞ %S]")))
ad-do-it))
But the problem is pwd command return the PWD of the terminal buffer, while it is not the PWD of the SHELL in that terminal.
The PWD of the terminal buffer is set by defcustom multi-term-default-dir. And it does not change when the PWD change in the SHELL.
(defcustom multi-term-default-dir "~/"
"The default directory for terms if current directory doesn't exist."
:type 'string
:group 'multi-term)
How can I get the PWD of the SHELL in the terminal?
Regards.
AFAIK there is no easy way to retrieve information from a running process.
But if you want to get the current directory you could:
ask the shell to print it
parse and trace the command-line for functions like cd, pushd, popd…
poll /proc/PID/cwd
The first method is described in the header of term.el (M-xfind-libraryRETtermRET).
And now, thank you for your question, you gave me the opportunity to do this:
(defadvice term-send-input (after update-current-directory)
(let* ((pid (process-id (get-buffer-process (current-buffer))))
(cwd (file-truename (format "/proc/%d/cwd" pid))))
(cd cwd)))
(ad-activate 'term-send-input)
It's a naive implementation of the third method and it doesn't work if the user uses su or ssh. However, I don't know if it's possible withouth using the first or the second method.
In your case, you can just replace the cd command with whatever you want.
Building off of Daimrod's answer for polling /proc/PID/cwd, I found a way get around the problem that Reed pointed out where the advice doesn't pick up the updated CWD immediately and you have to hit Enter twice.
If you move the CWD update code to its own function and use run-at-time to call it from the advice at a later time, it will pick up the updated CWD correctly. Unfortunately I don't know enough about Emacs' scheduling to explain why this works (any enlightenment would be appreciated).
Here's my code based on Daimrod's. Note I advised term-send-input for line-mode and term-send-return for char-mode. I tested this using multi-term on Emacs 24.3.1:
(defadvice term-send-input (after update-current-directory)
(run-at-time "0.1 sec" nil 'term-update-dir)
)
(ad-activate 'term-send-input)
(defadvice term-send-return (after update-current-directory)
(run-at-time "0.1 sec" nil 'term-update-dir)
)
(ad-activate 'term-send-return)
(defun term-update-dir ()
(let* ((pid (process-id (get-buffer-process (current-buffer))))
(cwd (file-truename (format "/proc/%d/cwd" pid))))
(unless (equal (file-name-as-directory cwd) default-directory)
(message (concat "Switching dir to " cwd))
(cd cwd)))
)
Most terminals get their window name from the command echo -en. In zsh you can put this in your ~/.zshenv
precmd() { echo -en "\e]0;`basename ${PWD}`\a" }
and that will get the basename of your PWD environment variable. Ideally multi-term would do something similar and put it in multi-term-buffer-name, which is the variable which holds its buffer name.
Yes, this is not a complete solution. I'm hoping for one too!
Try this:
(defun open-or-jump-to-multi-term ()
(interactive)
(if (string-prefix-p "*terminal<" (buffer-name))
(delete-window)
(progn
(setq bufname (concat "*terminal<" (directory-file-name (file-name-directory (buffer-file-name))) ">"))
(if (get-buffer-process bufname)
(switch-to-buffer-other-window bufname)
(progn
(split-window-right)
(other-window 1)
(multi-term)
(rename-buffer bufname)
)
)))
)
(global-set-key (kbd "C-`") 'open-or-jump-to-multi-term)