## Really Simple Scrivener Mode

Here’s a screenshot of a really simple Scrivener type view for org mode files. I set this up following my simple sidebar set up.

I’ve copied the code below (I’ve also joined the 21st Century and started uploading code to GitHub)

The code is actually very simple. To make notes appear in a side window, simply put the letters TR (for top right), BR (for bottom right) or HD (for heading) at the start of a title and then call org-tree-to-indirect-buffer on those headings. I’ve added a key binding to M-s i to make this easy. I like to have certain notes always visible while I’m typing, this system allows me to vary just which notes they are.

And that’s it. Very simple, but I’ve found this very useful when writing.

(defun my-sidebars()
(setq fit-window-to-buffer-horizontally t)
(setq window-resize-pixelwise t)

(setq display-buffer-alist
(("\\*Occur\\*" display-buffer-in-side-window
(side . left) (slot . 0)
(window-width . fit-window-to-buffer)
(preserve-size . (t . nil))
(window-parameters . ((no-delete-other-windows . t))))
(".*\\.org-HD." display-buffer-in-side-window
(side . top) (slot . 0)
(preserve-size . (t . nil))
(window-parameters . ((no-delete-other-windows . t))))
(".*\\.org-TR." display-buffer-in-side-window
(side . right) (slot . -1)
(preserve-size . (t . nil))
(window-parameters . ((no-delete-other-windows . t))))
(".*\\.org-BR." display-buffer-in-side-window
(side . right) (slot . 1)
(preserve-size . (t . nil))
(window-parameters . ((no-delete-other-windows . t)))))))

(defun my-indirect-buffer ()
(interactive)
(let ((current-prefix-arg 4))                       ;; emulate C-u
(call-interactively 'org-tree-to-indirect-buffer)))

(defun scriv()
(interactive)
(when (require 'wc-mode nil t)
(wc-mode))
(toggle-frame-maximized)
(my-sidebars)
(global-set-key (kbd "M-s i") 'my-indirect-buffer))


## Sidebar for Emacs Org Mode

It would be nice to have a sidebar when using org mode. The sidebar would display the headlines of an org file. When a headline is selected, the subheadings and text would be displayed in another buffer.

You can currently do this by using C-c C-x b which is bound to (org-tree-to-indirect-buffer). The command opens a subtree in an indirect buffer which is sort of what I’m looking for, but you have to enter the command each time you land on a new headline.

You can make the process automatic by adding a hook as follows:

(add-hook 'post-command-hook #'org-tree-to-indirect-buffer nil :local)

The solution works, but it’s not quite there.

Searching the internet I found a useful suggestion from the delightfully named My Other Soup’s a Borscht:

M-x occur then search for the regexp "*+ " (note the space at the end)

This gives more of the functionality I want and has the advantage of being customizable. One problem: I wanted the sidebar to appear on the left hand side.

So I looked a little further and discovered side windows

My first thought was so what? I can already do that by splitting windows. The advantage of side windows is that you can set them to stay in position and to fix the buffer they display. No more losing your layout when you hit C-x 1.

If the above seems a little confusing (and it did to me at first) there’s an example of what you can do here in the Emacs Manual

So I combined the two things I’d learned and came up with the following function:

(defun my-sidebar-occur()
(interactive)
(setq fit-window-to-buffer-horizontally t)
(setq window-resize-pixelwise t)

(setq
display-buffer-alist
(("\\*Occur\\*" display-buffer-in-side-window
(side . left) (slot . 0) (window-width . fit-window-to-buffer)
(preserve-size . (t . nil))
(window-parameters . ((no-delete-other-windows . t)))))))

Here’s a video of the process in action.

One last thing. org-sidebar appears to solve my problem, but at the time of writing it’s still a little buggy. It’s nicely done though and could well become the standard in the future. Until then, I’ll use my workaround.

## Chessboards

Here’s a chessboard. Each square is 4×4 characters

    XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX


What’s the most Emacsy way of producing the above?

## First Line

XXXX    XXXX    XXXX    XXXX

You could do the following:

C-4 <space> 4 Spaces
C-4 X       4 Xs
C-k         Kill line
C-y         Yank
C-x z z z   Repeat last command three times


Another way is to use a macro:

F3          Start recording
C-4 <space>
C-4 X
F4          Stop recording
F4 F4 F4    Run the macro three times


Once you have one line, you could copy it and then yank it three times to get the first line of squares.

Here’s another way to get a line of squares, this time using rectangles. See this post to remind yourself about rectangles.

C-16 X
Kill and yank to get the following:

XXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXX


Now insert the white squares:

Go to start of the pattern

Set the region to cover the first square
C-x r o to insert blank space to fill the space of the region-rectangle

XXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXX

Now move the point forward 8 so its at the correct position to open the next square

C-8 C-f

You can record a macro of the above and then run it 3 times. Don’t forget to add the C-8 C-f at the end to move the point to the correct starting position.

## 2 The Second Line

Once you have the first line of squares, the second is quite easy. Copy one line of squares beneath itself to get the following:

    XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX

And then use C-x r k to kill the white square at the start of the second line.

    XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX
XXXX    XXXX    XXXX    XXXX


Now you can just kill and yank four times to get the complete chessboard.

Of course, you could just do it in LISP:

(defun one-line(pattern)
"Insert PATTERN 4 times"
(dotimes (count 4)
(insert pattern)))

(defun four-lines(pattern)
"Insert 4 lines of PATTERN"
(dotimes (count 4)
(one-line pattern)
(insert "\n")))

(defun chess-board()
(interactive)
(dotimes (count 4)
(four-lines "    XXXX")
(four-lines "XXXX    ")))

M-x chess-board

Can you think of a more efficient method than the ones above? Why not post it below?

## Emacs Characters 3

I never thought I would write three posts about entering characters in Emacs.

Emacs Characters demonstrates the quickest way to insert characters such as è and ä by using the C-x 8 key combination. So, for example:

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

Emacs Characters 2 shows how C-x 8 [return] allows you to type in the description of a character, so C-x 8 [return] LEFT ARROW gives ←

It’s time for another way. This post demonstrates toggle-input-method. Emacs has a number of input methods, used for entering such things as Arabic characters. You can see the full list using

 M-x list-input-methods 

Use C-\ to enable the input method. The first time you do this you’ll be prompted for a method. For the purposes of this post, enter TeX. If you don’t know TeX, this post gives you a flavour.

You can now enter characters using TeX. Here are some examples

\pir^2 → πr²
Z\"urich → Zürich
Caf\'e  → café

I used \rightarrow to get the → used above, by the way.

When you’re done using TeX, use C-\ to disable the current input method

That’s three different methods for entering text. Which one is best? For me, it’s whichever is the most convenient. If I want to type the acute accent in café I’d probably use C-x 8 ‘e. When I was writing my novel Dream Paris I used TeX input for typing in the French dialogue.

As this is the Emacs workout, why not think of the ways you could type the following in Emacs?

Einstein wrote E=mc² on the table whilst eating a rösti in a café in Zürich. As easy as πr², he thought.

If you get stuck

M-x describe-input-method 

will give a list of key sequences.

## Common Lisp Loops

I can’t think why you wouldn’t use the Common Lisp loop macro in Emacs. Don’t forget to (require ‘cl-lib)

### Simple Loops

;; keywords: to, upto, below, downto, above, by
;; keywords: collect, append, nconc, count, sum, maximize, minimize

(cl-loop
do (princ 1))
=> 111111... infinite loop

(cl-loop repeat 5
do (princ 1)
(princ 2))
=> 1212121212

(cl-loop for i from 1 below 10
maximize i)
=> 9

(cl-loop for x from 9 downto 1
collect x)
=> (9 8 7 6 5 4 3 2 1)

(cl-loop for i from 10 above 1 by 2
collect i)
=> (10 8 6 4 2)

### Looping over Sets and Arrays

;; keywords: in, on, across, by
;; Remember in for lists
;; across for vectors

(cl-loop for l in '(1 2 3 4 5)
do (princ l))
=> 12345

(cl-loop for l in '(1 2 3 4 5) by #'cddr
collect l)
=> (1 3 5)

(cl-loop for l on '(1 2 3 4 5)
collect l)
=> ((1 2 3 4 5) (2 3 4 5) (3 4 5) (4 5) (5))

(cl-loop for l on '(1 2 3 4 5) by #'cddr
collect l)
=> ((1 2 3 4 5) (3 4 5) (5))

;; Remember that a string is an array in lisp, so...
;; Add up the digits in 90125
(cl-loop for d across "90125"
sum (- d 48))
=> 17

### Destructuring

(cl-loop for (a nil) in '((1 2) (2 3) (3 4))
collect a)
=> (1 2 3)

(cl-loop for (a b) in '((1 2) (2 3) (3 4))
collect (* a b))
=> (2 6 12)

(cl-loop for (a b) on '(1 2 3 4 5) while b
collect (+ a b))
=> (3 5 7 9)

(cl-loop for (a b) on '(1 2 3 4 5) by #'cddr while b
collect (+ a b))
=> (3 7)

### Hashtables

(cl-loop for key being the hash-keys of myhashtable
using (hash-value value)
do (princ value))

### Parallel fors

(cl-loop for i from 1 to 5
for l in '(a b c d)
collect (list i l))
=> ((1 a) (2 b) (3 c) (4 d))

(cl-loop for i from 1 to 5
for j from 2 to 10 by 2
collect (* i j))
=> (2 8 18 32 50)

### Nested fors

(cl-loop for i from 1 to 5
collect (cl-loop for j from 1 to 5
collect (* i j)))
=> ((1 2 3 4 5) (2 4 6 8 10) (3 6 9 12 15) (4 8 12 16 20) (5 10 15 20 25))

(cl-loop for i from 1 to 5
append (cl-loop for j from 1 to 5
collect (* i j)))
=> (1 2 3 4 5 2 4 6 8 10 3 6 ...)

(cl-loop for i from 1 to 5
collect (cl-loop for j from 1 to 5
sum (* i j)))
=> (15 30 45 60 75)

(cl-loop for i from 1 to 5
sum (cl-loop for j from 1 to 5
sum (* i j)))
=> 225

### Selection

;; if, when, unless

(cl-loop for i from 1 to 20
unless (cl-evenp i) collect i)
=> (1 3 5 7 9 11 13 15 17 19)

(cl-loop for i from 1 to 20
when (= (% i 3) 0) collect i into fizz
when (= (% i 5) 0) collect i into buzz
finally return (list fizz buzz))
=> ((3 6 9 12 15 18) (5 10 15 20))

(cl-loop for i from 1 to 20
if (and (= (% i 3) 0) (= (% i 5) 0)) collect i into fizzbuzz
else if (= (% i 3) 0) collect i into fizz
else if (= (% i 5) 0) collect i into buzz
finally return (list fizz buzz fizzbuzz))
=> ((3 6 9 12 18) (5 10 20) (15))

(cl-loop for i from 1 to 10
if (cl-evenp i)
collect i into evens
and sum i into evensum
else
collect i into odds
and sum i into oddsum
finally return (list evens evensum odds oddsum))
=> ((2 4 6 8 10) 30 (1 3 5 7 9) 25)

Find c from comp where diff is never a member of squares
(cl-loop for c in comp
if  (cl-loop for p in pri
for diff = (/ (- c p) 2)
never (member diff squares))
collect c)

### Then Iteration

(cl-loop for i from 1 to 5
for square = (* i i)
collect square)

;; Though you'd be better with
(cl-loop for i from 1 to 5
collect (* i i))

;; However, this leads to Triangle Numbers
(cl-loop for n from 1 to 10
for triangle = 1 then (+ triangle n)
collect triangle)
=> (1 3 6 10 15 21 28 36 45 55)

(cl-loop for x = 0 then y
for y = 1 then (+ x y)
while (< y 30)
collect y)
=> (1 2 4 8 16)

;; Fibonacci Sequence (note the and)
(cl-loop for x = 0 then y
and y = 1 then (+ x y)
while (< y 30)
collect y)
=> (1 1 2 3 5 8 13 21)

### Termination

;; while, until, always, never, and thereis

while and until are straightforward

(cl-loop for n from 1
for tri = 1 then (+ tri n)
until (> (divs tri) 500)
finally return tri)

never, thereis and always are shorthand for a combination of when-return

(defun isprime(n)
(cond
((< n 2) nil)
((= n 2) t)
((cl-evenp n) nil)
(t
(cl-loop for i from 3 to (sqrt n) by 2
never (= (% n i) 0)))))

## Code is Poetry

Brian Bilston has written a History of Modern Art in Poetry.  I  wondered what it would be like to do something similar in various programming languages.

Here’s the original poem:

Roses are red
Violets are blue
Sugar is sweet
And so are you

Here’s the poem constructed using a zip statement in Haskell

Prelude> zip ["roses","violets","sugar","you"]["red","blue","sweet","sweet"]
[("roses","red"),("violets","blue"),("sugar","sweet"),("you","sweet")]

The list produced holds the relationship that sugar is sweet and you are sweet. The comparison between “you” and sugar is not made clear.

### Lisp

Here’s the poem stored as an alist in Lisp

(setq poem '(("roses" . "red") ("violets" . "blue") ("sugar" . "sweet")("you" . "sweet")))
(mapcar (lambda (x) (concat (car x) " are " (cdr x))) poem)

I’ve gone one stage further here, using a mapcar function to produce something that looks a little bit more like the original poem, however we’re still missing the connection between “you” and sugar.

("roses are red" "violets are blue" "sugar are sweet" "you are sweet")

### Python

Of course, sugar are sweet isn’t right.   Let’s try some Python.

poem = {"roses":"red","violets":"blue","sugar":"sweet","you":"sweet"}

for key, value in poem.items():
if key == "sugar":
print(key, "is" ,value)
else:
print(key, "are", value)


This output is at least grammatically correct.

roses are red
violets are blue
sugar is sweet
you are sweet


### Java

Java can do something similar using a HashMap

Map<String, String> poem = new HashMap<String, String>();

poem.put("roses", "red");
poem.put("violets", "blue");
poem.put("sugar", "sweet");
poem.put("you", "sweet");

for (Map.Entry<String, String> entry : poem.entrySet()) {
if(entry.getKey().equals("sugar")){
System.out.println(entry.getKey() + " is " + entry.getValue());
} else{
System.out.println(entry.getKey() + " are " + entry.getValue());
}

}


But we’re still no closer to conveying the connection between “you” being sweet, just like sugar is sweet.

Fortunately, Java allows us to use some object oriented design to better convey the meaning of the poem.

In the example below I’ve used an interface to allow sweetness to be applied to both sugar and to the special one to whom the poem refers.  The comparison is at last made clear.  As there can only be one true love, it seemed reasonable to make a singleton class for TheOne, inherited from a regular person.

Run the code and the poem is printed out properly, just like the original.  More importantly though, the concepts to which the poem refers are properly encapsulated and related.

The original poem was only 4 lines long.  My implementation takes 80 lines, but I think you’ll agree I’ve done a rather better job, providing clarity and removing any ambiguity.

public class Love {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Flower [] rose = new Flower[12]; // 12 roses in a bunch
Flower [] violet = new Flower[30]; // more violets in bunch
Sugar sugar = new Sugar();
TheOne myLove = TheOne.getInstance();  // Singleton class
// There can only be one true love

rose[0] = new Flower();
rose[0].setColour("red");  // colour is static so only need
// to instantiate one here

violet[0] = new Flower();
violet[0].setColour("blue");

System.out.println("Roses are " + rose[0].getColour());
System.out.println("Violets are " + violet[0].getColour());
System.out.println(sugar.sweet());
System.out.println(myLove.sweet());
}

}

class Flower {
private static String colour;

public void setColour(String colour){
this.colour = colour;
}

public String getColour (){
return colour;
}
}

class Sugar implements Sweetness {

@Override
public String sweet() {
return "Sugar is sweet";
}

}

class Person {
public String sweet()
{
return "Not sweet";
}
}

class TheOne extends Person implements Sweetness{
private static TheOne instance = null;

private TheOne()
{

}

public static TheOne getInstance()
{
if(instance == null)
instance = new TheOne();

return instance;
}

@Override
public String sweet() {
return "And so are you";
}
}

interface Sweetness {
String sweet();
}


## MyKitaab Podcast

The mission of the MyKitaab podcast series is to help answer the question “I have written a book, how do I get it published in India?”
Here, host Amar Vyas talks to me about writing, blogging and Open Source software, especially  Emacs!
You can access the podcast as follows:

Or listen to it here:

## Emacs Characters 2

I wrote about inserting characters in Emacs in this post.

There I pointed out that it’s easy to insert characters such as è and ä by using the C-x 8 key combination. So, for example:

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


What I didn’t realise at the time is there was an easier combination formed by simply entering the Unicode name of a character.

For example, to insert é, use the combination

C-x 8 [return] LATIN SMALL LETTER E ACUTE


Capital letters begin, unsurprisingly, with LATIN CAPITAL.

At first glance the above doesn’t look easier, even allowing for the fact that Emacs allows you to use a few shortcuts. With tab completion, I got the key sequence down to…

C-x 8 [return] lat [tab] sm [tab] e [space] a [tab]


… but that’s still not as compact as the original examples.

So why is that an easier combination?

Well, it’s easier in the sense that it’s easier to remember, and therefore it can be quicker to use for obscure characters than having to look up a character code.

Just as an experiment, I tried to put in a British pound sign without using the appropriate key on my UK keyboard.

I used C-x 8 [return] and typed po [tab], and there was pound sign (along with

POODLE, POULTRY LEG and POUTING CAT FACE).

If you’re interested what POUTING CAT FACE looks like (I certainly was) here’s a link: http://www.fileformat.info/info/unicode/char/1f63e/index.htm

## Emacs Writing Tips: What to do When You’ve Finished a Novel

Just because the novel is finished, it doesn’t mean the file it was written on is done with. Experience suggests the file is something that I will return to over the coming months. Here are a few reasons:

• Blurbs, summaries and press releases will need to be written
• This being the age of Social Media,  Blog and Guest Blog entries will need to be written
• I may wish to refer to events when writing a sequel
• There may be another novel or short story to be written in the same setting
• There will be unused ideas that can be used elsewhere.

The following process is intended to tidy up the file, removing the chaff and sorting the useful stuff into some sort of order. It’s well worth the time.
First, use org-sparse-tree to check for unfinished TODOs.  In my setup, this brings up TODOs and IDEAs

C-c / t


Here’s a short example from Dream Paris, my latest novel

** TODO P.232 More explanation of (2)You and You(2)?
** TODO Get Mr Monagan mentioned earlier
** TODO Do something about the Tu Vous numbers
** TODO Why is Anna the Hero of Dream Paris?
** TODO Where did Kaolin's intelligence come from?
** TODO Kaolin speaks a leetle like this.  Good 'ealth!

Go through and mark those TODOs which have been done as DONE
Find the PAUSED ideas in a similar way and change them to TODOs (they might be useful in other stories)

C-c / T PAUSED


Now begin the process of sorting. Add three headings at the beginning of the file.

* A General Ideas
* B Blog
* C Sequel


Mark up the remaining TODOs using Shift up and down to give them a priority of A (for General Ideas), B (for Blog) and C (for Sequel) (I don’t use org-mode priorities, so this is just a quick way of marking up)

Now that the notes are categorised, copy them to the appropriate heading, ready for refiling. There are a number of ways this can be done. Here are a couple to get you going.

Use org-sparse-tree to identify the individual entries and then org-refile to the appropriate heading:

C-c / / #A     Find all the #A General ideas
C-c C-w            Refile to appropriate heading


or
Make a copy of the buffer and then use keep-lines to flush all lines that do not contain the regexp #A. Copy the remaining lines to the appropriate heading.

Repeat for #B and #C

At the end of all that, I’m left with a list of notes ready to be transferred to other files. Here’s an edited sample.

 * A General Ideas
** TODO [#A] Vive L'indifference!
** TODO [#A] Wallace Fountains
** IDEA [#A] Diagonal Anneka
** IDEA [#A] Geppetto (8 or 35)
* B Blog
** TODO [#B] This is an adult story.  In real life, kids shouldn't be expected to save their parents.
** TODO [#B] Anna and Francis Orangina
** IDEA [#B] The wine scene
* C Sequel
** TODO [#C] Soldiers with guns saying (12)Mine
** TODO [#C] Dream Paris Courtesans
** TODO [#C] Walking around Dream Paris
** TODO [#C] German Brass Band Instruments


Now it’s time to start the next novel…

## C-x r

I wrote in this post on Evil Emacs about some of the things that vi does well. One feature I particularly like is the ability to store a mark in a register q using the key combination mq. You can then jump back to that point using q

Compare that with the equivalent Emacs key combinations: C-x r <space> q to store a point in a register, and C-x r j q to jump back.

There are lots of useful, and by me at least, underused Emacs features that begin with C-x r

A handy trick to see them is all to enter

C-x r C-h
which opens a buffer listing all the commands beginning C-x r

Here are the four we’re interested in for the moment

C-x r space q         Store point in register q
C-x r s q               Store region in register q
C-x r i q              Insert text from register q


Could that key sequence be shortened? Well, here’s one way…

C-x r calls the ctl-x-r-map prefix keymap

Adding the following to your .emacs will save you a keystroke: now C-</strong> is the same as hitting <strong>C-x r</strong>. <pre class="example">(global-set-key (kbd "C-“) ctl-x-r-map)

Now the key combinations for storing points and regions are as follows

C- space q        Store point in register q
C- s q              Store region in register q
`