Category Archives: editing

Use LaTeX syntax to enter non-standard characters

Sometimes it is handy to be able to enter non-standard characters in emacs documents. For example I sometimes need to use a £ symbol but my US keyboard doesn’t have one. Other times I need to add an accent or similar to a letter like é or ö. There is a nice overview of the ways to do this at Mastering Emacs, and here I’ll pick out the method I find most useful.

Since I use LaTeX a lot and am familiar with its syntax for symbols, I use C-\ to run the command toggle-input-method and then enter TeX as the alternate input method. Now I am in TeX input mode I can enter a string like \pound and have it appear as £ or \"o to give me ö. Pressing C-\ again now toggles back and forth between normal and TeX input modes.

For symbols you use a lot, you can also set up abbreviations e.g. by entering gbp C-x a - C-\ \pound we set the text gbp to expand to £.

Use abbreviations to expand text

Emacs has the ability to use abbreviations to save time typing. For example, if I type fn and then press space or almost any punctuation character, it is automatically expanded to the word function. This is also great for correcting common typos, like “teh” for “the”.

To make this work the most seamlessly, paste the following lines into your emacs config file, changing the location of your abbreviation file if you want:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; abbreviations                                                          ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setq-default abbrev-mode t)
;; save abbreviations upon exiting xemacs
(setq save-abbrevs t)
;; set the file storing the abbreviations
(setq abbrev-file-name "~/docs/my-abbreviations.el")
;; reads the abbreviations file on startup
(quietly-read-abbrev-file)

and then highlight the lines and run M-x eval-region or restart emacs.

Now you can type the abbreviation you want, followed by C-x a - and you will be prompted for the expanded text. e.g. to set up the abbrevation above, I used

fn C-x a - function

You can set as many of these as you want. You will be asked if you want to save your abbreviations when you exit emacs.

If you type something that you don’t want to be expanded, then follow the abbreviation with C-q, so typing fn C-q SPACE will give you the string fn followed by a space.

Convert tabs to spaces

To replace tabs with the appropriate number of spaces, use M-x untabify.

To do the reverse and convert multiple spaces to tabs, you can use M-x tabify.

Both commands work on a region. To run on the whole buffer use a prefix argument (i.e. C-u M-x untabify).

Append to kill-ring

We previously looked at cycling through the history of the kill-ring (emacs’ clipboard). A somewhat related idea is that you can append text that you cut or copy onto the last entry of the kill-ring so that you can accumulate several pieces of text into a single clipboard entry.

You do this by preceding a cut or copy command with C-M-w (this also happens automatically if you use successive cut/copy commands without anything else in between).

This is explained in the emacs manual, but as a simple illustration in the animation below I cut the line bbbbbbb and then move to the ddddddd line and hit C-M-w before cutting that line. My paste command then pastes the two lines.

append-to-kill-ring.gif

Prettier text replacement with anzu

We recently introduced basic text replacement, but it is easy to make things a bit snazzier. You can preview the replacement by installing the anzu package, and then adding the following to your emacs config file:

(require 'anzu)
(global-anzu-mode)
(global-set-key (kbd "M-%") 'anzu-query-replace)
(global-set-key (kbd "C-M-%") 'anzu-query-replace-regexp)

This is illustrated in the example below from my post on renaming multiple files in dired – note how when I replace “foo” with “bar” you see the replacement text previewed next to the original text

dired-rename.gif

If you use my recommended setup, prelude, this behaviour is the default,so you shouldn’t need to do anything.

Basic text replacement

You can replace text using M-% (which runs the command query-replace). For example, to replace “foo” with “bar”, use M-x RET foo RET bar and then emacs will step through all the occurrences of “foo” asking if you want to replace them. You can hit y, n, to say yes or no to each, or ! to say yes to all.

Replacement runs from the current cursor position, so to run it everywhere in the buffer, you can jump to the start of the buffer first. Also, remember that when you have finished with your search and/or replace, you can jump back to where you started with C-u SPACE.

Note also, that if you highlight a region, then query-replace will only run on the selected region.

Later on we’ll come back to this topic to look at more advanced text replacement using regular expressions and other neat additions.

Sort lines in a region

Select a region of text and then use M-x sort-lines to sort the lines into alphabetical order (really ascii-betical order). To reverse the sort, we give the command a prefix argument by using C-u M-x sort-lines. The keybinding C-u provides a prefix argument to the command that follows. In the case of sort-lines, the documentation (C-h f sort-lines) tells us that giving an argument will reverse the sort, hence using C-u.

To sort numerically, use M-x sort-numeric-fields. This sorts the lines into ascending numerical order. For simple tabular data, this command can sort by a particular field, if each line contains the same number of fields separated by whitespace. To do this we need to provide a numeric argument, which we do with e.g. C-u 3 M-x sort-numeric-fields to sort by the 3rd field on each line.

To reverse the numeric sort, simply perform the normal sort, and then select the region again and reverse the order of the lines with M-x reverse-region.

As a final tip, after you run the sort command, you will find that the region you originally selected is no longer highlighted, but you need it to be to run reverse-region. Don’t touch the mouse, just hit C-x C-x (which runs the command exchange-point-and-mark) which exchanges the point (the cursor) and the mark (the beginning of the region you previously selected) and activates (highlights) the region between them. The net effect is that the region you previously selected is now selected again.

Update

As pointed out below by commenter Noam Postavsky, you do not need to use C-x C-x to reactivate the region before using reverse-region. This is because the region still exists even though it is not highlighted, so the reverse-region command works just fine. I’ve written a short post about emacs regions to clarify this behaviour for myself.

Advanced undo/redo with undo-tree

In emacs, by default C-/ runs the command undo, which does what you would expect and undoes your changes to the current buffer. However, there is a really great upgrade to this called undo-tree which records and visualises your undo history as a branching tree. Install this package, and then add the following to your emacs config file

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; undo tree mode                                                         ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;turn on everywhere
(global-undo-tree-mode 1)
;; make ctrl-z undo
(global-set-key (kbd "C-z") 'undo)
;; make ctrl-Z redo
(defalias 'redo 'undo-tree-redo)
(global-set-key (kbd "C-S-z") 'redo)

Now you can use C-z for undo and C-Z for redo. Even better though is using C-x u to run undo-tree-visualize which opens a second buffer displaying a tree view of your undo history in a buffer. You can navigate this with the arrow keys and watch the main buffer change through its previous states, and hit q to exit when you have the buffer the way you wanted it, or C-q to quit without making any changes.

In this simple illustration, I do the following:

  • type some text and then undo some of that typing
  • type some new text
  • use undo-tree to undo the new text and then switch branches to redo the old text

undo-tree.gif

Undo-tree can do other neat things too – see the web page for details.

Join line to previous line

Emacs has a slightly obscurely named command delete-indentation which is bound to M-^ which can be rather useful. From the help for the function (which you can always look up using C-h k M-^ or C-h f delete-indentation):

Join this line to previous and fix up whitespace at join.

You can use this multiple times to “gather up” lines, joining them together. The easiest way to explain is with an example:

join-lines.gif

N.B. after I have joined the lines in the example above, I used M-q to wrap (fill) the lines tidily.

Paste history

Any time you copy (M-w) or cut (C-w) anything in emacs, it is added to the kill-ring (emacs’ version of a clipboard). This keeps a history of all the stuff you have previously copied or cut. After you have pasted (yanked in emacs-speak) text with C-y, you can use M-y as the next key to cycle through the history of all previous text that was cut or copied.

M-y runs the command yank-pop, but this can be substituted with fancier ways of using the kill-ring that we may come back to in due course.