Elisp: Refactoring, Move Code to Files

By Xah Lee. Date: . Last updated: .

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."
   (list (ido-completing-read "Which:" '("specialwords"
  (let (
        ($destFile (concat @category ".html")))
    (if (use-region-p)
          (setq p1 (region-beginning))
          (setq p2 (region-end)))
        (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)

        ;; 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 xahsite-server-root-path

Elisp Commands Do thing-at-point

  1. Count Words
  2. Run Current File
  3. Delete Current File
  4. Copy File Path
  5. Convert Line Ending
  6. Make Backup
  7. Copy Column of Text to Clipboard
  8. Convert Image File
  9. Dired Rename Space to Hyphen
  10. Python 2to3 Wrapper
  11. Move Code to Files
  12. Update Web Feed
  13. Updating Page Tags
  14. Single Key Copy/Paste Register

If you have a question, put $5 at patreon and message me.
Or Buy Xah Emacs Tutorial
Or buy a nice keyboard: Best Keyboards for Emacs


Emacs Lisp