Saturday, February 01, 2014

Interaction between bash and dired in Emacs

Switch back and forth between Dired on Emacs and bash on Terminal is a headache. Add a visiting directory onto "~/.bash_history" and refer it by "tail -n 1" will help with following setup.

on ~/.emacs.d/init.el
(require 's)
(add-hook 'dired-mode-hook 'append-pwd-bash-history)
(add-hook 'find-file-hook 'append-pwd-bash-history)
(defun append-pwd-bash-history (&optional DIR)
  "Append a DIR where Dired visited to `~/.bash_history'."
  (interactive)
  (setq DIR (or DIR (expand-file-name default-directory)))
  (let ((DIROUT DIR))
    (with-current-buffer (find-file-noselect "~/.bash_history") ;; $HISTFILE
      (if windows-p
          (setq DIROUT (shell-command-to-string (format "cygpath %s" (shell-quote-argument DIR)))))
      (setq DIROUT (replace-regexp-in-string "\\([@ #]\\)" "\\\\\\1" DIROUT)) ; escape
      (unless (string= DIROUT "")
        (goto-char (point-max))
        (insert (format "cd %s\n" (s-chomp DIROUT)))
        (basic-save-buffer)))))
 on ~/.bashrc
function cdd {
  lastdir=`grep "^cd /[a-zA-Z0-9]" $HOME/.bash_history | tail -1 | awk '{print $2}'`;
  if [ "$lastdir" != "" ] ; then
    cd "$lastdir";
  fi
  echo cd `pwd`;
}

2 comments:

Jean-Pierre De Schacht said...

WARNING:
When you have an interactive shell running while using this feature in
emacs, you need to run `history -r' in the shell. You can then cd to
the last directory accessed in emacs using the shell history keys (up
arrow to see the last cd)

If you don't run the history command, and you close the interactive
shell, the commands that emacs added to bash_history will be lost.

tak.kunihiro said...

Thank you for the comment. I understand that `history -r' is useful in some cases; however, I run 7 bash sessions at the same time using GNU screen. With the option, previous command is shared among
sessions and problematic. I think without the option is more
realistic. Anyway I appreciate again for your comment. Happy
Hacking!