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 (point-min))
    (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

If you have a question, put $5 at patreon and message me on xah discord.
Or support me by Buy Xah Emacs Tutorial

Emacs Tutorial

Emacs Init

Emacs Keys


ELisp Examples

ELisp Write Major Mode

ELisp Examples

Xah Commands

Text Transform Under Cursor

Commands Do thing-at-point

Command to Insert Things

Script Examples