echo Impossible|sed 's/Im/To be /'

May 04, 2015

Emacs Elisp script

用 Emacs lisp 當 script language

與 Emacs 相處越久,越習慣 elisp 後,漸漸把常用的工具也 elisp 化。底下簡單記錄幾個入門用法。

Elisp with arguments

$> cat elisp-argv.el

#!/bin/sh
":"; exec emacs --no-site-file --script "$0" -- "$@" # -*-emacs-lisp-*-
(princ (format "hello %s!\n" argv))
(while argv
  (princ (format "Hello %s!\n" (pop argv))))

$> chmod +x elisp-argv.el
$> ./elisp-argv.el lloyd huang
hello (-- lloyd huang)!
Hello --!
Hello lloyd!
Hello huang!

Elisp with standard input

$> cat elisp-stdin.el

#!/bin/sh
":"; exec emacs --no-site-file --script "$0" -- "$@" # -*-emacs-lisp-*-
(let (line)
  (while (setq line (ignore-errors (read-from-minibuffer "")))
    (princ (format "--> [%s]!\n" line))))

$> chmod +x elisp-stdin.el
$> cat /etc/passwd | ./elisp-stdin.el
--> [root:x:0:0:root:/root:/bin/bash]!
--> [bin:x:1:1:bin:/bin:/bin/false]!
skip ...

Elisp enable debug mode

$> cat elisp-debug.el

#!/bin/sh
":"; exec emacs --no-site-file --script "$0" -- "$@" # -*-emacs-lisp-*-
(setq debug-on-error t)
(typo-err)

$> chmod +x elisp-debug.el
$> ./elisp-debug.el
Debugger entered--Lisp error: (void-function typo-err)
  (typo-err)
  eval-buffer(#<buffer  *load*> nil "elisp-debug.el" nil t)  ; Reading at buffer position 118
  load-with-code-conversion("elisp-debug.el" "elisp-debug.el" nil t)
  load("elisp-debug.el" nil t t)
  command-line-1(("-scriptload" "./elisp-debug.el" "--"))
  command-line()
  normal-top-level()

Elisp exit

$> cat elisp-exit.el

#!/bin/sh
":"; exec emacs --no-site-file --script "$0" -- "$@" # -*-emacs-lisp-*-
(princ "hi all 1")
(kill-emacs)
(princ "hi all 2")

$> chmod +x elisp-debug.el
$> ./elisp-exit.el
hi all 1

Posted by Lloyd Huang in on May 04, 2015