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'."
  (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)))
 on ~/.bashrc
function cdd {
  lastdir=`grep "^cd /[a-zA-Z0-9]" $HOME/.bash_history | tail -1 | awk '{print $2}'`;
  if [ "$lastdir" != "" ] ; then
    cd "$lastdir";
  echo cd `pwd`;