Manipulating Strings: Yodaizer

Let’s make a function that talks like Yoda. It will take a sentence like “This is instructive” and output “Instructive, this is.”

To do this we’ll need to teach Emacs some adjectives:

1: (setq adjectives '("happy" "sad" "fun" "clever" "instructive"))

We’ll split the sentence into a list of words, and we’ll prepare an empty list for the result of the function:

1: let (  (result '())
2:         (words (split-string s))
3:      )

We’ll use a dolist macro to traverse the words, checking for adjectives, and we’ll use the old lisp trick of concatenating the word we’ve found at the front or the back of the result list, as appropriate.

1: (dolist (element words result)
2: (if (member element adjectives) (setq result (concat (capitalize element) ", " result)) (setq result (concat result " " element))  )
3: )

Lastly, we won’t forget to captalize the first word of the sentence and add a comma…

1: (concat (capitalize element) ", " result)

Put it together and we get the finished function:

 1: (defun yodaizer (s)
 2: "Moves adjective to the front of the sentence."
 3: (interactive "sInput a phrase:")
 4: (setq adjectives '("happy" "sad" "fun" "clever" "instructive"))
 5: 
 6: (let (  (result '())
 7:         (words (split-string s))
 8:      )
 9: (dolist (element words result)
10: (if (member element adjectives) (setq result (concat (capitalize element) ", " result)) (setq result (concat result " " element))  )
11: )
12: (message result)))

that was instructive

Instructive, that was

Next: Date and Time

Find and Replace in a Region: Strip Smart Quotes in a Region

These are smart quotes: “ ” ‘ ’

The easiest way to get Emacs to automatically insert smart-quotes is to use smart-quotes mode.

I prefer not to use smart-quotes mode, however. I find it easier when editing to stick to plain quotes (” and ‘) and then to let org-mode export convert to smart quotes.

What makes things awkward is finding text with smart-quotes already included. I wrote the following function to strip those smart-quotes out. It narrows to a region, uses save-restriction to remember how things were before the narrowing and then uses two regex searches to find first double quotes and then single quotes, replacing both with plain quotes.

 1: (defun strip-smart-quotes (rStart rEnd)
 2:   "Replace smart quotes with plain quotes in text"
 3:   (interactive "r")
 4:   (save-restriction
 5:   (narrow-to-region rStart rEnd)
 6:   (goto-char (point-min))
 7:   (while (re-search-forward "[“”]" nil t) (replace-match "\"" nil t))
 8:   (goto-char (point-min))
 9:   (while (re-search-forward "[‘’]" nil t) (replace-match "'" nil t))
10: ))
Before: “You put your smart-quotes in, you take your smart-quotes out… ”
After: "You put your smart-quotes in, you take your smart-quotes out… "

Dired Tricks #2

Here are some random Dired mode tips:

1 Want to include the names of files in a document?

w       copies names of marked files to kill ring.
C-0 w   copies absolute file name
C-u     copies names relative to Dired’s current directory

Here’s an example of this in action:

Bob Hall is a leading British boogie-woogie pianist. Here are the tracks off his album What Goes Round

  1. I Can’t Get My Ass in Gear.mp3
  2. Road of No Return.mp3
  3. Running with the Blues.mp3
  4. Bloodhound Blues.mp3
  5. What Goes Round Comes Back.mp3
  6. The All Star Medicine Show.mp3
  7. Backwater Blues.mp3
  8. Alone with the Blues.mp3
  9. One More Road.mp3
  10. Back on the Valley.mp3
  11. Same Old Place.mp3

2 Fed up with deleting Dired buffers as you navigate through structures?

Pressing a rather than enter will close the current dired buffer as Emacs opens the next one.

3 Hiding Uninteresting Files

Here’s a partial view of a directory:

-rw-rw-r--  1 ***** *****  110537 Mar 24 13:07 planner.org
-rw-rw-r--  1 ***** *****   60688 Sep  3  2013 planner.org.~1~
-rw-rw-r--  1 ***** *****   60688 Sep  3  2013 planner.org.~2~
-rw-rw-r--  1 ***** *****  112046 Mar 18 16:37 planner.org.~860~
-rw-rw-r--  1 ***** *****  112079 Mar 18 16:40 planner.org.~861~
-rw-rw-r--  1 ***** *****  112133 Mar 18 16:55 planner.org.~862~
-rw-rw-r--  1 ***** *****  112133 Mar 18 16:55 planner.org.~863~
-rw-rw-r--  1 ***** *****  112196 Mar 20 15:16 planner.org.~864~

As I use force backups on all my files, all those ~backups clutter things up. I used to do the following remove them:

% m ~   Mark all backup files
k       Remove them from view

Then I discovered dired-omit-mode, part of dired-x.

Place the following in your .emacs file

(require 'dired-x)
(setq dired-omit-mode t)

Now hit M-o to toggle uninteresting files like backup files on and off.

4 And finally…

Something that I always forget when I need it: to create a new file with non existent parent directories from current directory:

M-x make-directory RET RET

Related Posts

Dired Tricks #1

Mouse and Emacs

Okay, if you’re using Emacs properly you won’t be using the mouse. You know that you waste time moving your hand from the keyboard to the mouse and back again.

But there will be times when you have the mouse in your hand anyway, so whilst it’s there you might want to remember these handy shortcuts…

Buffers

Ctrl and mouse 1 brings up the buffer list. Slide that mouse down context menu to quickly change buffer

Selecting Text

The following are worth remembering:
  • Double clicking on a parenthesis selects up to the matching parenthesis
  • Double clicking on a word selects it
  • Triple clicking selects a line

Mouse-1, Mouse-2, Mouse-3

I’m right handed. On my computer, Mouse-1 is left click, Mouse-2 is the scroll wheel and Mouse-3 is right click
Mouse-1 sets the point
Dragging the mouse not only sets the region, it also copies it to the Primary Selection, ready to be inserted by Mouse-2
Mouse-3 extends the current selection up to the point clicked. Mouse-3 a second time deletes the selection. This doesn’t work in all modes, however.

Searching

See the aardvark, a few lines down? It’s worth remembering that it’s often faster get to it by using C-s to search than by moving the cursor. Emacs expects you to search frequently, that’s why searching takes less key presses than C-x s, the save command.

Here’s a reminder of the search commands:

C-s C-w         Search for word after point
C-s C-s         Repeat last search
C-s C-y         Search line
C-s M-y         Search last kill
C-u C-s         Regexp Search
C-u C-r         Regexp Reverse Search

Emacs incremental search can occasionally be a pain. Don’t forget you can search non-incrementally for a specific word such as elephant using

M-s w <RET> elephant <RET>

Here’s the aardvark, by the way.

Date and Time

1 Reading Date and Time

This is how elisp stores a time:

(current-time) => (21209 38073 267139)

The first two numbers are the high and low bits of an integer number giving seconds since the epoch (0:00 January 1, 1970 UTC). The last number is microseconds and may be ommitted. There may be a fourth number representing picoseconds.
decode-time puts this into a more user friendly format:

(decode-time (current-time)) => (30 38 20 17 1 2014 5 nil 0)

The individual values are (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE) DOW is DOW of week DST is t if Daylight saving time is in effect ZONE is an integer indicating the number of seconds east of Greenwich.
format-time-string gives a more everyday format:

(format-time-string "%d/%m/%Y %H:%M:%S" (current-time)) => "17/01/2014 20:38:43"

Or, if you’re really in a hurry:

(current-time-string) => "Fri Jan 17 20:38:54 2014"

2 Setting a Date or Time

Set a time using date-to-time

(date-to-time "May 20 2011 19:30:00") => (19926 45864)

Note that the date strings format is dependent on your machine’s locale settings. For example, the following may be necessary. For more about locales, read this post.

(date-to-time "20 May 2011 19:30:00")

Enter a date using parse-time-string

(setq concert (parse-time-string "May 20 2011 19:30:00")) => (0 30 19 20 5 2011 nil nil nil)

Unlike date-to-time, parse-time-string allows you to omit the time value :

(setq birthday (parse-time-string "July 29 1953")) => (nil nil nil 29 7 1953 nil nil nil)

Here are some times:

(setq five-seconds (seconds-to-time 5))
(setq ninety-minutes (seconds-to-time (* 60 90)))
(setq one-day (seconds-to-time (* 60 60 24)))

The last can be more easily entered as:

(setq one-day (days-to-time 1))

Which leads to

(setq one-week (days-to-time 7))

and so on…

3 Converting Time Values

Use encode-time and decode-time to switch between formats

(encode-time 0 30 19 20 5 2011) => (19926 45864)
(decode-time '(19926  45864)) => (0 30 19 20 5 2011 5 t 3600)

4 Calculations on Dates and Times

Use time-add to add two times together.
Here’s the time a concert starts

(setq concert (date-to-time "May 20 2011 19:30:00"))

Suppose the concert lasts two hours (or 2 x 60 x 60 seconds). You can work out the time the concert ends as follows

(time-add concert (seconds-to-time (* 2 60 60)))

Let’s just check that worked

(format-time-string "%d/%m/%Y %H:%M:%S" (time-add concert (seconds-to-time (* 2 60 60)))) => "20/05/2011 21:30:00"

Suppose you know the start and end times of the concert. Use time-subtract to work out the duration:

(setq concert-start (date-to-time "May 20 2011 19:30:00"))
(setq concert-end (date-to-time "May 20 2011 22:25:00"))
(format-time-string "%H:%M:%S"(time-subtract concert-end concert-start)) => "02:55:00"

See Also

My Emacs Writing Setup

Due to the interest in my post on Writing Tools, I’ve published an HTML document on my Emacs writing setup.

If you want to know how I plan and plot stories, you may find the document interesting.  You’ll probably find it more interesting if you use Emacs yourself.

A Note on Emacs

I think of Emacs as a text editors’ tool. As I spend most of my life working with text, either programming or writing, I want to do it as efficiently as possible.
It first struck me when I was editing my novel Divergence just how inefficient I was being in pressing the arrow key and waiting for the cursor to get to where I wanted. That got me thinking about the time spent deleting text, transposing words, moving around paragraphs… I realised there must be a quicker way.
And then I remembered Emacs.

It makes sense for someone who spends most of their time manipulating text to learn a group of obscure key combinations. It saves time and increases productivity. Learning to use Emacs properly reminds me of playing Jazz on the piano. I’ve learnt all those chords and runs and fills so that I can use them without thinking when I’m improvising. Likewise, I’ve practised using Emacs key strokes such as M-f, M–M-c and C-M-<Space> so often I use them without thinking when editing. I rely on M-/ to complete words, and I can’t do without M-h and C-e to select and move around text.

I practice using Emacs because it makes me a more productive writer. If you’re interested, I’ve written up some of those tips and exercises on my Emacs Workout.

Calc Mode 1: Binary Numbers

Thanks to Andrew Hyatt for inspiring this entry

Here’s how to use Emacs to convert 8 numbers to binary. Why? Read on…

  1. Write the numbers: 127, 54, 32, 178, 199, 244, 3, 255
  2. Mark the region of the numbers and hit C-x * g. This grabs the numbers into calc mode as a vector
  3. In calc mode, hit d 2 to display the numbers in binary
  4. Still in calc mode, hit d z to show the leading zeroes. This shows them as 32 bit words
  5. Hit b w 8 to set the word size to 8 bits.
  6. Finally, and still in calc mode, hit y to yank the numbers back into the last buffer you were using.
  7. Add a table, tidy things up, and you’ve got a worksheet like the one below for a set of students and the answers for yourself.

Convert the 8 bit unsigned numbers to denary

  1. 01111111
  2. 00110110
  3. 00100000
  4. 10110010
  5. 11000111
  6. 11110100
  7. 00000011
  8. 11111111

Emacs Characters

Who would have thought that three dots could cause so many problems?

Most of the Aethernet Magazine writers use the ellipsis …

The Guardian Style Guide suggests leaving a space before and after the ellipsis.

In the Aethernet style guide the ellipsis is always followed by a space

“Is it… ?”

“Yes… ”

Preparing texts proves to be an interesting Emacs exercise.

It’s easy to search for three dots … , but there also exists a unicode character …
Now, as everyone knows, Emacs characters are saved as integers. You can insert any character on Emacs by hitting C-q and then the appropriate code in octal, in this case:

C-q 20046       gives …

If you want to enter the codes in denary, evaluate the following: (setq read-quoted-char-radix 10)

Evaluate the above and now…

C-q 8230 gives  …

Better yet, place the code in your .emacs file. Set the value to 16 if you want to quote in hexadecimal.

It’s easy to find a character’s value:

C-x = gives information about a character under the point.

For example, the ellipsis gives

Char: … (8230, #o20046, #x2026, file ...)

There are easier ways to insert non-keyboard characters using C-x 8

C-x 8 ' e prints é
C-x 8 `e prints è
C-x 8 ^ e prints ê
C-x 8 " u prints ü
C-x 8 / / prints ÷
C-x 8 C prints © copyright

The above are just a few examples

C-x 8 C-h to see all characters

If you want to hurry (dépêcher in French) you might get tired of typing C-x 8 all the time. The following allows you to omit the C-x 8 section

M-x set-input-method latin-9-prefix

Okay, what now… ?

Repeating Commands

Repeating Commands

C-x z   Repeats the last command.  Hitting z repeatedly keeps on repeating that command.

Once you know this trick, many other apparently complicated Emacs commands suddenly become clear. For example, why is the command to widen a window the extremely time consuming C-x }? That takes four keypresses on my keyboard, as I have to hold down shift to access the }. Surely it’s faster to use a mouse?
Not if you remember C-x z. Try it now:

C-x 3   Split into two vertical windows
C-x }   Widen the window one space
C-x z   Repeat the last command.  Now hit z until the window is wide enough.

Granted, this is still pretty complicated at first sight. If you’ve stumbled across this page whilst looking for something else you’re probably wondering why on Earth anyone would want to use Emacs, but that’s to miss the point. C-x z is another useful command that you can chain together with others to produce new results.

Whilst we’re here, here’s some useful window commands to remember

C-x -   Shrink the window to the size of the buffer text, if it's smaller
C-x +   Make windows the same size
C-x 4 0 Kill buffer and window
C-M-v   Scroll other window down
S-C-M-v Scroll other window up