# Move cursor to top/middle/bottom of window

As mentioned previously you can use C-l to recentre the window on the line containing the cursor (point in emacs terminology). A related command is move-to-window-line-top-bottom which is bound to the short-cut M-r. Use this repeatedly to cycle the position of the cursor (point in emacs terminology) between the top, middle and bottom of the window.

In other words, C-l recentres the window while keeping the point on the same line, while M-r moves the point without recentring the window.

# Use scroll margins to give context to your cursor

I add the following line to my emacs config file so the when I move the cursor near to the top or bottom of the window, the window will scroll when I am 3 lines away from edge. The effect is that (however it is moved) the cursor is always given 3 lines of context before the top or bottom of the window, which I find very useful.

(setq scroll-margin 3)


# Smart text templates with yasnippet

We looked before at expanding text with abbreviations which is great for simple things, but you can do a whole lot more using yasnippet. This is a smart template system for emacs, which is best explained with a simple example.

In the animation below I first of all use a snippet to write a fraction in latex by typing frac and hitting TAB which expands to \frac{numerator}{denominator} and places the cursor in the numerator field. I then type 1 and TAB to get to the next field and type 2 and TAB again to exit the snippet.

In the second part of the animation I typed begin and hit TAB to expand the snippet, creating a latex environment. In this example, note how the environment field is mirrored in the begin and end lines so I only type itemize once.

If you use my recommended setup, prelude then you already have yasnippet installed as well as a bunch of useful snippets, so you can get started right away. Otherwise you can install yasnippet from one of the package repositories. In either case you can add

(require 'yasnippet)
(yas-global-mode 1)


to your emacs config file to turn on yasnippet globally so it works in all buffers.

If you install from one of the repositories, you won’t get many snippets, but you can download sets of them from the official git repository and write your own (see below). Snippets are defined in simple text files that you put (by default) in ~/.emacs.d/snippets/ in subdirectories named after the major mode for those snippets. So e.g. ~/.emacs.d/snippets/latex-mode/ contains my snippets that will be active in latex mode.

Writing a snippet is really simple. The fraction snippet I used above looks like this:

# -*- mode: snippet -*-
# name: frac
# key: frac
# --
\frac{${1:numerator}}{${2:denominator}}$0  The name can be whatever you like, but the key is the thing you type and TAB to expand out the snippet. You can see that the ${1:numerator} represents the first field the cursor moves to, with the placeholder text, and similarly for the second field. $0 indicates where the cursor goes when the final TAB exits the snippet. The snippet for the latex environment in the second example is similarly simple: # -*- mode: snippet -*- # name: begin # key: begin # -- \begin{${1:environment}}
$0 \end{$1}


The repeated $1 mirrors the environment field. After you have written a snippet, it should also be saved with the key as the file name in the appropriate subdirectory for the major mode you want. You’ll then need to use the commands yas-recompile-all and yas-reload-all to load the new snippets. These are simple examples and yasnippet can do a lot more, such as include lisp code that is activated when the snippet expands. I’ll show an example of using this to generate email templates in a future post. There are some other sophisticated examples in this video from emacs rocks. # Delete (non) matching lines Recently I needed to clean up a pile of text I had pasted into emacs from a pdf. One of the things I wanted was to remove all lines that didn’t start with a comma. Emacs of course provides functions for this, so I highlighted the text and used M-x delete-non-matching-lines ^, The ^, is a regular expression that matches lines starting with a comma. Emacs also offers the command delete-matching-lines which does what you would expect. # Org-mode basics VI: A simple TODO list In the first part of my series on org-mode, I described how to create a rich structured notebook that can be exported to various useful formats. In the next few posts in this series I’m going to talk about another essential way I use org-mode, which is to organise myself! I use org-mode to manage my (depressingly long) task list including scheduled tasks and deadlines, to export a calendar feed for events, and to quickly capture useful information including emails and scanned documents. If you want to see a very advanced use case, look at Bernt Hansen’s Org Mode – Organize Your Life In Plain Text. In this post, we’ll start by looking at setting up a simple todo list, and we’ll cover some of the more advanced topics later. To start with, add the following code to your emacs config file: ;; set key for agenda (global-set-key (kbd "C-c a") 'org-agenda) ;;file to save todo items (setq org-agenda-files (quote ("/Users/bjm/todo.org"))) ;;set priority range from A to C with default A (setq org-highest-priority ?A) (setq org-lowest-priority ?C) (setq org-default-priority ?A) ;;set colours for priorities (setq org-priority-faces '((?A . (:foreground "#F0DFAF" :weight bold)) (?B . (:foreground "LightSteelBlue")) (?C . (:foreground "OliveDrab")))) ;;open agenda in current window (setq org-agenda-window-setup (quote current-window)) ;;capture todo items using C-c c t (define-key global-map (kbd "C-c c") 'org-capture) (setq org-capture-templates '(("t" "todo" entry (file+headline "/Users/bjm/todo.org" "Tasks") "* TODO [#A] %?")))  This sets up the file in which we will save our todo items (put your own choice of file here), configures a few other options, and sets up a capture template to quickly add todo items to the list (put the same file name for your todo file here too). Now you can highlight the code in your config file and use M-x eval-region or restart emacs to pick up the changes. Once you have done this you can add your first todo item using C-c c t, which will pop up a small window with a prompt like this ** TODO [#A]  You can see this looks like an org-mode headline, and you should add your todo item and any notes to go with is to this like so: ** TODO [#A] make a todo list Some notes here about how to do it  Then hit C-c C-c to save this item. The nice thing about this method of adding items (called org-capture) is that you can add an item from anywhere in emacs and get right back to what you were doing afterwards. By default our item was given priority A, but you can change this easily by hitting shift and up or down arrow to cycle through the priority levels (I find that three levels, A-C is enough for me). Let’s add a priority B item: ** TODO [#B] add another item to my list  Now we can have a look at our todo list using C-c a to launch the “agenda dispatcher”, a powerful interface for selecting different ways to view your tasks. For now we’ll just hit t in the dispatcher to view the todo items (i.e. use C-c a t). This switches to a buffer with our todo list – in this list view, you might want to: • Cross an item off your list (the best bit!). To do this put the cursor on the corresponding line and hit $ which marks it as done and archives the item in a file called todo.org_archive getting rid of it from your todo list.
• Change the priority of an item using shift up/down.
• View the notes to go with items by hitting E.
• Edit or view an item in more detail by hitting RET with the cursor on the item that you want. This takes you to the item in your todo.org file where you can edit it or look at the notes you added to it in more detail.
• Quit back to where you were before with q

That is all there is to it, and you now have a simple but powerful todo list in emacs. Just remember C-c c t to create a todo item and C-c a t to view the todo list.

That’s all for now. In the next part we’ll look at scheduling and deadlines.

# Join line to following line

I wrote a while ago about using M-^ to join the current line to the previous line. In fact, when editing I find that I most often want to join a line to the following line. I used to do this by using C-e to move to the end of the line and then C-d to delete until I got the next line joined to the current one. It is easier to do this with a single key using a simple function, which I set to C-j. Add the following to your emacs config file:

;; join line to next line
(global-set-key (kbd "C-j")
(lambda ()
(interactive)
(join-line -1)))


You can keep hitting C-j to keep joining the next line.

## Update

I originally used M-j as the keybinding for this, but Kaushal Modi pointed out in the comments that C-j is a better choice.

# Change text size

To change the size of the text in the current buffer, use C-x C-- (i.e. control x then control minus) to decrease the size, and C-x C-+ or C-x C-= to increase the size. To reset to the default, use C-x C-0. These run the command text-scale-adjust which can take further input, so using C-x C-+ and then hitting + again will increase the size a second time, or hitting 0 will reset to default.

You can, of course, change the default text size and font. I add the following to my emacs config file:

;;use larger font
(setq default-frame-alist '((font . "Source Code Pro-14")))


# Editing and managing files remotely

Emacs supports editing files remotely, as a nice alternative to opening a new emacs session on your remote machine and sending the window over X11. This feature is called tramp.

It works seamlessly – just open a file as usual with C-x C-f and then give the name of the remote file, including the host address – e.g.

C-x C-f /host.server.com:/home/bjm/myfile.org


Note the syntax, that the remote machine name is opened at the top level directory “/”.

You can then edit and save as normal.

It is useful to note that you can also do exactly the same thing to open remote directories in dired to browse, copy, rename and otherwise manage files on a remote machine.

## Update

As commenter Nagora points out, if your username is different on the remote machine, you should specify it like

C-x C-f /user@host.server.com:/home/bjm/myfile.org


# Don’t search, swipe

We looked before at basic searches using isearch. However, for some time now I have been using a very nice alternative called swiper. The project page has some good information and a link to a video, so I’ll just summarise what I like about it here.

Swiper acts like isearch, in that you type a string and you get an updating list of matches, but the matching lines are shown in a list in an expanded minibuffer, which you can move through with arrows or C-n and C-p.

One of the best things is that swiper supports regular expressions in a simple way. The main thing you need to know is that spaces are interpreted as a wildcard .* so the query "don swi" would match the title of this post, for example.

The best way to understand it is to try it out yourself. Install swiper and then run it with M-x swiper. I like it so much I have bound it to C-s to replace isearch altogether:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; swiper                                                                 ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(global-set-key (kbd "C-s") 'swiper)
(setq ivy-display-style 'fancy)


The second line in the above code sets the colours of the swiper results display to be a bit more, well, fancy! Apparently this option only works well for emacs versions 24.5 and higher, so get updated.

The other tweak I have made is to get swiper to recenter the display when it exits – I found it a little unpredictable where the point was going to be after I finished swiper. This is done with a little bit of advice:

;;advise swiper to recenter on exit
(defun bjm-swiper-recenter (&rest args)
"recenter display after swiper"
(recenter)
)


# Org-mode basics V: Exporting your notes

In this final post of my short series on using org-mode to write rich, structured notes, we will look at exporting the notes as a web page or pdf document. The previous posts covered structuring your notes and adding tables and links and images, and formatting text and source code.

If you have been following along, you should have an org file containing all of the notes on org-mode from the previous posts. We’ll now look at exporting that file.

One strength of org-mode is the ability to export to multiple formats. Probably the most useful to begin with are web pages and pdf (via latex) but more are available; to quote the org manual

ASCII export produces a readable and simple version of an Org file for printing and sharing notes. HTML export allows you to easily publish notes on the web, or to build full-fledged websites. LaTeX export lets you use Org mode and its structured editing functions to create arbitrarily complex LaTeX files for any kind of document. OpenDocument Text (ODT) export allows seamless collaboration across organizational boundaries. Markdown export lets you seamlessly collaborate with other developers. Finally, iCal export can extract entries with deadlines or appointments to produce a file in the iCalendar format.

To export your org file to a web page, type C-c C-e to start the exporter and then press h to select html and o to select open. A new web page should now open in your browser.

Similarly, typing l and o in the exporter will convert the org file to latex and then compile it to produce a pdf and display that. Try both of these.

It is possible to add many customisations to the export process. For example, go to the top of the buffer (using M-<) and use C-c C-e and then # to insert an export template. You can then choose to add html or latex (or other) templates (press TAB to see the list).

As an example, add the following to the top of your org file to tweak the appearance of the exported documents.

#+LaTeX_CLASS: bjmarticle
#+TITLE:     Org-mode Basics
#+AUTHOR: Ben Maughan
#+OPTIONS: html-preamble:t html-scripts:t html-style:t
#+OPTIONS: html5-fancy:nil tex:t
#+HTML_DOCTYPE: xhtml-strict
#+HTML_CONTAINER: div
#+DESCRIPTION:
#+KEYWORDS:
#+HTML_MATHJAX:
#+SUBTITLE:
#+INFOJS_OPT:
#+CREATOR: <a href="http://www.gnu.org/software/emacs/">Emacs</a> 24.4.1 (<a href="http://orgmode.org">Org</a> mode 8.3.2)


This is the default html export template with a couple of tweaks.

• I have added a link to a style sheet to style the html
• I have added a latex class bjmarticle to control the appearance of the generated pdf

The latex class is defined in my emacs config file with the following

(add-to-list 'org-latex-classes
'("bjmarticle"
"\\documentclass{article}
\\usepackage[utf8]{inputenc}
\\usepackage[T1]{fontenc}
\\usepackage{graphicx}
\\usepackage{longtable}
\\usepackage{hyperref}
\\usepackage{natbib}
\\usepackage{amssymb}
\\usepackage{amsmath}
\\usepackage{geometry}
\\geometry{a4paper,left=2.5cm,top=2cm,right=2.5cm,bottom=2cm,marginparsep=7pt, marginparwidth=.6in}"
("\\section{%s}" . "\\section*{%s}")
("\\subsection{%s}" . "\\subsection*{%s}")
("\\subsubsection{%s}" . "\\subsubsection*{%s}")
("\\paragraph{%s}" . "\\paragraph*{%s}")
("\\subparagraph{%s}" . "\\subparagraph*{%s}")))


You’ll need some experience of LaTeX to make significant changes here, but the sky is the limit.

I have compiled the series of posts on org-mode basics into a single org file, and exported it with this set of export options.

• The org file is here
• The exported web page is here
• The exported pdf is here

The wrapping of the example and code blocks in the pdf needs to be fixed, but overall we get some pretty nice looking documents with minimal effort.