Elisp: 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.
here it is:
(defun xwe-move-word-to-page (@category) "Take current selection or block of text, ask which page to move it to." (interactive (list (ido-completing-read "Which:" '("specialwords" "arcane" "combowords" "easy" "foreignwords" "gre" "hyphwords" "informal" "slang" "noun" "noun_things" "noun_abs" "poesy" "satwords" "writerwords")))) (let ( p1 p2 $wordText ($destFile (concat @category ".html"))) (if (use-region-p) (progn (setq p1 (region-beginning)) (setq p2 (region-end))) (save-excursion (if (re-search-backward "\n[ \t]*\n" nil "move") (progn (re-search-forward "\n[ \t]*\n") (setq p1 (point))) (setq p1 (point))) (if (re-search-forward "\n[ \t]*\n" nil "move") (progn (re-search-backward "\n[ \t]*\n") (setq p2 (point))) (setq p2 (point))))) (setq $wordText (buffer-substring-no-properties p1 p2)) (delete-region p1 p2 ) (find-file (concat (xahsite-server-root-path) "wordyenglish_com/words/" $destFile)) (goto-char 1) (search-forward "<section class=\"word\">") (search-backward "<") (insert $wordText "\n\n") (save-buffer ) (kill-buffer ) (message "Word moved to 「%s」" $destFile) (let* ;; save the working buffer, but make backup first (($fname (buffer-file-name)) ($backupName (concat $fname "~" (format-time-string "%Y%m%d_%H%M%S") "~"))) (copy-file $fname $backupName 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, and the section of