Some Advanced Emacs Tips

Xah Lee, 2005

This page is some advanced emacs tips. Advanced, but still commonly needed. If you don't understand what it says, you need to goto Emacs Intermediate Tips.

Search Text, Find and Replace Text

How to search text?

Press “Ctrl+s” (or “Alt+x search-forward”), then type your text. Emacs will search as you type. To advance to the next occurrence, press “Ctrl+s” again. To go to previous occurrence, type “Ctrl+r”. When done, press Enter to place the cursor at the current spot, or type “Ctrl+g” to return to the spot before search was started.

This command is also under the menu “Edit‣Search”.

To search for the word that is under cursor, type “Ctrl+s Ctrl+w”. This can save you some typing. Also, “Ctrl+s” twice will search your last search.

How to find and replace?

Type “Alt+%” (or “Alt+x query-replace”). Then, emacs will prompt you for the find string and replace string. Once emacs found a match, you can type “y” to replace, “n” to skip, or “!” to do all replacement without asking. To cancel further finding, type “Ctrl+g”. You can undo the previous replacement after you type “Ctrl+g”.

If you want to use regex pattern, type “Ctrl+Alt+%” (or “Alt+x query-replace-regexp”). These commands are under the menu “Edit‣Replace”.

If you would like to do replacement on a region, in one shot, without emacs prompting you for each match, you can type “Alt+x replace-string” or “Alt+x replace-regexp”.

For detailed turorial on issues of matching or replacing letter cases, see: Find and Replace with Emacs.

Find and Replace menus in emacs

Whatever you do in emacs, don't forget the power of the graphical menu. Where, everything you wanted to do or needs to know can be found within.

How to find and replace for all files in a dir?

Type “Ctrl+x d”, type the dir path, mark the files you want to work on (“m” to mark, “u” to unmark), then press Q (which invokes dired-do-query-replace-regexp.).

Once in dired, you can find the command under the menu “Operate‣Query Replace in Files...”.

For a detailed, step-by-step tutorial, see Interactive Find and Replace String Patterns on Multiple Files.

Editing Related Questions

How to add a prefix to every line? (such as # or //)

Mark (Ctrl+Space) the beginning of first line and move cursor to the beginning of the last line, then do “Alt+x string-rectangle” (Ctrl+x r t), then type what you want to insert. This command can be used to insert a string across mulitple lines not just at their beginning position, but any position in a block of lines.

Alternatively, you can select a region and do “Alt+;” to make the region into a comment or uncomment block specific to your language's mode.

How to delete the first few n chars of every line?

Mark (Ctrl+Space) the beginning of first line and move cursor to the last line, and move it to the right n chars. Then do “Alt+x kill-rectangle” (Ctrl+x r k). This command can be used to delete any rectangular block of text, not just at the beginning of lines.

How to replace unprintable characters such as tabs or line return chars in Emacs?

Use any of the find/replace commands (Example: Alt+x query-replace) as usual, type the unprintable char by preceding it with “Ctrl+q”. Example: type “Alt+% Ctrl+q Ctrl+j Enter Space Enter”, will replace all returns with spaces.

The “Ctrl+q” does the command quoted-insert, which will let you enter the next charater literally. For example, to type a literal tab, press “Ctrl+q” then the Tab key. Some characters do not have a representation on the keyboard (for example, unix's line return the form feed), so emacs provides the “Ctrl+j” method to input them. Here's a short table on how to enter common unprintable chars:

NameASCII Codestring notationCaret NotationInput method
horizontal tab9\t^ICtrl+q Ctrl+i or Ctrl+q Tab
line feed10\n^JCtrl+q Ctrl+j
carriage return13\r^MCtrl+q Ctrl+m or Ctrl+q Enter

If you are confused by all these notations, see this article The Confusion of Emacs's Keystroke Representation for a explanation.

How to change file line endings between Mac/Dos/Unix?

Open the file, then do “Alt+x set-buffer-file-coding-system” (Ctrl+x Enter f). Give it a value of mac, dos, unix. Then, when you save the file, it'll be saved with the proper encoding for newlines.

Note: Unixes (including Linuxes and Mac OS X) uses LF (ascii 10; line feed) for newline. Mac OS Classic uses CR (ascii 13; carriage return) for newline. (Mac OS X prefers LF but accepts CR too) Windows uses CR followed by LF ("\r\n") for its newline char. See wikipedia newline for detail.

To do it batch on a list of files, use the following lisp code:

(defun to-unix-eol (fpath)
  "Change file's line ending to unix convention."
  (let (mybuffer)
    (setq mybuffer (find-file fpath))
    (set-buffer-file-coding-system 'unix) ; or 'mac or 'dos
    (save-buffer)
    (kill-buffer mybuffer)
   )
)

(mapc 'to-unix-eol
 (list
"~/jane/myfile1"
"~/jane/myfile2"
"~/jane/myfile3"
; ...
  )
)

To use the code, first edit the list of files above. Then, select all the code, type “Alt+x eval-region”. That's it.

If you want the function to work on marked files in dired, then use the following code:

(defun dired-2unix-marked-files ()
  "Change to unix line ending for marked (or next arg) files."
  (interactive)
  (mapc 'to-unix-eol (dired-get-marked-files))
)

Select the code and do “Alt+x eval-region”, then “Alt+x dired”, then press “m” to mark the files you want, then do “Alt+x dired-dos2unix-marked-files”.

How to record a sequence of keystrokes?

To record keystrokes, type “Ctrl+x (” then start typing your keystrokes. When done, type “Ctrl+x )”. This records your keystrokes. To run the keystrokes you've recorded, type “Ctrl+x e”.

Here are the command names and their shortcuts:

start-kbd-macro            Ctrl+x (
end-kbd-macro              Ctrl+x )
call-last-kbd-macro        Ctrl+x e

If you want to use your keyboard macro for future use, you can save it. To save the macro, first type “Alt+x name-last-kbd-macro”, then type “Alt+x insert-kbd-macro”, which will insert the lisp code for the keyboard macro at the cursor point. Put the code in your emacs init file (usually at “~/.emacs”). Then, you can execute your keyboard macro like this: “Alt+x yourMacroName” the next time you start emacs.

How to have spell-checker turned on?

Type “Alt+x flyspell-mode” or “Alt+x flyspell-buffer”. To have it always on, put in your emacs init file this code: “(add-hook 'text-mode-hook (lambda () (flyspell-mode 1)))”.

This is under the menu “Tools‣Spell Checking”.

Emacs Customization

How to disable emacs's automatic backup?

Use this code “(setq make-backup-files nil)”.

How to stop emacs's backup changing the file's creation date of the original file?

Put this code in your emacs init file: “(setq backup-by-copying t)

Explanation: when emacs does a backup, by default it renames the original file into the backup file name, then create a new file and insert the current data into it. This effectively destroys the creation date of your file. (In short, all files you've edited, their creation date becomes the last modification date. Note: file systems used by unix (and linux) do not record file creation date. File systems used by Windows and OS X does record file creation date.).

How to set emacs so that all backups are directed into one folder? (such as at a directory "~/myBackups")

Use the following lisp code in init file:

; return a backup file path of a give file path
; with full directory mirroring from a root dir
; non-existant dir will be created
(defun my-backup-file-name (fpath)
  "Return a new file path of a given file path.
If the new path's directories does not exist, create them."
  (let (backup-root bpath)
    (setq backup-root "~/.emacs.d/emacs-backup")
    (setq bpath (concat backup-root fpath "~"))
    (make-directory (file-name-directory bpath) bpath)
    bpath
  )
)
(setq make-backup-file-name-function 'my-backup-file-name)

The above will mirror all directories at the given backup dir. For example, if you are editing a file “/Users/jane/web/xyz/myfile.txt”, and your backup root is “/Users/jane/.emacs.d/emacs-backup”, then the backup will be at “/Users/jane/.emacs.d/emacs-backup/Users/jane/web/xyz/myfile.txt~”.

If you want all backup to be flat in a dir, use the following:

(setq backup-directory-alist '(("" . "~/.emacs.d/emacs-backup")))

This will create backup files flat in the given dir, and the backup file names will have “!” characters in place of the directory separator. For example, if you are editing a file at “/Users/jane/web/xyz/myfile.txt”, and your backup dir is set at “/Users/jane/.emacs.d/emacs-backup”, then the backup file will be at: “/Users/jane/.emacs.d/emacs-backup/Users!jane!web!emacs!myfile.txt~”. If you use long file names or many nested dirs, this scheme will reach file name length limit quickly.

How to startup emacs without loading any customization?

To run emacs without loading the “.emacs” init file, start emacs like this: “emacs -q”. To not load any site-wide startup file, start emacs with “emacs -q -no-site-file”. Type “info emacs” in the command line for detail.


Related essays:

2005-08
© 2005 by Xah Lee.