by shigemk2

当面は技術的なことしか書かない

sort-words.elを読んでみる

replace-regexp-in-regionの使い方を調べていたら出てきた

emacs.rubikitch.com

ソースコードを読もうと言われたから読んでみた

github.com

主要なコード region内のワードをソートするelisp functionだけれど、

  • regionの先端末端のポインタであるpoint-min point-maxをsort-words-sortedに放り込む
  • sort-words-sortedの中でsort-words-in-regionを実行し、sort-words-in-regionの中でbuffer-substring-no-propertiesでregionの中身をstringに変換しつつsplit-stringしたりsortしたりしたものをconcatする
  • delete-regionしてpoint-minに戻しつつ、sort-words-sortedの結果をバッファにinsertする(save-excursionとsave-restrictionのコンボ)
(defun sort-words-in-region (start end)
  "Sort the words in a given region (START and END) and return them as a list."
   (sort (split-string (buffer-substring-no-properties start end)) #'string<))

(defun sort-words-sorted (start end)
  "Sort the words in a given region (START and END) and return them as a string."
  (mapconcat 'identity (sort-words-in-region start end) " "))

;;;###autoload
(defun sort-words (start end)
  "Sort words in region alphabetically.
Then insert them replacing the existing region.
START and END are boundries of the selected region."
  (interactive "r")
  (save-excursion
    (save-restriction
      (narrow-to-region start end)
      (let ((words (sort-words-sorted (point-min) (point-max))))
        (delete-region (point-min) (point-max))
        (goto-char (point-min))
        (insert words)))))

www.gnu.org

www.math.s.chiba-u.ac.jp