Categories

# replace.el

When writing a worksheet for students, I always include the answers, as follows:

```Figure 1 shows the contents of a memory location
#+CAPTION: Figure 1
|10100111|
What is the denary equivalent of the contents of
this memory location if it represents an unsigned
binary integer? (1 mark)
ANS: 167
What is the denary equivalent of the contents of
this memory location if it represents an unsigned
binary fixed point number, with 4 bits before and
4 bits after the binary point? (2 marks)
ANS: 10.4375
What is the denary equivalent of the contents of
this memory location if it represents a two's
complement binary integer? (2 marks)
ANS: -89
What is the hexadecimalequivalent of the binary
pattern shown in Figure 1? (1 mark)
ANS: A7
```

When I’ve finished I save a copy of the sheet and then remove the answers, leaving me with a worksheet and the answer sheet. Emacs makes it easy to remove the answers using

```M-x flush-lines  ^ANS:
```

As it says in the documentation, flush-lines deletes lines containing matches for REGEXP.

Use flush-lines to delete blank lines as follows:

```M-x flush-lines ^\$
```

flush-lines is part of replace.el. There are some nice functions in replace.el As it says in the introductory comments:

This package supplies the string and regular-expression replace functions documented in the Emacs user’s manual.

M-x keep-lines is the inverse of flush-lines, handy if you want a sheet with the answers only

M-x how-many returns the number of occurrences of REGEXP following the point. Handy for counting how many ANS: there are.

M-x occur opens a buffer showing all lines in the current buffer containing a match for REGEXP.  See this post on stylesheets for more on this.

Lastly, map-query-replace-regexp will replace a matches for a regexp in rotation. As a simple example, suppose you want assign a group to a collection of students:

```gp: Adam
gp: Bella
gp: Carol
gp: Danuta
gp: Ed
gp: Fran
```

Select the names and

```map-query-replace-regexp
^gp:
red: blue: green:
```

gives

```red: Adam
blue: Bella
green: Carol
red: Danuta
blue: Ed
green: Fran
```