Skip to content

Instantly share code, notes, and snippets.

@mooz
Created December 1, 2010 04:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mooz/722978 to your computer and use it in GitHub Desktop.
Save mooz/722978 to your computer and use it in GitHub Desktop.
Emacs でバッファ中の数値をインクリメント

Emacs でバッファ中の数値をインクリメント

こんにちは. 今日はバッファ中の数値をそれぞれインクリメントする方法をご紹介したいと思います.

query-replace-regexp

まず query-replace-regexp を実行します.

そして, 置換対象のパターンに

([0-9]+)

を指定します. (数値にマッチすれば何でも良い)

次に, 置換するパターンに

,(1+ (string-to-number \1))

などと指定します.

ここに出てくる \,(sexp) が今回のポイント. これは sexp に書いた任意の S 式の評価結果を置換後の文字列として使用してくれる, とっても強力な構文なんですねー.

もちろん S 式の中では \1, \2, などとして正規表現中にグルーピングした部分の文字列を参照することが可能です.

なにこれ便利……!

この構文, 案外知られてないみたいなんですよね. もったいない><

@mooz
Copy link
Author

mooz commented Jan 24, 2012

For non-interactive calls of query-replace-regexp, we cannot use \,(sexp). Use conbination of re-search-forward and match-string idiom.

(while (re-search-forward "^\\([ ]+\\)" nil t)
  (replace-match
   (make-string (length (match-string 1)) ?\t)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment