スクリプト言語 emacs

テキスト処理に今まで Sed/Awk/Perl/Ruby を使ってきたが、emacs を使ったことはなかった。Emacs 使いとして怠慢の極みだ。_| ̄|○

ありえるえりあ - Emacs Lisp を仕事で使ってみた

「--script」 オプションの説明は man emacs ではでてこないが、info emacs した後に検索(/) するとノード「Initial Options」で発見できる。

`--script FILE'
     Run Emacs in batch mode, like `--batch', and then read and execute
     the Lisp code in FILE.

     The normal use of this option is in executable script files that
     run Emacs.  They can start with this text on the first line

          #!/usr/bin/emacs --script

     which will invoke Emacs with `--script' and supply the name of the
     script file as FILE.  Emacs Lisp then treats `#!'  as a comment
     delimiter.

dolist と with-current-buffer が重要なので、ヘルプを見ながら使い方を確認する。関数 dolist は リストを逐次、一時変数に代入していき、その後の式を評価していく。Ruby で言うと each みたいな感じ。

使用例

(dolist (x '("a" "b" "c"))
  (insert x))

Ruby でいうとこんな感じ。

ruby -e '["a", "b", "c"].each do |x| print x end'

関数 with-current-buffer はバッファに対してその後の式を実行していく。

使用例

(with-current-buffer (current-buffer) (goto-char (point-min)))

ここまでわかったら、cat コマンドを作成してみる。

#!/usr/local/bin/emacs --script 

(dolist (file command-line-args-left)
	(with-current-buffer (find-file-noselect file)
		(send-string-to-terminal (buffer-string))))

ついでに行番号を表示する catn コマンドも作成してみる。ここでは awkperl -e 'while (<>) { ... }' のような行ループを作成して、行ごとに処理をさせている。

#!/usr/local/bin/emacs --script 

(dolist (file command-line-args-left)
  (with-current-buffer (find-file-noselect file)
    (goto-char (point-min))
    (let ((ln 1)(beg)(end))
      (while (not (eobp))
        (beginning-of-line)
        (setq beg (point))
        (end-of-line)
        (setq end (point))
        (send-string-to-terminal (concat (format "%4d " ln) (buffer-substring beg end) "\n"))
        (setq ln (+ 1 ln))
        (next-line)))))


追記:

info コマンドでキーワードサーチや該当個所へのジャンプができる。¢(. .。)メモメモ…。

$ info --apropos script | grep emacs && info emacs "Initial Options"