Calc Mode 0: Basics

Having seen it written on a blackboard in the Simpsons, I wanted to check if

398712 + 436512 = 447212

thus disproving Fermat’s Last Theorem. My pocket calculator confirmed the expression to be true, but those are big numbers, and the calculator lacks precision.

This seemed like a perfect opportunity to use calc mode.

M-x calc        to enter calc mode

First enter the left hand side

3987
<Enter>
12 ^
4365
<Enter>
12 ^

Both numbers are now there in the stack:

--- Emacs Calculator Mode ---
2:  16134474609751291283496491970515151715346481
1:  47842181739947321332739738982639336181640625

Hit + to add them together. Now to enter the right hand side.

4472
<Enter>
12 ^

Now the left and right sides of the original expression are there in the stack, and you can see that whilst they may be sufficiently equal to fool a pocket calculator, they can’t fool Emacs.

--- Emacs Calculator Mode ---
2:  63976656349698612616236230953154487896987106
1:  63976656348486725806862358322168575784124416

Hit  to see the difference:

1211886809373872630985912112862690

d g to group the number, then hit y to yank the number back into the current buffer.

1,211,886,809,373,872,630,985,912,112,862,690

… as I just did there.

See Also

Calc Mode 1: Binary Numbers

Regexp Exercises

You might want read the post on Regexp Builder before attempting these…

Here’s an example of a British Postcode: OL1 3SQ. It has the format 2 letters and a digit, space, 1 digit and two letters. The following emacs regex finds this type of postcode:

“[A-Z]\{2\}[0-9] [0-9][A-Z]\{2\}”

  1. Write a regex to find postcodes of the type W1 1AA
  2. Write a regex to find postcodes of the type RM12 4JJ
  3. Write one regex that finds all three types of postcode: OL1 3SQ, W1 1AA and RM12 4JJ
  4. Write a regex that finds simple email addresses of the form [email protected]
  5. Now extend the regex to find email addresses of the form [email protected]
  6. Now write a general email regex that will find all properly formed email addresses
  7. Google the form of an ISBN (There are two standards). Write a regex to find ISBNs
  8. Write a regex that can find unnecessary white space in a line of text

This      line     has              unnecessary      white space    .
|              So does this line   |
This line does not.

Finally…

“He said ‘Have you got the time?’” “Why didn’t he look at his watch?”
Write a regex that can find the left single quotes: ‘and right double quotes: ” in the above conversation.

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.