Emacs Lisp: Refactoring, Move Code to Files 🚀
This page shows a example of writing a emacs command to move a text block into a predefined set of files. When this command is called, it'll prompt you to select a category, then move the current block of text into a corresponding file.
(defun xah-words-move-word-to-page (Category) "Take current selection or block of text, ask which page to move it to. version 2022-04-07" (interactive (list (completing-read "Which:" '("specialwords" "arcane" "combowords" "easy" "foreignwords" "gre" "hyphwords" "informal" "slang" "noun" "noun_things" "noun_abs" "poesy" "satwords" "writerwords")))) (let (xp1 xp2 xwordText (xdestFile (concat Category ".html"))) (if (use-region-p) (setq xp1 (region-beginning) xp2 (region-end)) (save-excursion (if (re-search-backward "\n[ \t]*\n" nil "move") (progn (re-search-forward "\n[ \t]*\n") (setq xp1 (point))) (setq xp1 (point))) (if (re-search-forward "\n[ \t]*\n" nil "move") (progn (re-search-backward "\n[ \t]*\n") (setq xp2 (point))) (setq xp2 (point))))) (setq xwordText (buffer-substring-no-properties xp1 xp2)) (delete-region xp1 xp2) (find-file (concat "~/web/xahlee_org/wordy/words/" xdestFile)) (goto-char 1) (search-forward "<section class=\"word88\">") (search-backward "<") (insert xwordText "\n\n") (save-buffer) (kill-buffer) (message "Word moved to 「%s」" xdestFile) (let* ;; save the working buffer, but make backup first ((xfname (buffer-file-name)) (xbackupName (concat xfname "~" (format-time-string "%Y%m%d_%H%M%S") "~"))) (copy-file xfname xbackupName t) (save-buffer))))
So now, i press a key, then the text block under cursor is moved to a appropriate file in the appropriate location. This is used for my vocabulary collection page: Wordy English: Vocabulary Compilation with Usage Examples.
Now, to move the current paragraph to a file, it takes me just 2 seconds. Otherwise, it'll take about 15 seconds (using all emacs tricks to cut current text block, open/switch to the appropriate file, locate the position to insert, insert, save and close).
You can use this code to refactor programing source code. You'll need to modify the list of category.