Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Org is a major mode for GNU Emacs that turns plain text files into an outliner, a task manager, a spreadsheet, a computational notebook and a publishing system. All of these features work on the same kind of file: a text file with the extension .org, written in a small markup language.

This book teaches Org from the first file to the design of your own systems: a task workflow with an agenda, literate programs that generate code and configuration, and documents that export to HTML, LaTeX and other formats.

What Org looks like

An Org file is readable without any software beyond a text editor. Here is a small one:

#+TITLE: Home server

* TODO Replace the backup disk                              :hardware:
DEADLINE: <2026-12-01 Tue>
The current disk reports reallocated sectors.

* Disk usage
| Mount | Used (GB) | Size (GB) |
|-------+-----------+-----------|
| /     |        41 |       120 |
| /data |       812 |      2000 |

* Check free space
#+BEGIN_SRC sh
df -h /data
#+END_SRC

Even without knowing the syntax, you can read the structure: three headlines marked with stars, a task with a deadline and a tag, a table, and a shell command. In Emacs, the same file becomes interactive. The headlines fold and unfold, the task appears in a weekly agenda as its deadline approaches, the table aligns itself and can compute totals, and the shell command can be run with its output inserted below it.

Why plain text

Org’s choice of plain text has practical consequences that shape everything else in the book:

  • Your data stays yours. An Org file opens in any editor, on any system, and will still open in decades. There is no database and no proprietary format.
  • Version control works. Org files diff and merge well in Git, so you can track the history of your notes or tasks like code.
  • Structure is in the syntax. Because headlines, timestamps, tags and properties have a defined textual form, Org (and other programs) can parse a file reliably. The agenda, the exporter and column view are all queries over that parsed structure.
  • Complexity is optional. A file with only headlines and paragraphs is already a valid Org file. You add TODO keywords, tables or code blocks only when you need them.

The price is that Org is best used in Emacs. Other editors can display and edit Org files, but the commands that make Org productive (folding, the agenda, capture, export) are Emacs features.

Who this book is for

The book is written for software engineers who use Emacs at least a little: you should know how to open and save a file, run a command with M-x, and add a line to your init file. No knowledge of Emacs Lisp is required for Parts I to IV; Part V uses a little Lisp to extend Org.

How this book is organized

The book has 20 chapters in 5 parts. Part I is the foundation for everything else. After it, Parts II, III and IV are largely independent, so you can follow the one that matches your goal. Part V combines the earlier parts.

flowchart TD
    P1["Part I: Foundations"] -->|tables inside documents| P2["Part II: Tables"]
    P1 -->|headlines become tasks| P3["Part III: Planning and Tasks"]
    P1 -->|documents and code| P4["Part IV: Code and Publishing"]
    P2 -->|formulas, plots| P5["Part V: Mastery"]
    P3 -->|agenda and capture| P5
    P4 -->|Babel and export| P5

Figure 1.1: Part I is shared ground; Parts II to IV can be read in any order, and Part V draws on all of them.

Part I: Foundations

  1. Introduction: this chapter.
  2. Getting Started: installation, the first file, key conventions, the C-c C-c key, templates, speed keys, in-buffer settings and org-lint.
  3. Document Structure: headlines, folding, motion, structure editing, sparse trees, plain lists, drawers, blocks and display options.
  4. Markup for Rich Contents: emphasis, entities, LaTeX, literal examples, images, captions and footnotes.
  5. Hyperlinks: internal and external links, storing and inserting links, IDs, and custom link types.

Part II: Tables

  1. The Table Editor: creating and editing tables, column widths and Orgtbl mode.
  2. The Spreadsheet and Plotting: references, formulas, recalculation and plots.

Part III: Planning and Tasks

  1. TODO Items: TODO keywords, workflows, logging, priorities, checkboxes and habits.
  2. Tags, Properties and Column View: metadata on entries, searches, and tabular views of an outline.
  3. Dates and Times: timestamps, deadlines, scheduling and repeating tasks.
  4. Clocking, Effort and Timers: measuring time, clock reports, effort estimates and timers.
  5. Capture, Refile, Archive and Attachments: getting items in, moving them, and putting them away.
  6. Agenda Views: collecting tasks and dates from many files into one view, and building custom views.

Part IV: Code and Publishing

  1. Working with Source Code (Babel): evaluating code blocks, passing data between them, and tangling source files.
  2. Exporting: the export dispatcher, settings, and the built-in backends.
  3. Publishing and Citations: publishing projects of many files, and citations with bibliographies.

Part V: Mastery

  1. Hacking and Extending Org: hooks, the element API, new link types and export backends.
  2. Org Beyond the Basics: encryption, org-protocol, mobile access, terminal use and other packages.
  3. Putting It Together: complete systems built from the features in this book.
  4. Key Bindings and Glossary: a key reference grouped by task and a glossary of Org terms.

Suggested paths

  • Task management: chapters 2 and 3, then 8, 10, 12 and 13. Add 9 and 11 when your lists grow, and finish with the task system in chapter 19.
  • Writing and publishing: chapters 2 to 5, then 15 and 16. Read chapter 6 if your documents contain tables.
  • Literate programming and notebooks: chapters 2 to 4, then 14 and 15.

Version and sources

This book describes Org 9.8.13, the latest stable release at the time of writing. All facts were taken from the Org repository at the tag release_9.8.13 (commit e24d7f830679bdedc4f00757753f02ae6aca87be):

  • doc/org-manual.org, the source of the official manual,
  • doc/org-guide.org, the compact guide,
  • lisp/*.el, the Lisp source, which decides whenever the documentation is ambiguous,
  • etc/ORG-NEWS, the list of changes between releases.

Links to source files point to that exact commit in the emacs-straight/org-mode mirror on GitHub, so that they keep showing the code this book describes. The official repository is hosted on Savannah, with a mirror at https://git.sr.ht/~bzg/org-mode; the project website is https://orgmode.org.

The book was written independently of the official manual. It is not a translation or an abridgment of it: the explanations, the order of topics and the examples are its own, and the manual’s text is not copied. Key bindings, names of variables and functions, keywords and short syntax samples are reproduced exactly, because they are the interface of the program. Where the manual and the source disagreed (for instance about the name of a #+STARTUP option), the book follows the source.

Examples that show a result, such as an exported fragment, a recalculated table or the output of a code block, were produced by running Org 9.8.13 in batch Emacs (GNU Emacs 31.1), and the output is shown as Emacs printed it. Each chapter ends with a “Further reading” list that links the corresponding sections of the official manual at https://orgmode.org/manual/ and, where useful, the relevant source files.

Conventions in this book

  • Keys and key sequences are written as code: C-c C-c means Control and c, then Control and c again. M- is Meta (usually Alt) and S- is Shift.
  • Commands, variables and functions are also written as code: org-agenda-files. You can read the documentation of any of them with C-h f (functions) or C-h v (variables).
  • Org examples appear in blocks marked org, configuration in blocks marked elisp, and program output in plain blocks.
  • Each chapter defines Org terms the first time it uses them. Chapter 20 collects them in a glossary.
  • Figures are numbered by chapter in order of appearance: Figure 3.2 is the second figure of chapter 3. The sentence under each figure states what the figure shows.

Further reading

Getting Started

This chapter takes you from an empty Emacs to a working Org setup and a first file. Along the way it introduces the habits that the rest of the book relies on: how Org names its keys, why one key can do many things, how to insert common structures quickly, and how to tell Org about per-file settings. It ends with org-lint, a checker that catches mistakes before they cause confusing behavior.

Installing and checking Org

Org is part of GNU Emacs, so you probably have it already. To see which version you are running, type M-x org-version. This book describes Org 9.8.13; if your version is older, most of the material still applies, but some commands (for example the link preview commands in Markup for Rich Contents) are new in 9.8.

Each Org release supports the latest Emacs release and the two before it. According to ORG-NEWS, Org 9.8 requires at least Emacs 28; support for Emacs 26 and 27 was dropped in this release.

Installing a newer version

If the bundled version is too old, you can install a newer Org on top of it. Choose one method and stay with it, because mixing installation methods is a common cause of strange errors.

  • From the package archive. Run M-x list-packages and upgrade org. Do this in a session where you have not yet opened any Org file; otherwise parts of the old version are already loaded and will conflict with the new one. With Emacs 30 or later, the safest way is a separate batch process:

    emacs -Q -batch -eval "(progn (package-refresh-contents) (package-upgrade 'org))"
    
  • From the Git repository. Clone the repository, run make autoloads (this step is required: it generates the version file and the autoload definitions), and put the lisp directory first in your load path:

    (add-to-list 'load-path "~/src/org-mode/lisp")
    

The examples in this book were run against a Git checkout of the release_9.8.13 tag, loaded exactly this way.

Activating Org

Files whose names end in .org open in Org mode automatically. For a file with another extension, make the first line a mode line:

MY PROJECTS    -*- mode: org; -*-

Org needs Font Lock (syntax highlighting), which is on by default in Emacs. Many Org commands also act on the active region, which relies on Transient Mark mode, also on by default.

Three global keys

Most Org commands only make sense inside an Org buffer, but three are useful everywhere: storing a link to the current location, opening the agenda, and capturing a quick note. Bind them to keys that work in every buffer. The key sequences C-c followed by a plain letter are reserved for users, so these bindings will not collide with any mode:

(global-set-key (kbd "C-c l") #'org-store-link)
(global-set-key (kbd "C-c a") #'org-agenda)
(global-set-key (kbd "C-c c") #'org-capture)

The rest of this book assumes these bindings. The commands themselves are explained in Hyperlinks, Agenda Views and Capture, Refile, Archive and Attachments.

Your first file

Open a new file, for example ~/org/start.org, and type the following. Do not worry about every symbol yet; the point is to see how little syntax a useful file needs.

#+TITLE: Getting started with Org

* Learn the basics
** TODO Read the structure chapter
** TODO Try visibility cycling
- press TAB on a headline
- press S-TAB anywhere

* Shopping
| Item   | Qty |
|--------+-----|
| apples |   3 |
| kiwi   |  12 |

* Notes
Org files are plain text. Emphasis looks like *this*,
and a link looks like [[https://orgmode.org][the Org website]].

Now try a few commands:

  1. Put point on * Learn the basics and press TAB several times. The subtree folds and unfolds.
  2. Press S-TAB a few times to switch the whole file between an overview, the list of headlines, and the full text.
  3. On ** TODO Read the structure chapter, press C-c C-t. The keyword changes from TODO to DONE.
  4. Put point at the end of ** TODO Try visibility cycling and press M-RET. A new headline appears at the same level.
  5. In the table, change 12 to 120 and press TAB. The table realigns itself.
  6. Put point on the link and press C-c C-o to open it.

Each of these actions has its own chapter: Document Structure for 1, 2 and 4, TODO Items for 3, The Table Editor for 5, and Hyperlinks for 6.

How Org names its keys

Org uses the standard Emacs notation. C-x means holding Control while pressing x, M-x means Meta (usually Alt), and S- means Shift. RET, TAB, SPC and the arrow keys LEFT, RIGHT, UP, DOWN are written as words. C-c C-t is a sequence: first C-c, then C-t.

Most Org-specific keys start with C-c, followed by a control key (C-c C-t) or by C-c C-x and another key (C-c C-x C-w). The plain-letter C-c keys stay free for your own bindings.

One key, many meanings

Org deliberately reuses a small set of keys and lets the context decide what they do. The idea is that one familiar gesture should mean “the natural operation here”. M-RIGHT is a good example: on a headline it demotes the headline, in a plain list it indents the item, and in a table it moves the column to the right.

Internally, such keys are bound to a generic command (here org-metaright) that inspects point and calls the specific command (org-do-demote, or org-table-move-column-right). This book, like the manual, names the specific command whenever it can.

The main families of context-sensitive keys are:

KeysGeneral meaning
TAB, S-TABCycle visibility; in tables, move between fields.
M-RETInsert a new item of the same kind: headline, list item or table row.
M-LEFT, M-RIGHT, M-UP, M-DOWNChange the level or the position of the thing at point.
S-LEFT, S-RIGHT, S-UP, S-DOWNChange a value at point: TODO state, priority, timestamp, bullet type.
C-c C-c“Do the obvious thing here.”

The Shift-arrow keys conflict with Emacs’s Shift selection. By default (org-support-shift-select is nil), Org gives them its own meaning in these contexts instead of selecting text. On a text terminal, some of these key combinations may not reach Emacs at all; Org Beyond the Basics lists the alternative keys.

The busy key: C-c C-c

C-c C-c (org-ctrl-c-ctrl-c) is the most heavily loaded key in Org. When you are unsure how to “apply” or “update” something, it is usually the right key. The command checks a series of conditions in a fixed order and runs the first action that applies.

flowchart TD
    K["C-c C-c"] --> A{"Column view or temporary highlights?"}
    A -- yes --> A1["Quit column view or remove highlights"]
    A -- no --> B{"Special buffer, such as capture?"}
    B -- yes --> B1["Finish: file the note"]
    B -- no --> C{"Babel result hash, or a function on org-ctrl-c-ctrl-c-hook?"}
    C -- yes --> C1["Run that handler"]
    C -- no --> D["Inspect the element or object at point"]
    D --> E["Act on it: run a code block, align a table, toggle a checkbox, refresh keywords, set tags, jump to a footnote"]
    D --> F["Nothing matches: org-ctrl-c-ctrl-c-final-hook, else an error"]

Figure 2.1: C-c C-c first checks a few global situations, then dispatches on the syntax at point.

The order comes from the source of org-ctrl-c-ctrl-c in lisp/org.el. The most common actions, by what is at point:

Point is onC-c C-c does
A source block or an inline code callEvaluate the code (Working with Source Code).
A tableRealign it and recalculate the current line; on a #+TBLFM line, apply all formulas.
A plain list item with a checkboxToggle the checkbox; on other items, repair the list.
A #+KEYWORD lineReread all in-buffer settings.
A headlineSet tags.
A property drawer or property lineOffer property commands.
A footnote reference or definitionJump to the other end.
A statistics cookie such as [1/3]Update it.
A #+BEGIN: line of a dynamic blockUpdate the block.
A timestampCorrect the day name.

Two of these can be seen in batch Emacs. With point in this table, C-c C-c produces the aligned version on the right:

| Name | Qty |
|-
| apples | 3 |
| kiwi | 12 |
| Name   | Qty |
|--------+-----|
| apples |   3 |
| kiwi   |  12 |

And on a timestamp with the wrong day name, <2026-11-19 Mon> becomes <2026-11-19 Thu>.

The two hooks let packages add their own behavior. A function on org-ctrl-c-ctrl-c-hook runs before Org’s own checks and takes over the key whenever it returns non-nil; a function on org-ctrl-c-ctrl-c-final-hook runs only if nothing else applies.

Completion

Inside an Org buffer, M-TAB completes the text before point. Org does not bind M-TAB itself; it adds its own function to completion-at-point-functions, and the global M-TAB command uses it. What is completed depends on what you have typed:

ContextCompletes
At the start of an empty headlineTODO keywords
After \Entities and TeX symbols
After : in a headlineTags
After : elsewhereProperty names used in the buffer
After [[Link abbreviations
After [[*Headlines of the buffer, for internal links
After #+Keywords such as TITLE or STARTUP; a second M-TAB after a complete keyword inserts example settings
After #+STARTUP:Startup options

If your window manager uses M-TAB to switch windows, C-M-i runs the same command, and ESC TAB also works.

Structure templates

Blocks such as #+begin_src … #+end_src are typed so often that Org provides a shortcut. C-c C-, (org-insert-structure-template) asks for a key and inserts the matching block at point. With an active region, it wraps the region in the block. For example, selecting the line (message "hi") and choosing src emacs-lisp gives:

#+begin_src emacs-lisp
(message "hi")
#+end_src

The keys come from org-structure-template-alist. In Org 9.8.13 its default value is:

KeyBlock
a#+begin_export ascii
c#+begin_center
C#+begin_comment
e#+begin_example
E#+begin_export
h#+begin_export html
l#+begin_export latex
q#+begin_quote
s#+begin_src
v#+begin_verse

Pressing TAB, RET or SPC at the prompt lets you type any block type instead. You can add your own entries; this one makes el produce an Emacs Lisp source block:

(with-eval-after-load 'org
  (add-to-list 'org-structure-template-alist '("el" . "src emacs-lisp")))

Org Tempo: typing <s TAB

If you prefer to type the shortcut directly in the text, load Org Tempo:

(require 'org-tempo)

You can also enable it by adding org-tempo to org-modules. Then type <s at the start of a line and press TAB: Org replaces the two characters with an empty source block. Every key in org-structure-template-alist works this way, and org-tempo-keywords-alist adds keyword shortcuts. By default <L expands to #+latex: , <H to #+html: , <A to #+ascii: and <i to #+index: .

Speed keys

Most Org commands need a modifier key. Speed keys remove that need in one specific place: when point is at the very beginning of a headline (before the first star), a single letter runs a command. Elsewhere, letters insert themselves as usual. This makes navigation and restructuring fast, especially when you are reviewing an outline.

Speed keys are off by default. Turn them on with:

(setq org-use-speed-commands t)

The built-in keys are defined in org-speed-commands. Some of the most useful ones:

KeyCommandEffect
n, porg-next-visible-heading, org-previous-visible-headingMove to the next or previous headline.
f, borg-forward-heading-same-level, org-backward-heading-same-levelMove between siblings.
uoutline-up-headingMove to the parent.
c, Corg-cycle, org-shifttabCycle the subtree or the buffer.
sorg-toggle-narrow-to-subtreeNarrow to the subtree, or widen again.
U, Dorg-metaup, org-metadownMove the subtree up or down.
r, lorg-metaright, org-metaleftDemote or promote the headline.
torg-todoChange the TODO state.
,org-prioritySet the priority.
:org-set-tags-commandSet tags.
I, Oorg-clock-in, org-clock-outStart or stop the clock.
worg-refileRefile the entry.
?org-speed-command-helpList all active speed keys.

To add your own, append entries to org-speed-commands. Each entry pairs a single character with a command; an entry containing only a string becomes a heading in the help list. Choose letters that are not already taken, because the first matching entry wins:

(setq org-speed-commands
      (append org-speed-commands
              '(("Personal")
                ("y" . org-copy-subtree))))

In-buffer settings

Many Org options can be set in two places: globally in your init file, or for a single file through lines that start with #+. Such a line is called a keyword (an in-buffer setting when it configures Org). It has the form #+NAME: value; the name is case-insensitive.

#+TITLE: Home server notes
#+STARTUP: overview indent
#+TODO: TODO WAIT | DONE
#+FILETAGS: :homelab:

Per-file settings travel with the file, which matters when you share it or open it on another machine. A setting in the file overrides the global default for that buffer only.

flowchart LR
    I["Init file: setq org-..."] -->|global default| B["Buffer settings"]
    S["#+SETUPFILE: shared.org"] -->|keywords read from it| B
    K["#+KEYWORD lines in the file"] -->|override for this file| B
    B -->|inherited by entries| E["Entry"]
    P["Properties of a subtree"] -->|override for some options| E

Figure 2.2: Settings flow from the init file through per-file keywords down to individual entries, with each level able to override the one above for its own scope.

Org reads the keywords when it opens the file. After editing a keyword line, press C-c C-c on it, or Org will keep using the old values. For example, if you add #+TODO: TODO WAIT | DONE to an open buffer, the list of TODO keywords stays ("TODO" "DONE") until you press C-c C-c on that line; afterwards it is ("TODO" "WAIT" "DONE"), and Emacs reports “Local setup has been refreshed”.

The following keywords are the ones you will meet most often:

KeywordSetsExplained in
#+STARTUP:Options applied when the file opens: visibility, indentation, numbering, logging, previewsThis chapter, Document Structure
#+TODO:, #+SEQ_TODO:, #+TYP_TODO:TODO keywords for the fileTODO Items
#+TAGS:Allowed tags and their fast-selection keysTags, Properties and Column View
#+FILETAGS:Tags inherited by every entry in the fileTags, Properties and Column View
#+PROPERTY:Default property values for the fileTags, Properties and Column View
#+CATEGORY:The category shown in the agendaAgenda Views
#+PRIORITIES:Highest, lowest and default priorityTODO Items
#+ARCHIVE:Where archived subtrees goCapture, Refile, Archive and Attachments
#+LINK:Link abbreviationsHyperlinks
#+COLUMNS:Default column view formatTags, Properties and Column View
#+CONSTANTS:Constants for table formulasThe Spreadsheet and Plotting
#+SETUPFILE:Another file (or URL) whose settings are read as if they were in this fileThis chapter
#+TITLE:, #+AUTHOR:, #+OPTIONS:Export settingsExporting

The STARTUP keyword

#+STARTUP: accepts several words separated by spaces, and several #+STARTUP: lines are allowed. A selection of its options:

OptionEffect
overview, content, showall, show2levels, showeverythingInitial visibility
indent, noindentTurn Org Indent mode on or off
num, nonumTurn dynamic headline numbering on or off
hidestars, showstarsHide all but the last star of each headline
hideblocks, nohideblocksFold all blocks on startup
entitiespretty, entitiesplainDisplay entities as UTF-8 characters
linkpreviews, nolinkpreviewsShow image and link previews on startup
latexpreview, nolatexpreviewShow LaTeX previews on startup
logdone, lognotedone, nologdoneRecord a time (or a note) when a task is completed
align, noalignAlign all tables on startup

Type #+STARTUP: and press M-TAB to see the complete list.

Sharing settings with SETUPFILE

When several files need the same settings (the same TODO keywords, tags, or export options), put them in one file and refer to it:

#+SETUPFILE: ~/org/setup/common.org

Org reads only the in-buffer settings from that file and ignores its other content. The value may also be a URL, in which case Org downloads the file and caches it; C-c C-c on the #+SETUPFILE line rereads the file and clears the cache. C-c ' on the line opens a local setup file for editing.

Checking a file with org-lint

Org is forgiving: syntax it does not recognize simply becomes plain text. The disadvantage is that a mistake rarely produces an error message; a link silently goes nowhere, or a drawer is ignored. M-x org-lint runs a set of checks over the buffer and lists suspicious places in a report buffer.

Consider this short file, which contains four mistakes:

#+TITLE: Notes
* Heading
#+BEGIN_SRC
(+ 1 2)
#+END_SRC
See [[*Missing heading]].
:PROPERTIES:
:ID: x
:END:
A note.[fn:9]

Org 9.8.13 reports the following (line number and message):

LineMessage
3Missing language in source block
6Unknown fuzzy location “Missing heading”
7Incorrect contents for PROPERTIES drawer
10Missing definition for footnote [9]

The third report deserves an explanation: a PROPERTIES drawer is only valid directly after a headline, and here it follows a paragraph. Each report also carries a trust level, because some checks can produce false positives.

In the report buffer, these keys are available:

KeyEffect
C-j, TABShow the offending line in the Org buffer.
RETMove to the offending line.
gRun the checks again.
hHide all reports from the same checker.
iAlso ignore that checker in later runs.
SSort the reports by the column at point.

Running org-lint on a file that behaves strangely is a good first step before searching for a bug elsewhere.

Getting help

C-c C-x I (org-info-find-node) opens the section of the Org manual that matches the syntax at point; on a headline, for example, it shows the chapter on document structure. Press q to close the Info window.

If you think you have found a bug, first check whether it happens in a clean Emacs: start emacs -Q (with Org’s lisp directory in the load path if you use a newer Org than the bundled one) and reproduce the problem there. If it persists, M-x org-submit-bug-report prepares an email to the Org mailing list with your Emacs and Org versions and relevant settings already filled in.

A starter configuration

The following configuration collects the suggestions from this chapter. It was evaluated with Org 9.8.13 in batch mode without errors. Treat it as a starting point; later chapters add settings for tasks, the agenda and capture.

;; Global entry points
(global-set-key (kbd "C-c l") #'org-store-link)
(global-set-key (kbd "C-c a") #'org-agenda)
(global-set-key (kbd "C-c c") #'org-capture)

;; Where your Org files live
(setq org-directory "~/org")

;; Single-key commands at the start of headlines
(setq org-use-speed-commands t)

;; Indented display of every Org file
(setq org-startup-indented t)

;; <s TAB and friends
(require 'org-tempo)
(with-eval-after-load 'org
  (add-to-list 'org-structure-template-alist '("el" . "src emacs-lisp")))

Summary

  • Org ships with Emacs; check the version with M-x org-version and choose a single installation method for upgrades.
  • Bind org-store-link, org-agenda and org-capture to global keys.
  • Org keys are context-sensitive; C-c C-c is the general “apply” key.
  • M-TAB completes, C-c C-, and <s TAB insert blocks, and speed keys give single-letter commands on headlines.
  • #+ keywords configure a single file; press C-c C-c on them after editing.
  • M-x org-lint finds silent syntax mistakes.

Further reading

Document Structure

Every Org file is a tree. Headlines form the branches, and everything else (paragraphs, lists, tables, code, metadata) hangs from those branches. Once you see a file as a tree, most of Org’s commands become predictable: they show part of the tree, hide part of it, move a branch, or search inside it.

This chapter covers the parts of Org that shape and navigate that tree: headlines, visibility, motion, structure editing, sparse trees, plain lists, drawers and blocks. It closes with two display options, Org Indent mode and dynamic numbering, that change how the tree looks without changing the file.

Headlines: the backbone of a file

A headline is a line that starts at the left margin with one or more asterisks followed by a space. The number of asterisks is the headline’s level. A level 2 headline under a level 1 headline is its child; two headlines of the same level under the same parent are siblings.

* Projects
** Home server
*** Buy disks
Two 2 TB SSDs, mirrored.
*** Install the OS
** Website
* Reading list

Three terms recur throughout the book, so it helps to fix them now:

TermMeaning
EntryA headline together with the text directly under it, up to the next headline of any level.
SectionThe text of an entry without its headline line.
SubtreeA headline, its section, and all its descendants.

In the example above, the subtree of ** Home server contains both level 3 headlines and the text about the SSDs. When you fold ** Home server, the whole subtree disappears behind one line; when you move it, the whole subtree moves.

The anatomy of a headline

A headline is more than a title. Between the stars and the end of the line, Org recognizes several optional components, always in a fixed order.

Figure 3.1: Each optional part of a headline has a fixed position, which is what lets Org parse it reliably.

The figure labels come from the Org parser itself. Running org-element-at-point on that headline in Org 9.8.13 reports these properties:

:level => 2
:todo-keyword => "TODO"
:todo-type => todo
:priority => 65
:commentedp => t
:raw-value => "Write chapter 3 [1/2]"
:title => "Write chapter 3 [1/2]"
:tags => ("book" "draft")

The priority is stored as a character code (65 is A), and the statistics cookie [1/2] stays inside the title. Each component has its own chapter:

Only the stars and the space are required. * Groceries is a complete, valid headline.

Reserved titles and blank lines

One headline title has a special meaning. The variable org-footnote-section (default "Footnotes") names the heading under which Org collects footnote definitions, so do not use that title for ordinary content.

Blank lines also matter. A single empty line after a subtree belongs to the subtree and is hidden when the subtree is folded. If you leave at least two empty lines, one of them stays visible in the folded view, which can make a long outline easier to scan. The threshold is controlled by org-cycle-separator-lines (default 2).

Visibility cycling

The main reason to use an outliner is that you can hide what you are not working on. Org reduces folding to two keys: TAB acts on the subtree at point, and S-TAB acts on the whole buffer. Each key rotates through three states.

stateDiagram-v2
    direction LR
    state "Local: TAB on a headline" as local {
        FOLDED --> CHILDREN: TAB
        CHILDREN --> SUBTREE: TAB
        SUBTREE --> FOLDED: TAB
    }
    state "Global: S-TAB anywhere" as global {
        OVERVIEW --> CONTENTS: S-TAB
        CONTENTS --> SHOW_ALL: S-TAB
        SHOW_ALL --> OVERVIEW: S-TAB
    }

Figure 3.2: TAB rotates one subtree through three states, while S-TAB rotates the entire buffer through three corresponding states.

The local states mean the following:

  • FOLDED shows only the headline.
  • CHILDREN shows the headline’s own text and the headlines of its direct children, but not their contents.
  • SUBTREE shows everything below the headline.

Two edge cases are worth knowing. If the entry has no text and no children, TAB only reports EMPTY ENTRY. If the entry has text but no children, Org skips the CHILDREN state and goes straight to SUBTREE, because org-cycle-skip-children-state-if-no-children is t by default.

The global states are OVERVIEW (top-level headlines only), CONTENTS (all headlines, no body text) and SHOW ALL. With a numeric prefix, S-TAB shows headlines down to that level: C-u 2 S-TAB displays levels 1 and 2.

Here is a small file and what each global state leaves visible. The output was produced in batch Emacs by calling org-cycle-overview and org-cycle-content and printing only the visible characters.

#+TITLE: Home server
* Hardware
A small fanless box.
** Disks
Two mirrored SSDs.
** Network
FIXME: assign a static address.
* Services
** Backup
Nightly at 02:00.
** Media
FIXME: move the library.
==== overview
#+TITLE: Home server
* Hardware
* Services
==== contents
#+TITLE: Home server
* Hardware
** Disks
** Network
* Services
** Backup
** Media

Pressing TAB three times on * Services from the overview produces the three local states. After the first press you see ** Backup and ** Media; after the second you also see their text; after the third, * Services is folded again.

More visibility commands

TAB and S-TAB cover daily work. The remaining commands help when you need a specific view.

KeyCommandEffect
C-u C-u TABorg-cycle-set-startup-visibilityReturn to the visibility the file had when it was opened.
C-u C-u C-u TABorg-fold-show-allReveal the whole buffer, drawers included.
C-c C-rorg-fold-revealShow the context around point: the current entry, the following heading, and the headlines above.
C-c C-korg-kill-note-or-show-branchesShow all headings of the subtree without their bodies.
C-c TABorg-fold-show-childrenShow the direct children; with a numeric prefix N, down to level N.
C-c C-x borg-tree-to-indirect-bufferShow the current subtree in a separate indirect buffer.
C-c C-x vorg-copy-visibleCopy only the visible text of the region.

org-fold-reveal (also available under its older name org-reveal) is most useful after a search or an agenda jump has dropped you inside a mostly folded file. org-tree-to-indirect-buffer is a good way to focus on one project: the indirect buffer shares its text with the original, so edits appear in both places.

Inside a table, S-TAB moves to the previous field instead of cycling. If you want TAB at the very beginning of a buffer (before the first headline) to cycle globally, set org-cycle-global-at-bob to t.

Initial visibility

When Emacs opens an Org file, it shows everything by default, because org-startup-folded is showeverything. You can change the default globally or per file. A per-file setting is a #+STARTUP: line anywhere in the buffer:

#+STARTUP: overview

The values for initial visibility are overview, content, showall, show2levels to show5levels, and showeverything. The difference between showall and showeverything is drawers: showeverything also opens them.

A single subtree can override the file-wide setting through its VISIBILITY property, with one of the values folded, children, content or all:

* Archive of old notes
:PROPERTIES:
:VISIBILITY: folded
:END:

Properties are covered in Tags, Properties and Column View. C-u C-u TAB restores exactly this combination of startup option and VISIBILITY properties, so it is a quick way to tidy a buffer after a long editing session.

Protecting hidden text

Folding creates a risk: you might delete or type inside text you cannot see. Org checks for this. The variable org-fold-catch-invisible-edits (default smart) decides how cautious Org is, and org-fold-catch-invisible-edits-commands lists the commands that are checked. Setting the first variable to nil turns the protection off, which is rarely a good idea.

Moving between headlines

The motion commands treat headlines as stepping stones, skipping the body text in between.

KeyCommandMoves to
C-c C-norg-next-visible-headingThe next visible headline.
C-c C-porg-previous-visible-headingThe previous visible headline.
C-c C-forg-forward-heading-same-levelThe next sibling.
C-c C-borg-backward-heading-same-levelThe previous sibling.
C-c C-uorg-up-headingThe parent headline.
C-c C-jorg-gotoA headline you choose in a temporary outline view.

org-goto is the tool for long files. It opens a copy of the outline in which you can fold, unfold and search; when you press RET, point moves to the chosen headline in the original buffer, and the buffer’s visibility stays as it was. By default you can type to start an incremental search immediately (org-goto-auto-isearch is t). The variable org-goto-interface switches to a different interface that reads an outline path with completion.

If you turn on Emacs’s repeat-mode, these motion keys become repeatable. After C-c C-n, you can press n, p, f, b or u alone to keep moving, until you press any other key. The bindings live in org-navigation-repeat-map; block and link navigation (C-c M-f, C-c M-b, C-c C-x C-n, C-c C-x C-p) have their own repeat maps, org-block-navigation-repeat-map and org-link-navigation-repeat-map.

Editing the structure

Because a subtree is a unit, Org lets you insert, promote, move and copy whole subtrees with single commands. The commands are designed so that the tree stays valid after every step.

Inserting headlines

M-RET (org-meta-return) inserts a new headline at the same level as the current one. Its exact behavior depends on where point is:

  • At the beginning of a headline, the new headline is created before the current line.
  • At the beginning of an ordinary text line, that line becomes a headline.
  • In the middle of a line, Org splits the line, and the text after point becomes the title of the new headline. Customize org-M-RET-may-split-line to keep lines intact.

For example, with point after groceries in * Buy groceries and cook dinner, M-RET produces two headlines, * Buy groceries and * and cook dinner (the space before and comes along with the split text).

C-RET (org-insert-heading-respect-content) is often more convenient: it always inserts the new headline after the end of the current subtree, so you never split a subtree by accident. M-S-RET and C-S-RET do the same as M-RET and C-RET but add a TODO keyword.

When the new headline is still empty, TAB changes its level: the first press makes it a child of the previous headline, further presses move it up through the parent levels, and eventually it returns to where it started. This is the fastest way to place a new headline at the right depth.

Promoting, demoting and moving

KeyCommandEffect
M-LEFT / M-RIGHTorg-do-promote / org-do-demoteChange the level of the current headline only.
M-S-LEFT / M-S-RIGHTorg-promote-subtree / org-demote-subtreeChange the level of the whole subtree.
M-UP / M-DOWNorg-move-subtree-up / org-move-subtree-downSwap the subtree with its previous or next sibling.

The difference between the plain and the shifted promote commands matters. M-RIGHT on a headline with children demotes only that headline, which can make its former children its siblings. M-S-RIGHT keeps the subtree intact. Here is org-demote-subtree applied to * Website:

* Projects
* Website
** Pick a theme
** Write the about page
* Reading
* Projects
** Website
*** Pick a theme
*** Write the about page
* Reading

M-UP and M-DOWN never break the hierarchy: they swap a subtree only with a sibling of the same level. With point on * Reading in the file * Projects, * Website (with a child), * Reading, one M-UP gives * Projects, * Reading, * Website, and the child ** Pick a theme travels with * Website.

If the region is active, the promote and demote commands act on every headline in it. Many other commands (scheduling, setting TODO states) also loop over all headlines in an active region; this is controlled by org-loop-over-headlines-in-active-region (default t).

Cutting, copying and pasting subtrees

KeyCommandEffect
C-c @org-mark-subtreeMark the subtree; repeat to extend the mark to following siblings.
C-c C-x C-worg-cut-subtreeKill the subtree.
C-c C-x M-worg-copy-subtreeCopy the subtree to the kill ring.
C-c C-x C-yorg-paste-subtreeYank a subtree, adjusting its level to fit the location.
C-yorg-yankYank; subtrees are folded after yanking by default.

org-paste-subtree is the careful way to paste: it changes the levels of the yanked subtree so that it fits at point. With C-u it inserts the subtree as a sibling, with C-u C-u as a child. Plain C-y runs org-yank, which by default does not adjust levels (org-yank-adjusted-subtrees is nil) but folds the pasted subtree (org-yank-folded-subtrees is t). Use C-u C-y for a completely ordinary yank.

Two related commands copy structure in bulk:

  • C-c C-x c (org-clone-subtree-with-time-shift) creates several sibling copies of a subtree and can shift the timestamps in each copy, for example to prepare one entry per weekly meeting.
  • C-c C-w (org-refile) moves an entry to another place, possibly in another file. Refiling is a central part of task management and is covered in Capture, Refile, Archive and Attachments.

Sorting

C-c ^ (org-sort) sorts the children of the current headline, or all entries in the active region. It asks for a sorting key: alphabetical, numeric, by time (several kinds of timestamp), by priority, by TODO keyword, by a property value, or by a function you supply. An uppercase key reverses the order, and C-u makes alphabetical sorting case-sensitive.

Sorting * Shopping alphabetically (C-c ^ a) changes the order of its children:

* Shopping
** milk
** bread
** apples
* Shopping
** apples
** bread
** milk

Narrowing and converting

Narrowing restricts the buffer to one part, so that commands and searches cannot reach the rest. C-x n s (org-narrow-to-subtree) narrows to the current subtree, C-x n b (org-narrow-to-block) to the current block, and C-x n w (widen) shows the whole buffer again.

C-c * (org-toggle-heading) converts in both directions. On an ordinary line or a list item it creates a headline at the appropriate level; on a headline it removes the stars. With point on A plain line under * Ideas, the result is a child headline:

* Ideas
** A plain line

Sparse trees

A sparse tree is a view in which the whole file is folded except for the parts that match a query, together with the headlines above them. It answers questions such as “where did I write FIXME?” without losing the context of each match.

All sparse tree commands start from one dispatcher, C-c / (org-sparse-tree), which asks for a second key. The simplest is C-c / r (or C-c / /), org-occur, which searches for a regular expression. Applied to the home server file from earlier with the pattern FIXME, it leaves exactly this visible:

#+TITLE: Home server
* Hardware
** Network
FIXME: assign a static address.
* Services
** Media
FIXME: move the library.

Each match is also highlighted. The highlights disappear when you edit the buffer or press C-c C-c (governed by org-remove-highlights-with-change). With C-u, a new search keeps the previous highlights, so you can combine several queries. M-g n and M-g p (next-error and previous-error) jump between matches.

The regular expressions are Emacs Lisp regular expressions, so alternation is written \|: the pattern FIXME\|TODO matches either word. How much context Org reveals around a match is controlled by org-fold-show-context-detail.

The other sparse tree commands select headlines by TODO state, tags, properties or dates; they are described in TODO Items, Tags, Properties and Column View and Dates and Times. A search you run often can be given its own key in the agenda dispatcher:

(setq org-agenda-custom-commands
      '(("f" occur-tree "FIXME")))

After this, C-c a f (assuming org-agenda is bound to C-c a, as in Getting Started) builds the FIXME sparse tree in the current buffer. Custom commands are covered fully in Agenda Views.

Plain lists

Headlines give a file its large-scale structure. Inside an entry, plain lists provide finer structure without creating new entries. Org recognizes three kinds:

  • Unordered items start with -, + or * (a * bullet needs indentation, otherwise it would be a headline).
  • Ordered items start with a number followed by . or ), such as 1. or 1).
  • Description items are unordered items that contain :: to separate a term from its description.
* Release checklist
Before tagging a release:
1. Update the changelog
2. Run the test suite
   - unit tests
   - integration tests, which need the staging database
3. [@5] Bump the version number
Terms used above:
- Changelog :: The file etc/NEWS in the repository.
- Staging :: The shared test environment.

Indentation defines the structure. All items of one list must start at the same indentation, and an item ends before the next line that is indented as much as its bullet or less. A list ends when every item has ended, or before two consecutive blank lines. In the example, Terms used above: is not indented, so it closes the numbered list and starts a new paragraph.

The [@5] cookie sets the counter of an ordered item: the third item is numbered 5, and any following items continue from there. When you repair this list with C-c C-c (described below), Org rewrites the bullet as 5. [@5] Bump the version number, so the plain text shows the same number as the export.

List commands

Most list commands share their keys with the headline commands, so the habits you build for headlines transfer directly.

KeyEffect on a list item
M-RETInsert a new item at the same level (split the item if point is in the middle).
M-S-RETInsert a new item with a checkbox.
TABFold the item; in an empty new item, change its level.
M-UP / M-DOWNMove the item with its sub-items; ordered lists are renumbered.
M-LEFT / M-RIGHTChange the indentation of the item only.
M-S-LEFT / M-S-RIGHTChange the indentation of the item and its sub-items.
C-c C-cToggle a checkbox, and repair bullets, indentation and numbering.
C-c -Cycle the bullet style of the whole list level.
S-LEFT / S-RIGHTAlso cycle the bullet style (when shift selection is off).
C-c *Turn the item into a headline.
C-c C-*Turn the whole list into subtrees of the current headline.
C-c ^Sort the list.

Repairing a list is a frequent need after manual editing. With point on any item, C-c C-c renumbers an ordered list:

Steps:
1. Install Emacs
3. Open a file
7. Save it
Steps:
1. Install Emacs
2. Open a file
3. Save it

C-c - rotates the bullet type, for example from - to +. C-c C-* (org-list-make-subtree) is useful when a list outgrows itself and its items deserve to become entries. Checkboxes become TODO keywords on the way:

* Trip
- [ ] Book flights
- [X] Renew passport
- Pack
* Trip
** TODO Book flights
** DONE Renew passport
** Pack

Checkboxes and their statistics cookies are covered in TODO Items.

Tuning lists

A few variables adjust list behavior:

  • org-list-demote-modify-bullet changes the bullet automatically when you demote an item, which helps distinguish levels visually.
  • org-list-indent-offset (default 0) adds extra indentation to sub-items.
  • org-list-automatic-rules controls the automatic corrections that list commands apply; disable individual rules if one gets in your way.
  • org-cycle-include-plain-lists (default t) lets TAB fold list items. The value integrate makes items behave like low-level headlines during cycling.
  • org-plain-list-ordered-item-terminator restricts ordered items to . or ).

Lists or headlines?

The two structures overlap, so a rule of thumb helps.

Use a headline whenUse a list when
The item needs its own TODO state, tags, dates or properties.The items are short and belong to one entry.
You want it to appear in the agenda.You want a checklist inside a single task.
It will collect notes, logs or attachments over time.Order and grouping are all the structure you need.

C-c * and C-c C-* make the decision reversible, so you can start with a list and promote items later.

Drawers

Some information belongs to an entry but should normally stay out of sight: metadata, logs, private notes. A drawer holds such information. It starts with a line containing a name between colons and ends with :END::

** Weekly meeting
Agenda is in the shared folder.
:NOTES:
Ask about the budget before Friday.
:END:
After the drawer, ordinary text continues.

A drawer can contain anything except a headline or another drawer. When you cycle visibility on the headline, the drawer stays collapsed to its first line; to open it, move point to the drawer line and press TAB.

C-c C-x d (org-insert-drawer) inserts a drawer at point and asks for its name; with an active region, it wraps the region in the drawer. M-TAB completes drawer names.

Two drawer names have built-in meanings:

  • PROPERTIES holds the entry’s properties and must come directly after the headline (and its planning line, if any). With a prefix argument, C-c C-x d creates it. It cannot be used for anything else. See Tags, Properties and Column View.
  • LOGBOOK can collect state-change notes and clock records. C-c C-z adds a time-stamped note to it. See TODO Items and Clocking, Effort and Timers.

The order of these parts inside an entry is fixed, which is why Org can find them quickly.

flowchart TD
    H["Headline: ** TODO Weekly meeting :work:"] --> P["Planning line: SCHEDULED / DEADLINE"]
    P --> PD["PROPERTIES drawer"]
    PD --> LB["LOGBOOK and other drawers"]
    LB --> B["Body: paragraphs, lists, tables, blocks"]
    B --> C["Child headlines (next level)"]

Figure 3.3: An entry is read top to bottom: the planning line and the PROPERTIES drawer must directly follow the headline, while other drawers and the body can follow in any arrangement.

Blocks

A block is a region delimited by #+BEGIN_NAME and #+END_NAME lines. Blocks hold content that needs special treatment: quotations, examples, source code, export-specific snippets, or the output of dynamic computations.

#+BEGIN_QUOTE
Simple things should be simple.
#+END_QUOTE

Keywords and block names are case-insensitive, so #+begin_quote is equally valid; Org’s own insertion commands use lowercase. The kinds of block and their meanings are described in Markup for Rich Contents and, for code, in Working with Source Code.

For structure, the important point is that blocks fold like headlines. Press TAB on the #+BEGIN line to hide or show the contents. To fold all blocks when a file opens, set org-hide-block-startup or use one of these lines:

#+STARTUP: hideblocks
#+STARTUP: nohideblocks

A cleaner outline view

Long chains of stars can make a deep outline look busy, and text under a level 4 headline still starts at column 0. Org offers two ways to get an indented view.

Org Indent mode

M-x org-indent-mode changes only the display. Each headline shows a single visible star, and the text below it is shifted by virtual spaces so that it lines up with the headline text. The file on disk does not change, so collaborators and other tools see a normal Org file.

File contents               With Org Indent mode
* Top level                 * Top level
** Second level               * Second level
some text                       some text
*** Third level                 * Third level
more text                         more text

Each level is shifted by org-indent-indentation-per-level characters (default 2). By default, Org Indent mode also hides leading stars and locally disables org-adapt-indentation. To change this, customize org-indent-mode-turns-on-hiding-stars (for the stars) or org-indent-mode-turns-off-org-adapt-indentation (for the indentation).

To use it everywhere, set org-startup-indented to t; for a single file, add #+STARTUP: indent (or noindent to override a global setting).

Hard indentation

If the file itself should look indented, even in another editor, Org can write real spaces instead:

(setq org-adapt-indentation t
      org-hide-leading-stars t
      org-odd-levels-only t)
  • org-adapt-indentation makes filling and structure editing indent text to match its headline. The value headline-data limits this to planning lines and drawers.
  • org-hide-leading-stars paints all stars but the last in the background color (the org-hide face). The per-file equivalents are #+STARTUP: hidestars and showstars.
  • org-odd-levels-only uses only levels 1, 3, 5 and so on, which doubles the visual step between levels. The per-file equivalents are #+STARTUP: odd and oddeven. To convert an existing file, use M-x org-convert-to-odd-levels or M-x org-convert-to-oddeven-levels.

Virtual indentation is the better default: it costs nothing in the file and can be switched off at any time. Choose hard indentation only when the plain file must look indented outside Emacs.

Dynamic headline numbering

Headlines in Org carry no numbers, which keeps reordering cheap. When you want numbers on screen, for example while discussing a document in a meeting, turn on M-x org-num-mode. It displays numbers in front of the headlines and updates them as you edit the structure; the file itself is unchanged.

You can exclude headlines from numbering by level (org-num-max-level), by tag (org-num-skip-tags), when they are commented (org-num-skip-commented), when they have a non-nil UNNUMBERED property (org-num-skip-unnumbered), or when they are the footnote section (org-num-skip-footnotes). All five are off by default. In this example only org-num-skip-tags is set to ("noexport"):

* Intro
* Setup
** Install
** Configure
* Notes :noexport:
* Appendix
:PROPERTIES:
:UNNUMBERED: t
:END:

Org 9.8.13 numbers the headlines as follows (the strings are the overlays that org-num-mode adds):

* Intro                 "1 "
* Setup                 "2 "
** Install              "2.1 "
** Configure            "2.2 "
* Notes :noexport:      (none)
* Appendix              "3 "

The tagged headline is skipped, but * Appendix is still numbered, because org-num-skip-unnumbered is nil by default. Set it to t if numbering should follow the same UNNUMBERED property that export uses.

The appearance is controlled by org-num-face and org-num-format-function. To turn the mode on for every file, set org-startup-numerated to t; for one file, use #+STARTUP: num.

Summary

  • A file is a tree of headlines; an entry is a headline with its text, and a subtree adds all descendants.
  • TAB cycles a subtree and S-TAB cycles the buffer, each through three states.
  • C-c C-n, C-c C-p, C-c C-f, C-c C-b, C-c C-u and C-c C-j move between headlines.
  • M-RET, C-RET, the M- arrow keys and C-c ^ insert, restructure and sort; prefer the subtree variants when children are involved.
  • C-c / builds sparse trees that answer a query while keeping the context.
  • Plain lists, drawers and blocks add structure inside an entry.
  • Org Indent mode and Org Num mode change the display only.

Further reading

Markup for Rich Contents

Org started as a tool for organizing notes, but the same plain text can become an HTML page, a PDF or a slide deck. For that, Org needs a way to express emphasis, symbols, formulas, code, images and footnotes. This chapter describes that markup.

Two ideas make the rules easier to remember. First, markup is designed to look reasonable as plain text: *bold* reads as emphasis even in a terminal. Second, every piece of markup is either an element or an object, and that distinction decides where it may appear.

Elements and objects

Org’s parser divides a document into two kinds of syntax:

  • An element is a block-level unit that occupies whole lines: a paragraph, a list, a table, a block, a drawer, a keyword line. Some elements, called greater elements, can contain other elements: a plain list contains items, and a quote block contains paragraphs.
  • An object is an inline unit inside a line: bold text, a link, an entity, a footnote reference, a LaTeX fragment. Objects can contain other objects (italic inside bold), but never elements.

The following entry and its parse tree show the relationship. The tree was printed from org-element-parse-buffer in Org 9.8.13 (plain text nodes omitted):

* Notes
Org is *plain /text/*.[fn:1]
- see =README=

#+BEGIN_QUOTE
Keep it simple.
#+END_QUOTE
flowchart TD
    D["org-data"] --> H["headline: Notes"]
    H --> S["section"]
    S --> P["paragraph (element)"]
    S --> L["plain-list (greater element)"]
    S --> Q["quote-block (greater element)"]
    P --> B["bold (object)"]
    B --> I["italic (object)"]
    P --> F["footnote-reference (object)"]
    L --> IT["item (greater element)"]
    IT --> P2["paragraph (element)"]
    P2 --> V["verbatim (object)"]
    Q --> P3["paragraph (element)"]

Figure 4.1: Elements stack inside greater elements down to paragraphs, and objects live only inside paragraphs and similar text-holding elements.

This explains several rules you will meet below. A caption keyword attaches to the next element, so it can label a table or a paragraph containing a single image link. Emphasis is an object, so it cannot span two paragraphs. The full lists of types are in the variables org-element-all-elements and org-element-all-objects; the parser itself is the subject of Hacking and Extending Org.

Paragraphs and line breaks

A paragraph is a run of text lines separated from other text by at least one empty line. Single line breaks inside a paragraph are not significant: when exporting, Org joins the lines, and the target format decides where to wrap.

When you need a hard line break inside a paragraph, end the line with two backslashes (\\):

Line one\\
line two

The HTML exporter turns this into Line one<br /> followed by line two, still within one <p> element.

Verse, quote and center blocks

Three blocks change how a paragraph is laid out.

BlockPurpose
#+BEGIN_VERSE … #+END_VERSEKeep line breaks, leading spaces and blank lines, for poems and addresses.
#+BEGIN_QUOTE … #+END_QUOTEMark a quotation, usually indented on both sides.
#+BEGIN_CENTER … #+END_CENTERCenter the contained text.
#+BEGIN_VERSE
  Roses
     are red
#+END_VERSE

#+BEGIN_QUOTE
Simple things should be simple.
#+END_QUOTE

Exported to HTML, the verse block keeps its shape through <br /> and non-breaking spaces, while the quote block becomes a <blockquote>:

<p class="verse">
Roses<br />
&nbsp;&nbsp;&nbsp;are red<br />
</p>

<blockquote>
<p>
Simple things should be simple.
</p>
</blockquote>

The text inside these blocks is still Org markup: emphasis and links work as usual. To insert any of them quickly, use the structure templates described in Getting Started.

Emphasis and monospace

Org has 6 inline markers. Each one surrounds the text it applies to:

MarkupMeaningHTMLLaTeX
*bold*Bold<b>bold</b>\textbf{bold}
/italic/Italic<i>italic</i>\emph{italic}
_underlined_Underline<span class="underline">\uline{underlined}
=verbatim=Verbatim<code>verbatim</code>\texttt{verbatim}
~code~Code<code>code</code>\texttt{code}
+struck+Strike-through<del>struck</del>\sout{struck}

The HTML and LaTeX columns are the real output of Org 9.8.13 for the sentence Make words *bold*, /italic/, _underlined_, =verbatim=, ~code~ and +struck+.

Verbatim and code differ from the others in one important way: their contents are not parsed. Inside =...= or ~...~, stars, slashes and brackets are just characters. This makes them the right choice for file names, commands and identifiers. By convention, ~code~ is used for code and =verbatim= for literal strings such as file names, although most backends export both the same way.

Emphasis can be nested, as long as the markers differ:

*bold /and italic/ together*

This exports as <b>bold <i>and italic</i> together</b>.

When a marker counts as markup

A star or slash in the middle of ordinary text should not start emphasis, so Org applies boundary rules. The rules live in org-emphasis-regexp-components; in Org 9.8.13 they say, in summary:

  • The opening marker must be preceded by the start of a line, whitespace, or one of -('"{.
  • The character right after the opening marker, and the character right before the closing marker, must not be whitespace.
  • The closing marker must be followed by the end of a line, whitespace, or one of -.,:!?;'")}\[.

The same variable also limits the number of line breaks, but that limit concerns highlighting in the buffer. In a test, the exporter accepted an italic span that ran over 4 lines of one paragraph.

These rules handle most cases, but they are not perfect. The following sentence was exported to HTML:

*bold /and italic/ together*, but * not bold*, and x*y*z.
A path like /usr/bin/ is fine; but a/b/c is not italic.
<b>bold <i>and italic</i> together</b>, but * not bold*, and x*y*z.
A path like <i>usr/bin</i> is fine; but a/b/c is not italic.

* not bold* is safe because a space follows the opening star, and x*y*z is safe because a letter precedes it. The path /usr/bin/, however, satisfies every rule and becomes italic. There are two ways out:

  • Write paths and identifiers as verbatim: =/usr/bin/= exports as <code>/usr/bin/</code>.
  • Insert a zero width space right after the opening marker (see Escaping Org syntax). The exporter then leaves /usr/bin/ as plain text.

The reverse problem also exists. A marker character inside the emphasized text can end the emphasis early. The line /a sentence with ~user/?var~ inside/ exports as <i>a sentence with ~user</i>?var~ inside/: the slash inside the code is followed by ?, which is a valid closing context, so the italic span ends there and the code markup is lost. Again, a zero width space resolves the ambiguity.

Commands and display options

C-c C-x C-f (org-emphasize) asks for a marker character and applies it. With an active region, it wraps the region; without one, it inserts a pair of markers and places point between them.

Three variables control how emphasis looks in the buffer. None of them changes the file or the export.

  • org-hide-emphasis-markers: when t, the marker characters are hidden, so *bold* displays as a bold word without stars. This makes prose easier to read, but harder to edit at the edges of the emphasis.
  • org-fontify-emphasized-text (default t): set it to nil to turn off emphasis highlighting completely.
  • org-emphasis-alist: maps each marker to its face. Removing an entry stops the highlighting for that marker, but the markup is still recognized on export.

Subscripts and superscripts

_ introduces a subscript and ^ a superscript. Curly braces delimit a longer script:

The area is r^2, and R_{sun} is the solar radius.

Without braces, the script extends over the following run of alphanumeric characters, which may be more than you intended. This is the HTML export of a short sentence:

Water is H_2O, the area is r^2 and R_{sun} differs from file_name.
Water is H<sub>2O</sub>, the area is r<sup>2</sup> and R<sub>sun</sub> differs from file<sub>name</sub>.

Two results are wrong for most writers: 2O is lowered as a whole, and the underscore in file_name becomes a subscript. Technical documents contain many underscores, so the usual solution is to require braces. The export option ^:{} does this for one file:

#+OPTIONS: ^:{}
Water is H_{2}O but file_name stays.
Water is H<sub>2</sub>O but file_name stays.

The option sets two variables at once: org-use-sub-superscripts (the display in Emacs) and org-export-with-sub-superscripts (the export). Both accept t, {} or nil. With {}, a_b is still parsed as a subscript object, but neither displayed nor exported as one. Export options are described in Exporting.

In the buffer, C-c C-x \ (org-toggle-pretty-entities) displays sub- and superscripts raised and lowered, together with the entities described next. To start in that state, set org-pretty-entities to t; org-pretty-entities-include-sub-superscripts (default t) decides whether scripts are included.

Special symbols: entities

Plain text lacks many characters that technical writing needs. Org borrows the LaTeX style: an entity is a backslash followed by a name, such as \alpha for the Greek letter or \to for an arrow. When an entity is directly followed by a letter, end it with {}:

Angles \alpha and \beta; an arrow \to; \pi{}d; 5\nbsp{}km.

Each exporter translates entities into its native form. Org 9.8.13 produces:

Angles &alpha; and &beta;; an arrow &rarr;; &pi;d; 5&nbsp;km.
Angles \(\alpha\) and \(\beta\); an arrow \(\to\); \(\pi\)d; 5~km.

To find an entity, type \ and a few letters, then press M-TAB to complete. M-x org-entities-help lists all built-in entities in a buffer. You can add your own through org-entities-user. Each entry gives the name, the LaTeX code, whether that code needs math mode, and the HTML, ASCII, Latin-1 and UTF-8 forms:

(setq org-entities-user
      '(("check" "\\checkmark" t "&#10003;" "[x]" "[x]" "✓")))

With this setting, Done \check{} exports as Done &#10003; in HTML and Done \(\checkmark\) in LaTeX.

C-c C-x \ displays entities as UTF-8 characters in the buffer; the file keeps the ASCII form. Use #+STARTUP: entitiespretty to turn this on for a single file.

Special strings

A few common character sequences also receive special treatment on export:

InputExported as
--En dash (&ndash; in HTML)
---Em dash (&mdash; in HTML)
...Ellipsis (&hellip; in HTML, \ldots{} in LaTeX)
\-Soft hyphen (&shy; in HTML)

If you need the sequences exported unchanged, add #+OPTIONS: -:nil. With that option, A -- B --- C ... exports to HTML exactly as written.

Embedded LaTeX

Mathematical notation is hard to express in plain text, and LaTeX is the established notation for it. Org therefore recognizes LaTeX directly in the text, with no extra markup. Two forms are recognized:

  • A LaTeX environment: any \begin{...} … \end{...} construct, provided \begin starts a line (only whitespace may precede it).
  • A LaTeX fragment: math inside \(...\) or \[...\], or inside $...$ and $$...$$.
\begin{equation}
x=\sqrt{b}
\end{equation}

If \( b=2 \), then the solution is \[ x=\sqrt{2} \].

Prefer \(...\) for inline math. The single dollar form has strict conditions so that prices are not mistaken for math: the enclosed text may contain at most two line breaks, no whitespace may follow the opening $ or precede the closing one, and the closing $ must be followed by whitespace or punctuation other than a dash. When a literal dollar sign is misread, the entities \dollar and \USD help. For example:

It costs \dollar{}5, and $x$ is math.

exports to HTML as It costs $5, and \(x\) is math.; the second part is then rendered by MathJax in the browser.

Controlling LaTeX on export

The variable org-export-with-latex (default t) decides what happens to LaTeX on export. The LaTeX backend always passes the code through unchanged. For HTML, the default is MathJax, which renders the formulas in the browser. A file can override the default:

Option lineEffect
#+OPTIONS: tex:tProcess fragments in the default way (MathJax for HTML).
#+OPTIONS: tex:nilDo not process LaTeX fragments at all.
#+OPTIONS: tex:verbatimExport the LaTeX source as plain text.

HTML math settings are covered in Exporting.

Previewing formulas in the buffer

With a LaTeX installation and an image converter (by default dvipng, chosen by org-preview-latex-default-process), Org can show typeset formulas as images in the buffer.

C-c C-x C-l (org-latex-preview) previews the fragment at point, or all fragments in the current entry when point is not on one. Prefix arguments widen or reverse the action:

KeyEffect
C-c C-x C-lPreview the fragment at point, or the current entry.
C-u C-c C-x C-lRemove previews in the current entry.
C-u C-u C-c C-x C-lPreview all fragments in the buffer.
C-u C-u C-u C-c C-x C-lRemove all previews in the buffer.

The size of the images is set by the :scale property of org-format-latex-options (default 1.0), and org-format-latex-header defines the LaTeX preamble used to render them. #+STARTUP: latexpreview previews all fragments when the file opens, and nolatexpreview turns this off.

Entering math with CDLaTeX

If you write a lot of math, the third-party package CDLaTeX speeds up typing. Org ships its own minor mode for it, org-cdlatex-mode, which you turn on with M-x org-cdlatex-mode or for all Org buffers with:

(add-hook 'org-mode-hook #'turn-on-org-cdlatex)

The cdlatex package itself must be installed separately (it is available from NonGNU ELPA). Inside a LaTeX fragment, TAB then expands abbreviations such as fr into \frac{}{}, and C-c { inserts an environment template. Do not turn on the original cdlatex-mode in Org buffers; use the Org variant.

Literal examples

Technical notes often contain text that must appear exactly as written: program output, configuration files, code. Org provides several ways to keep such text away from the markup parser.

Example blocks and fixed-width lines

An example block holds literal text, exported in monospace with no markup processing:

#+BEGIN_EXAMPLE
Some output, where *stars* are just stars.
#+END_EXAMPLE

For one or two lines, a colon followed by a space at the start of each line is shorter. Such lines are called fixed-width lines:

: $ make test
: 42 tests passed

Escaping with commas

The contents of a block are protected from markup, but not from structure: a line starting with * would still end the block and start a headline. To prevent this, Org puts a comma before lines that begin with *, ,*, #+ or ,#+. The comma is removed whenever Org reads the block contents, including on export:

#+BEGIN_EXAMPLE
,* not a headline
,#+TITLE: not a keyword
#+END_EXAMPLE

The ASCII exporter prints this block as:

,----
| * not a headline
| #+TITLE: not a keyword
`----

You rarely need to add the commas yourself: when you edit a block with C-c ' (described below), Org adds and removes them automatically.

Source blocks

When the literal text is code, use a source block, which names a language:

#+BEGIN_SRC emacs-lisp
(defun double (n)
  "Return twice N."
  (* 2 n))
#+END_SRC

The language name serves three purposes. In the buffer, Org highlights the code with the major mode for that language. On export, backends can highlight it too. And with Babel, Org can run the code and insert its results. Running code is the subject of Working with Source Code; this section covers only the display features that example and source blocks share.

Line numbers and code references

The -n switch numbers the lines of an example or source block on export. It takes an optional starting number. The +n switch continues the numbering of the previous numbered block, optionally adding an offset. In a source block, switches go after the language name and before any header arguments.

#+BEGIN_SRC python -n 20
print(1)
print(2)
#+END_SRC

#+BEGIN_SRC python +n 10
print(3)
#+END_SRC

The ASCII export shows the numbering: the first block starts at 20, and the second continues from the last line (21) plus 10.

,----
| 20  print(1)
| 21  print(2)
`----

,----
| 31  print(3)
`----

Prose often needs to refer to a specific line of code. Put a label of the form (ref:name) at the end of the line, and link to it with [[(name)]]. The -r switch removes the labels from the exported code; combined with -n, the links then show the line numbers:

#+BEGIN_SRC emacs-lisp -n -r
(save-excursion            (ref:sc)
  (goto-char (point-min)))  (ref:jump)
#+END_SRC

Line [[(sc)]] saves point; line [[(jump)]] moves to the start.
,----
| 1  (save-excursion
| 2    (goto-char (point-min)))
`----

Line 1 saves point; line 2 moves to the start.

Without -n, the links show the label names instead. If the default label format clashes with the language’s syntax, change it with the -l switch, for example -l "((%s))", or globally with org-coderef-label-format (default "(ref:%s)").

Blocks may be indented to line up with a list item. By default Org keeps only the relative indentation of the lines; the -i switch preserves the block’s indentation as written.

Editing in the native mode

C-c ' (org-edit-special) opens the block at point in a separate buffer that uses the language’s major mode, with all its editing commands and completion. Press C-c ' again to write the edited text back into the Org file. On fixed-width lines, the same key opens an Artist mode buffer for drawing ASCII diagrams.

While you edit code this way, org-store-link (see Hyperlinks) asks for a label, inserts it as a (ref:label) at the end of the line, and stores a link to it that you can insert into your prose later.

An image in Org is simply a link to an image file that has no description part:

[[./img/architecture.png]]

Exporters turn such a link into an embedded image. A link with a description, such as [[./img/architecture.png][the diagram]], stays an ordinary link. Links are covered in Hyperlinks.

Showing images in the buffer

Org can display images inside the buffer. Since Org 9.8 this is part of a general link preview system: image links are the type previewed by default, and other link types can define their own previews (Hacking and Extending Org).

KeyCommandEffect
C-c C-x C-vorg-link-previewPreview links in the region if it is active, otherwise the link at point, otherwise the current section.
C-u C-c C-x C-vClear previews at point or in the current entry.
C-u C-u C-c C-x C-vPreview all links in the buffer.
C-u C-u C-u C-c C-x C-vClear all previews in the buffer.
C-c C-x C-M-vorg-link-preview-refreshRefresh all previews in the buffer.

By default only links without a description are previewed. A numeric argument of 1 (C-1 C-c C-x C-v) also previews described links locally, and 11 does the same for the whole buffer. M-x org-link-preview-region and M-x org-link-preview-clear work on the region or the whole buffer.

To show previews whenever a file opens, set org-startup-with-link-previews or add #+STARTUP: linkpreviews (nolinkpreviews disables it). With org-cycle-link-previews-display set, unfolding a subtree also displays its previews.

Size and alignment

Three variables control how previewed images appear:

  • org-image-actual-width (default t) uses the image’s real width, limited by org-image-max-width. A number forces that width in pixels. A number in a list, such as '(300), first looks for a width in an #+ATTR_... keyword above the link and falls back on the number.
  • org-image-max-width (default fill-column) caps the width when none is given explicitly. It also accepts window, a pixel count, or nil for no limit.
  • org-image-align (default left) can also be center or right. It affects only images that stand alone in their paragraph.

A single image can override these settings through attribute keywords. #+ATTR_ORG takes precedence in the buffer, while the exporters read their own keyword:

#+ATTR_HTML: :width 600px :align right
#+ATTR_ORG: :width 300 :align center
[[./img/architecture.png]]

In Emacs, this image is centered, and the HTML export uses the #+ATTR_HTML values. The :width 300 is honored in the buffer only when org-image-actual-width is nil or a list; with the default t, Org keeps the actual width. For a whole subtree, the property ORG-IMAGE-ACTUAL-WIDTH overrides org-image-actual-width.

Captions and names

A caption describes a table, an image or another element. Put a #+CAPTION: keyword directly before the element. A #+NAME: keyword gives the element a label that links can point to:

#+CAPTION: Request flow through the proxy
#+NAME: fig:flow
[[./img/flow.png]]

As [[fig:flow]] shows, every request passes the proxy.

Exported to HTML by Org 9.8.13, the image becomes a numbered figure, and the link resolves to its number (the id value is generated and changes between runs):

<div id="org79f6116" class="figure">
<p><img src="./img/flow.png" alt="flow.png" />
</p>
<p><span class="figure-number">Figure 1: </span>Request flow through the proxy</p>
</div>

<p>
As <a href="#org79f6116">1</a> shows, every request passes the proxy.
</p>

For an image, the link must be alone on its line, so that the paragraph contains nothing else. Tables work the same way, and are numbered as tables:

#+CAPTION[Disk sizes]: Disk sizes of the home server, measured after installation.
#+NAME: tab:sizes
| Disk | Size |
|------+------|
| sda  | 2 TB |

The text in square brackets is an optional short caption, used where space is limited, such as a list of tables in LaTeX. The HTML export of this table begins with <caption class="t-above"><span class="table-number">Table 1:</span> Disk sizes of the home server, measured after installation.</caption>. Other elements, such as source blocks and LaTeX environments, can also take captions; whether a backend uses them depends on the backend.

Horizontal rules

A line containing only dashes, at least 5 of them, is a horizontal rule. ----- exports to HTML as <hr />.

Footnotes

Footnotes let you add a remark without interrupting the main text. A footnote has two parts: a reference in the text and a definition elsewhere.

Org is plain text.[fn:1] It also exports well.[fn:: An inline note.]

[fn:1] Plain text survives changes of tools.

A definition starts with the label in square brackets at column 0, with no indentation. It ends at the next footnote definition, the next headline, or two consecutive empty lines.

Org accepts three forms of reference:

ReferenceMeaning
[fn:NAME]A reference to the definition labeled NAME; the label is a word or a number.
[fn:: text]An anonymous footnote, defined right where it is referenced.
[fn:NAME: text]An inline definition that also has a name, so that other places can refer to it with [fn:NAME].

Several references may point to the same named footnote. On export, Org numbers all footnotes in order of appearance. The HTML backend in 9.8.13 turns the example above into superscript links 1 and 2 and collects the definitions in a <div id="footnotes"> at the end of the page.

Footnote commands

C-c C-x f (org-footnote-action) is the main footnote command:

  • On a reference, it jumps to the definition.
  • On a definition, it jumps back to the first reference.
  • Elsewhere, it creates a new footnote. With the default settings the label is created automatically (see org-footnote-auto-label below).

With a prefix argument, C-c C-x f offers maintenance actions:

KeyAction
sSort the definitions in the order of their references.
rRenumber the simple fn:N footnotes.
SRenumber, then sort.
nRename all footnotes into the sequence fn:1 … fn:n.
dDelete the footnote at point with its definition and references.

C-c C-c on a reference or definition also jumps between the two, and with a prefix offers the same menu. C-c C-o and mouse clicks follow footnotes like links.

Four variables decide where new definitions go and how labels are created:

  • org-footnote-section (default "Footnotes"): the headline under which definitions are collected. When it is nil, each definition goes to the end of its own section.
  • org-footnote-define-inline (default nil): when t, new footnotes are defined inline. The per-file options are #+STARTUP: fninline and nofninline.
  • org-footnote-auto-label (default t): creates numeric labels automatically. Other values prompt for a label or offer one for confirmation; the matching STARTUP options are fnauto, fnprompt, fnconfirm and fnanon.
  • org-footnote-auto-adjust (default nil): renumbers and sorts footnotes after each insertion or deletion. The STARTUP options are fnadjust and nofnadjust.

Escaping Org syntax

Sometimes text looks like Org syntax but should stay plain. Org uses specific escape mechanisms in a few places: commas in blocks (described above), and backslashes in links and macros (Hyperlinks, Exporting). For everything else, the general tool is the zero width space, the invisible character U+200B. Inserted between two characters, it breaks the pattern without visible change.

Insert it with C-x 8 RET followed by either zero width space or 200B, then RET. Two typical uses:

  • To write [[1,2]] as text, put a zero width space between the two opening brackets. Without it, Org reads a link to a target named 1,2, and export fails with Unable to resolve link: "1,2".
  • To keep /usr/bin/ from becoming italic, put a zero width space right after the first slash. Org’s character classes count the zero width space as whitespace, so the opening slash is now followed by whitespace and no longer qualifies. For the same reason, a zero width space placed before the first slash does not help: it acts like an ordinary space there, which is a valid context for an opening marker.

The zero width space is invisible, which is both its strength and its weakness: a reader of the raw file cannot see why the markup is not applied. For paths and identifiers, verbatim markup (=/usr/bin/=) is usually clearer.

Summary

  • Elements are block-level and objects are inline; objects only appear inside text-holding elements.
  • Use *bold*, /italic/, _underline_, +strike+, and prefer =verbatim= or ~code~ for anything technical.
  • Add #+OPTIONS: ^:{} to documents with many underscores.
  • Entities (\alpha, \to, \nbsp) and LaTeX fragments (\(...\)) are translated per backend.
  • Example blocks, fixed-width lines and source blocks keep text literal; C-c ' edits them in their native mode.
  • An image is a link without a description; #+CAPTION and #+NAME turn it into a numbered figure.
  • C-c C-x f manages footnotes, and the zero width space escapes everything else.

Further reading

Hyperlinks

Notes become far more useful once they point at each other and at the material they talk about. An Org file can link to another headline in the same file, to a line in a source file, to a web page, to an email, or to a section of an Info manual, and the syntax is the same for all of them. A single command follows any of these links, and a single pair of commands creates them.

This chapter starts with the link syntax, then covers links inside one document, links to the outside world, and the everyday cycle of storing, inserting and following links. It ends with the tools for heavy users: abbreviations, search options, stable IDs that survive refiling, and link types of your own.

A link in Org is a piece of text that Org recognizes as a reference and makes clickable. The general form uses double square brackets:

[[LINK][DESCRIPTION]]
[[LINK]]

The first part, LINK, says where the link goes. The optional second part, DESCRIPTION, is the text a reader sees. Once both closing brackets are present, Org hides the brackets and the target and shows only the description (or the target itself, when there is no description). The visible text uses the org-link face, which is underlined by default.

Figure 5.1: Everything before ][ tells Org where to go, and only the description is shown once the link is complete.

The link part itself has up to three components:

ComponentExampleMeaning
Typefile:Which handler resolves the link. Without a known type, the link is internal.
Pathprojects.orgWhat the handler should open: a file name, a URL, an ID, and so on.
Search option::#redesignWhere to go inside the target. Valid for file:, attachment: and id: links.

Org also activates plain URLs that appear in running text, such as https://orgmode.org, without any brackets. You can wrap them in angle brackets (<https://orgmode.org>) when the end of the URL would otherwise be ambiguous, for example when it is followed by punctuation or when it contains spaces.

Because the target is hidden, editing a link needs a little care. You can edit the visible text directly. To change the hidden target, put point on the link and press C-c C-l: Org prompts for the link and then for the description, both prefilled with the current values.

If you delete one of the hidden closing brackets (pressing backspace just after the link does this), the link becomes incomplete and Org shows the raw text again. Typing the bracket back hides it once more. To see every link in its literal form, toggle the display with M-x org-toggle-link-display, set org-link-descriptive to nil, or put the startup option in the file:

#+STARTUP: literallinks

Escaping brackets

A link target can contain square brackets, for example a file name like [draft] plan.org. Inside the link part, every [ and ] must be preceded by a backslash, and so must any backslash that comes before a bracket or at the end of the link.

The link commands do this for you; you only need to think about it when you type or paste a raw link. The function org-link-escape produces the escaped form. Evaluated in Emacs 31.1 with Org 9.8.13:

(org-link-escape "file:notes/[draft] plan.org")
(org-link-make-string "file:notes/[draft] plan.org" "Draft plan")
file:notes/\[draft\] plan.org
[[file:notes/\[draft\] plan.org][Draft plan]]

An internal link is a link whose target does not start with a known link type. It refers to something in the current document. Internal links let a long document cross-reference itself, and on export they become anchors and, where it makes sense, numbers.

Org offers four precise kinds of internal target and one fallback:

You writeIt targets
[[#install]]The entry whose CUSTOM_ID property is install.
[[*Troubleshooting]]The headline whose text is Troubleshooting.
[[verify]]A dedicated target <<verify>> anywhere in the file, or else an element named verify with #+NAME:.
[[Installation]]If neither a target nor a name matches, a headline with this text.

A dedicated target is a string in double angle brackets, such as <<verify>>. It marks an exact spot (a list item, a sentence in a paragraph) that has no headline of its own. A named element is an element (a table, a code block, an image) preceded by a #+NAME: keyword.

The following file uses all of these. Note that <<verify>> is invisible in the buffer; Org shows only the text that follows it.

#+TITLE: Release notes
#+OPTIONS: toc:nil num:t author:nil date:nil

* Installation
:PROPERTIES:
:CUSTOM_ID: install
:END:
Follow the steps below.

1. Download the archive.
2. <<verify>>Check the signature.
3. Extract the files.

If step [[verify]] fails, read [[*Troubleshooting]] or the
[[#install][installation notes]].  The supported platforms are listed
in [[platforms]].

#+NAME: platforms
#+CAPTION: Supported platforms
| OS      | Status |
|---------+--------|
| Linux   | tier 1 |
| macOS   | tier 2 |

* Troubleshooting
See [[Installation]] again.

Exporting this file to plain text (C-c C-e t A) shows what happens to links without a description: each one becomes the number of the thing it points to. The target in the second list item becomes “2”, the headlines become their section numbers, and the named table becomes “1” because it is the first table with a caption.

                            _______________

                             RELEASE NOTES
                            _______________


1 Installation
==============

  Follow the steps below.

  1. Download the archive.
  2. Check the signature.
  3. Extract the files.

  If step 2 fails, read 2 or the [installation notes].  The supported
  platforms are listed in 1.

   OS     Status
  ---------------
   Linux  tier 1
   macOS  tier 2
  Table 1: Supported platforms


[installation notes] See section 1


2 Troubleshooting
=================

  See 1 again.

The HTML exporter turns the same links into anchors. A CUSTOM_ID becomes the anchor name directly, which is why it is the best choice for any section you want to link to from outside the document: the generated IDs (like org620893d below) change between exports.

If step <a href="#org620893d">2</a> fails, read <a href="#orgde999d6">2</a> or the
<a href="#install">installation notes</a>.  The supported platforms are listed
in <a href="#org2b3f7a5">1</a>.

Two practical rules follow from this behavior. First, a numbered reference to a named element works only when the element has a #+CAPTION:; without one, there is nothing to number. Second, custom IDs, targets and names must be unique in the document. M-x org-lint reports duplicates, which is worth running before an export.

When you follow a link, Org first checks whether the text before the first colon is a known link type. If it is, the type’s handler takes over. If it is not, Org treats the whole text as a search in the current buffer and tries the possibilities in a fixed order. The order comes from the function org-link-search in ol.el.

flowchart TD
  A["Follow link (C-c C-o)"] --> B{"Known type before the colon?"}
  B -- "yes" --> H["Type handler: file, id, https, ..."]
  B -- "no" --> C{"Starts with a hash sign?"}
  C -- "yes" --> D["Entry with that CUSTOM_ID"]
  C -- "no" --> E{"Wrapped in parentheses or slashes?"}
  E -- "parentheses" --> F["Code reference in a block"]
  E -- "slashes" --> G["Regexp search as a sparse tree"]
  E -- "neither" --> I["Dedicated target, then NAME keyword"]
  I -- "no match" --> J["Headline with the same text"]
  J -- "no match" --> K["Offer to create the headline, or fail"]

Figure 5.2: A link without a known type is a search, and Org tries the most specific kinds of target before it falls back to headline text.

A leading * skips the target and name steps and looks only at headlines. Headline matching ignores TODO keywords, priority cookies, statistics cookies, tags and extra white space, and it is not case-sensitive.

The last step is controlled by org-link-search-must-match-exact-headline. Its default, query-to-create, asks whether to create the missing headline, which is convenient when you write links to sections you plan to add later. Set it to t to get an error instead, or to nil to fall back to a plain text search in the file.

Following an internal link pushes the old position onto Org’s own mark ring. Press C-c & to jump back, and repeat it to go back further. You can push a position yourself with C-c %.

Radio targets

Sometimes you want every occurrence of a term to link to its definition, without writing a link each time. A radio target does this. Write the term in triple angle brackets where it is defined, and Org turns every other occurrence of the same words in normal text into a link to that spot, ignoring case.

#+OPTIONS: toc:nil num:nil
* Glossary
A <<<backlog>>> is the ordered list of work that has not started yet.

* Planning
Each Monday the team reviews the backlog and picks three items.

On export, the definition becomes an anchor and the later mention becomes a link to it:

A <a id="orgd0ac0f7">backlog</a> is the ordered list of work that has not started yet.
...
Each Monday the team reviews the <a href="#orgd0ac0f7">backlog</a> and picks three items.

Org scans the file for radio targets when it opens the file. After you add a new radio target, press C-c C-c on it so that Org activates the new term in the rest of the buffer. Use radio targets sparingly: a common word as a radio target turns half of the document into links.

An external link starts with a type name and a colon, such as https: or file:, with no space after the colon. Org ships with these types:

TypeExampleWhat it does
http, httpshttps://orgmode.org/Opens a web page with browse-url.
filefile:papers/last.pdfVisits a file. A path starting with / or ./ needs no prefix.
attachmentattachment:diagram.pngA file in the entry’s attachment directory. See Capture, Refile, Archive and Attachments.
idid:84b874ac-...The entry with this ID property, in any known file.
doidoi:10.1000/182A document through its DOI handle.
docviewdocview:papers/last.pdf::3A page of a document in DocView mode.
infoinfo:org#External linksA node of an Info manual.
helphelp:org-store-linkThe documentation of a symbol in the *Help* buffer.
shortdocshortdoc:text-propertiesAn Emacs short documentation group.
mailtomailto:someone@example.orgStarts composing a message.
newsnews:comp.emacsA Usenet group.
gnus, rmail, mhegnus:group#idA message or folder in an Emacs mail reader.
bbdbbbdb:R.*StallmanA contact in BBDB, found by regexp.
ircirc:/irc.libera.chat/#emacsAn IRC channel.
shellshell:ls *.orgRuns a shell command.
elispelisp:org-agendaEvaluates a Lisp form or calls a command.

Two of these types run code. Because a link in a file you received from someone else could run any command, Org asks for confirmation before it follows a shell: or elisp: link. The questions come from org-link-shell-confirm-function and org-link-elisp-confirm-function, both yes-or-no-p by default. Keep them that way unless you only ever open your own files.

File links deserve a closer look because they are the type you will use most. The path can be absolute, relative to the current file, or remote through TRAMP:

[[file:~/notes/projects.org][Projects]]
[[./papers/last.pdf]]
[[/ssh:me@build.example.org:logs/today.log]]

When you follow a file link, C-c C-o decides how to open the file from its extension, according to org-file-apps. Text files and directories open in Emacs; other files go to the application your system associates with them. A prefix argument changes the choice: C-u C-c C-o forces Emacs, and C-u C-u C-c C-o avoids Emacs.

On export to HTML, a link to an image without a description becomes an inline image, and a link whose description is an image becomes a clickable image. Displaying images inside the Emacs buffer is a separate feature called link previews; see Markup for Rich Contents.

Typing link targets by hand works for URLs, but for anything inside Emacs it is slow and error-prone. Org’s answer is a three-step cycle: store a link where you are, insert it where you need it, and follow it later.

flowchart LR
  S["Any Emacs buffer"] -- "org-store-link" --> L["List of stored links"]
  L -- "C-c C-l, choose with M-p or M-n" --> O["Org buffer: link text"]
  O -- "C-c C-o or mouse-1" --> T["Target buffer or application"]

Figure 5.3: Storing captures a location as a link, inserting turns a stored link into text, and following resolves that text back into the location.

The command org-store-link creates a link to the current location and keeps it in a list for later. It has no default key because it is useful from every buffer, not only from Org buffers. The manual suggests a global binding:

(global-set-key (kbd "C-c l") #'org-store-link)

What the stored link points to depends on where you are:

Where point isWhat gets stored
On a <<target>> in an Org fileA link to the target.
In a block named with #+NAME:A link to the name.
Elsewhere in an Org entryA link to the headline, or to its CUSTOM_ID if it has one; possibly an id: link (see below).
In any other fileA file: link with a search string built from the current line, or from the active region.
In a mail or news readerA link to the current message.
In an EWW or W3M bufferThe page URL, with the page title as description.
In the agendaA link to the entry on the current line.

In an Org buffer, C-c C-l (org-insert-link) prompts for a link. All links stored in this session are in the prompt’s history, so M-p and M-n (or the up and down arrows) cycle through them. Pressing RET on a stored link inserts it, and Org then asks for a description, offering a default.

The prompt also completes link types with TAB. If you type only a type and press RET, some types offer their own completion: after file you get file name completion, and after id (since Org 9.8) you can choose among known IDs.

C-u C-c C-l jumps straight to inserting a file link. The path is relative when the file lives in or below the current directory, and absolute (using ~ for your home directory where possible) otherwise; C-u C-u C-c C-l forces an absolute path. The variable org-link-file-path-type controls this choice for all file links.

If text is selected when you press C-c C-l, that text becomes the default description, which makes it quick to turn an existing phrase into a link.

A worked example

Suppose projects.org contains this:

* Projects
** Website redesign
:PROPERTIES:
:CUSTOM_ID: redesign
:END:
** Data migration

Running org-store-link on each of the two subheadings, and once more on “Data migration” with org-id-link-to-org-use-id set to t, stores three links. Inserting them with C-c C-l into journal.org in the same directory produces:

[[file:projects.org::#redesign][Website redesign]]
[[file:projects.org::*Data migration][Data migration]]
[[id:84b874ac-34c4-423d-9988-83374cfeb3df][Data migration]]

The first link uses the custom ID because the entry has one. The second falls back to a headline search. The third needed an ID, so Org created one and wrote it into the entry:

** Data migration
:PROPERTIES:
:ID:       84b874ac-34c4-423d-9988-83374cfeb3df
:END:

The three links behave differently when the file changes. The headline link breaks if you rename the headline, and both file: links break if you move the entry to another file. The id: link survives both, which is the subject of the section on stable IDs below.

C-c C-o (org-open-at-point) follows the link at point. A click with mouse-1 or mouse-2 does the same, and mouse-3 opens file links in Emacs and internal links in another window. If you prefer to follow links with RET, set org-return-follows-link to t; inside tables, RET keeps its table meaning.

C-c C-o is context-sensitive beyond links. On a headline that is not on a link, it offers all links in the entry. On tags it builds a tags view, and on a timestamp it opens the agenda for that date. Where the target window appears is controlled by org-link-frame-setup.

To move between links, use C-c C-x C-n (org-next-link) and C-c C-x C-p (org-previous-link). These keys are long; if you navigate links often, bind shorter ones:

(with-eval-after-load 'org
  (define-key org-mode-map (kbd "M-n") #'org-next-link)
  (define-key org-mode-map (kbd "M-p") #'org-previous-link))

The same link syntax works in any Emacs buffer, which is handy in code comments and commit messages. The commands org-insert-link-global and org-open-at-point-global insert and follow Org links outside Org mode. Neither has a default key.

/* The retry policy is described in [[file:~/notes/design.org::#retries]]. */

If you link to the same site many times, typing the full URL becomes tedious and makes the source hard to read. A link abbreviation is a short link word that Org expands into a longer target. You define the expansion once, either for all files in org-link-abbrev-alist or for one file with the #+LINK: keyword:

#+OPTIONS: toc:nil num:nil
#+LINK: gh https://github.com/%s
#+LINK: wiki https://en.wikipedia.org/wiki/%h
#+LINK: man https://man7.org/linux/man-pages/man1/%s.1.html

See [[gh:emacs-mirror/emacs][the Emacs mirror]], [[wiki:Plain text]] and [[man:grep]].

The text after the colon is the tag. In the expansion, %s is replaced with the tag as written and %h with the tag percent-encoded, which is why “Plain text” below becomes Plain%20text. If the expansion has neither, Org appends the tag to the end. Exporting the file to HTML shows the expanded URLs:

See <a href="https://github.com/emacs-mirror/emacs">the Emacs mirror</a>, <a href="https://en.wikipedia.org/wiki/Plain%20text">https://en.wikipedia.org/wiki/Plain%20text</a> and <a href="https://man7.org/linux/man-pages/man1/grep.1.html">https://man7.org/linux/man-pages/man1/grep.1.html</a>.

The global version takes an alist. The link word must start with a letter, and an expansion can also be a function that receives the tag and returns the link, or a string containing %(my-function), which calls my-function with the tag.

(setq org-link-abbrev-alist
      '(("gh" . "https://github.com/%s")
        ("wiki" . "https://en.wikipedia.org/wiki/%h")
        ("ticket" . "https://tracker.example.org/browse/")))

With this setting, [[ticket:OPS-412]] points to https://tracker.example.org/browse/OPS-412. Abbreviations also appear in the completion of C-c C-l, so a team can share one set of link words and use them consistently.

A file link can carry a search option after a double colon, which tells Org where to go inside the file once it is open. The same options work for attachment: and id: links.

[[file:~/code/server.c::255]]
[[file:~/notes/ops.org::Backup schedule]]
[[file:~/notes/ops.org::*Backup schedule]]
[[file:~/notes/ops.org::#backups]]
[[file:~/notes/ops.org::/rsync.*--delete/]]
OptionEffect
255Jump to line 255.
Backup scheduleLook for the target <<Backup schedule>>, then fall back to a text search, exactly as for internal links.
*Backup scheduleIn an Org file, look only at headlines.
#backupsGo to the entry with this CUSTOM_ID.
/rsync.*--delete/Show all matches of the regexp: a sparse tree in Org files, an occur buffer elsewhere.

When org-store-link stores a link to a non-Org file, it writes the words of the current line as a text search, so the link usually finds the line again even after lines are inserted above it. A line number is more precise but breaks as soon as the file changes. An empty file name searches the current file: [[file:::find me]] behaves like [[find me]].

For file formats where a line of text is a poor identifier, you can define your own search. Add functions to org-create-file-search-functions (which build the search string when a link is stored) and org-execute-file-search-functions (which perform the search when it is followed). Org uses this mechanism itself for BibTeX files, where the citation key is the natural identifier; ol-bibtex.el is a working example.

The links you have seen so far depend on where things are: a file name, a headline text, a custom ID in a particular file. In a task system where entries move between files (see Capture, Refile, Archive and Attachments), such links break. The org-id library solves this by giving entries a globally unique identifier in an ID property and keeping a map from IDs to files.

An id: link names only the ID. When you follow it, Org looks up the file in its map, opens it and searches for the property. If the entry has moved, Org rescans its known files, updates the map and tries again.

Creating IDs

You can create IDs explicitly or let org-store-link create them:

  • M-x org-id-get-create adds an ID property to the current entry if it has none, and returns the ID.
  • org-id-link-to-org-use-id decides whether org-store-link uses IDs in Org files.

The second option takes these values:

ValueBehavior of org-store-link
nil (default)Never use IDs; store a headline or custom ID link.
tAlways use an ID, creating one if needed.
create-if-interactiveCreate an ID when you call the command yourself, but only reuse existing IDs when capture stores a link.
create-if-interactive-and-no-custom-idLike the previous value, unless the entry already has a CUSTOM_ID.
use-existingUse an ID if the entry already has one; never create one.

The middle values exist because capture stores a link to the current location every time it runs. With t, every entry you happen to be in when you start a capture would receive an ID. A common setup is therefore:

(require 'org-id)
(setq org-id-link-to-org-use-id 'create-if-interactive-and-no-custom-id)

New IDs are UUIDs by default. org-id-method can switch to other generators, and org-id-prefix adds a fixed prefix.

Where Org keeps the map

Org stores the ID map in org-id-locations-file, by default .org-id-locations in your Emacs directory. The map is updated whenever Org creates an ID or finds one, and written to disk when Emacs exits. If you edit files outside Emacs or synchronize them between machines, the map can become stale. M-x org-id-update-id-locations rebuilds it by scanning your agenda files and their archives, all open Org buffers, and the files already in the map; add other files through org-id-extra-files.

IDs with a search option

Since Org 9.7, an id: link can also carry a search option. This lets you point precisely at a subheading, a target or a named block that has no ID of its own, as long as an ancestor has one. Set org-id-link-consider-parent-id to t and store a link to a child heading:

* Handbook
:PROPERTIES:
:ID:       handbook-2026
:END:
** Onboarding
** Expenses

With point on “Expenses” and org-id-link-to-org-use-id set to t, org-store-link produces:

[[id:handbook-2026::*Expenses][Expenses]]

The link survives moving the whole handbook to another file, because the ID travels with it, while the child headings stay free of extra properties.

When the built-in types and abbreviations are not enough, you can register a new link type. A custom type can define how links are followed, exported, stored, completed and displayed. The entry point is org-link-set-parameters, which associates a type name with a property list of functions; the full list of properties is in the docstring of org-link-parameters.

Abbreviations only rewrite the target. Choose a custom type when the link needs behavior: a different output per export format, a special way to open, or completion of valid values.

The following file defines an rfc: link type that opens an Internet RFC in a browser and exports it as a proper link in each format:

(require 'ol)

(defun my-rfc-url (number)
  (format "https://www.rfc-editor.org/rfc/rfc%s" number))

(defun my-rfc-follow (path _arg)
  (browse-url (my-rfc-url path)))

(defun my-rfc-export (path description backend _info)
  (let ((url (my-rfc-url path))
        (text (or description (format "RFC %s" path))))
    (pcase backend
      ('html (format "<a href=\"%s\">%s</a>" url text))
      ('latex (format "\\href{%s}{%s}" url text))
      ('md (format "[%s](%s)" text url))
      (_ (format "%s <%s>" text url)))))

(org-link-set-parameters "rfc"
                         :follow #'my-rfc-follow
                         :export #'my-rfc-export
                         :face 'org-link
                         :help-echo "Open this RFC in a browser")

The :follow function receives the path (here, the RFC number) and the prefix argument. The :export function receives the path, the description (or nil), the export backend and the export settings, and returns the text to insert. Returning a string for every backend, including a fallback, keeps exports to formats you did not plan for readable.

With this code loaded, the following paragraph:

HTTP semantics are defined in [[rfc:9110]]; caching rules live in
[[rfc:9111][the caching RFC]].

exports to HTML, LaTeX, Markdown and plain text as:

<p>
HTTP semantics are defined in <a href="https://www.rfc-editor.org/rfc/rfc9110">RFC 9110</a>; caching rules live in
<a href="https://www.rfc-editor.org/rfc/rfc9111">the caching RFC</a>.
</p>

HTTP semantics are defined in \href{https://www.rfc-editor.org/rfc/rfc9110}{RFC 9110}; caching rules live in
\href{https://www.rfc-editor.org/rfc/rfc9111}{the caching RFC}.

HTTP semantics are defined in [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110); caching rules live in
[the caching RFC](https://www.rfc-editor.org/rfc/rfc9111).

HTTP semantics are defined in RFC 9110
<https://www.rfc-editor.org/rfc/rfc9110>; caching rules live in the
caching RFC <https://www.rfc-editor.org/rfc/rfc9111>.

Other useful properties are :store, which lets org-store-link create links of your type from a particular kind of buffer, :complete, which provides completion after you type the type name in C-c C-l, and :preview, which shows an inline preview for the link. Writing a store function and packaging a link type as a library are covered in Hacking and Extending Org.

Summary

  • A link is [[LINK][DESCRIPTION]]; the link part has a type, a path and an optional search option.
  • Links without a known type are searches in the current file: #custom-id, *Headline, targets, #+NAME: names, then headline text.
  • Links without a description export as numbers, so internal references stay correct when the document changes.
  • Store with org-store-link, insert with C-c C-l, follow with C-c C-o, return with C-c &.
  • Abbreviations (#+LINK:, org-link-abbrev-alist) shorten repeated URLs.
  • id: links survive renaming and refiling; configure org-id-link-to-org-use-id to create IDs when you want them.
  • org-link-set-parameters defines new link types with their own follow and export behavior.

Further reading

The Table Editor

Plain-text tables are usually painful: every edit misaligns the columns, and fixing them by hand takes longer than the edit itself. Org removes that cost. You type rough rows separated by vertical bars, press TAB, and Org aligns the whole table, widens columns, extends separator lines and moves you to the next field. The file still contains nothing but text, so the table survives version control, diffs and any other editor.

This chapter covers the editor: how a table is written, how to create, navigate and restructure it, how to control column width and alignment, and how to group columns for export. It ends with Orgtbl mode, which brings the same editor to buffers that are not Org files. Formulas and plotting build on all of this and have their own chapter, The Spreadsheet and Plotting.

What makes a table

A table in Org is a group of consecutive lines whose first non-blank character is |. The vertical bar also separates the columns. Each cell between two bars is a field.

A line that starts with |- is a horizontal rule (Org calls it an hline); it separates groups of rows. Rows above the first hline are header rows.

Figure 6.1: A table is ordinary text, and each part (header, hlines, cookie row, formulas) is recognized from the first characters of its line.

The figure shows every part you will meet in this chapter and the next:

PartHow Org recognizes itPurpose
#+NAME: lineA keyword directly above the tableLets links and formulas in other tables refer to this table.
Header rowsRows above the first hlineColumn titles; exported as table headers and left alone by column formulas.
HlineA line starting with |-Separates header from body, or groups of rows.
Cookie rowA row with only <N>, <l>, <c>, <r> or column-group markersDisplay width and alignment; removed on export.
FieldText between two barsOne value. Leading and trailing spaces are not part of the value.
#+TBLFM: lineA keyword directly below the tableThe table’s formulas (see The Spreadsheet and Plotting).

The indentation of the first line sets the indentation of the whole table, so a table can sit inside a list item. A table ends at the first line that does not start with |.

Creating a table

You do not need to draw a table. Type the header with bars, start a separator line, and let Org fill in the rest:

|Language|Released|Typing
|-
|Lisp|1958|dynamic
|Haskell|1990|static
|Python|1991|dynamic

Pressing TAB anywhere in it (or C-c C-c, which aligns without moving) turns this into:

| Language | Released | Typing  |
|----------+----------+---------|
| Lisp     |     1958 | dynamic |
| Haskell  |     1990 | static  |
| Python   |     1991 | dynamic |

Org added the missing closing bars, padded each field, and expanded |- into a full rule. It also decided the alignment of each column: a column that is mostly numbers is right-aligned, any other column is left-aligned. An even faster start is to type only the header line and press C-c RET, which inserts the hline below it and moves to the first body row.

Converting existing data

Data often arrives as CSV, tab-separated text or columns separated by spaces. Select it and press C-c | (org-table-create-or-convert-from-region). Org guesses the separator: tabs if every line has one, commas if every line has one, otherwise white space. Given this CSV:

city,country,population_m
Tokyo,Japan,37.4
Toronto,Canada,6.2
Vancouver,Canada,2.6

C-c | produces:

| city      | country | population_m |
| Tokyo     | Japan   |         37.4 |
| Toronto   | Canada  |          6.2 |
| Vancouver | Canada  |          2.6 |

Add the hline under the first row with C-c - on that row. When the guess is wrong, a prefix argument forces the separator:

PrefixSeparator
C-u C-c |Comma (CSV)
C-u C-u C-c |Tab
C-u C-u C-u C-c |A regular expression you type
C-3 C-c |At least 3 consecutive spaces, or a tab

Without an active region, C-c | creates an empty table after asking for its size. M-x org-table-import reads a file and converts it the same way. Since Org 9.8 you can also paste a table copied from LibreOffice Calc with M-x yank-media.

Moving around and typing

Inside a table, the common motion keys gain table meanings. Every one of them also re-aligns the table, so you rarely need to think about alignment while typing.

KeyCommandEffect
TABorg-table-next-fieldNext field; at the end of the table, a new row.
S-TABorg-table-previous-fieldPrevious field.
RETorg-table-next-rowSame column in the next row; creates a row if needed.
M-aorg-table-beginning-of-fieldBeginning of the field, or the previous field.
M-eorg-table-end-of-fieldEnd of the field, or the next field.
C-c C-corg-table-alignAlign without moving.

Typing inside a field is also special. Characters and DEL do not push the rest of the row to the right; Org takes the space from the padding of the field. And when you type immediately after arriving in a field with TAB, S-TAB or RET, Org clears the field first, so you can overwrite a value without deleting it. If that surprises you more than it helps, set org-table-auto-blank-field to nil.

To edit a field whose content is wider than the column shows, press C-c ` (org-table-edit-field). It opens the field in a small separate window; C-c C-c there writes the result back.

Changing the structure

Rows and columns move with the same M- arrow keys that move headlines and list items, so the muscle memory carries over. Adding S- turns a move into an insertion or deletion.

KeyEffect on a columnKeyEffect on a row
M-LEFTMove column leftM-UPMove row up
M-RIGHTMove column rightM-DOWNMove row down
M-S-LEFTDelete columnM-S-UPDelete row (or hline)
M-S-RIGHTInsert columnM-S-DOWNInsert row above (below with C-u)

S-UP, S-DOWN, S-LEFT and S-RIGHT swap the current field with its neighbor, which is useful for fixing a single misplaced value. C-c - inserts an hline below the current row (above it with C-u), and C-c RET inserts an hline and moves below it.

When you change the structure with these commands, Org also updates absolute references in the table’s formulas so that they keep pointing at the same fields. Editing the text by hand (killing a line with C-k, for example) does not, so prefer the table commands once a table has formulas.

Sorting

C-c ^ (org-table-sort-lines) sorts rows by the column point is in. It sorts the rows between the nearest hlines, so the header and any total row below a rule stay in place. It asks for the sort type:

TypeOrder
a / AAlphabetic, ascending / descending
n / NNumeric, ascending / descending
t / TBy time (timestamp or HH:MM), ascending / descending
f / FBy a key that a function you provide extracts

Starting from this table:

| Service | Region   | Latency (ms) |
|---------+----------+--------------|
| api     | eu-west  |           42 |
| auth    | us-east  |          118 |
| search  | ap-south |           87 |
| billing | eu-west  |           35 |

C-c ^ N in the latency column gives the slowest service first:

| Service | Region   | Latency (ms) |
|---------+----------+--------------|
| auth    | us-east  |          118 |
| search  | ap-south |           87 |
| api     | eu-west  |           42 |
| billing | eu-west  |           35 |

and C-c ^ a in the region column on the original table groups rows by region:

| Service | Region   | Latency (ms) |
|---------+----------+--------------|
| search  | ap-south |           87 |
| api     | eu-west  |           42 |
| billing | eu-west  |           35 |
| auth    | us-east  |          118 |

With an active region, only the rows in the region are sorted. Alphabetic sorting ignores case unless you add a C-u prefix.

Transposing

M-x org-table-transpose-table-at-point swaps rows and columns. Hlines are dropped, because a horizontal rule has no meaning once rows become columns. The latency table above becomes:

| Service      | api     | auth    | search   | billing |
| Region       | eu-west | us-east | ap-south | eu-west |
| Latency (ms) | 42      | 118     | 87       | 35      |

Rectangles and wrapping

Ordinary kill and yank work on lines, which is the wrong shape for tables. Org provides rectangle commands that work on fields and ignore hlines:

KeyCommandEffect
C-c C-x M-worg-table-copy-regionCopy the fields between point and mark.
C-c C-x C-worg-table-cut-regionCopy them and blank the originals.
C-c C-x C-yorg-table-paste-rectanglePaste with the upper left corner at point, growing the table if needed.
M-x org-table-blank-fieldBlank the current field or region.

M-RET (org-table-wrap-region) splits the current field at point and moves the rest into the same column of the next row. With a region inside one column, it rewraps the text of that column across the rows. This is the tool for long text in a table that must stay narrow.

Quick calculations

Two commands help with numbers before you need real formulas:

  • C-c + (org-table-sum) adds the numbers in the current column, or in the selected rectangle. The result appears in the echo area and is put in the kill ring, so C-y inserts it.
  • S-RET (org-table-copy-down) copies the field above into an empty field, or copies the current field into the next row. With org-table-copy-increment (on by default), integers, timestamps and values with a trailing number are incremented, so S-RET on item-1 produces item-2. A C-0 prefix copies without incrementing.

For anything you want to recompute later, use formulas instead; see The Spreadsheet and Plotting.

Column width and alignment

By default Org makes each column as wide as its widest field, and right-aligns a column when most of its fields are numbers. Both choices can be overridden with cookies: short markers in angle brackets placed in a field of their own, anywhere in the column. It is customary to collect them in one row, as in Figure 6.1.

CookieMeaning
<12>This column may be shrunk to 12 characters.
<l>, <c>, <r>Align the column left, centered or right.
<r10>Both: align right, shrink to 10.

A width cookie does not truncate anything in the file. It tells Org how wide the column should look when it is shrunk. Shrinking is a display feature (an overlay), so the full text is still in the file and still exported:

KeyCommandEffect
C-c TABorg-table-toggle-column-widthShrink or expand the current column. Without a width cookie, the column shrinks to one character.
C-u C-c TABorg-table-shrinkShrink every column that has a width cookie, expand the others.
C-u C-u C-c TABorg-table-expandExpand all columns.

A shrunk field shows its full text in a tooltip when you hover over it, and C-h . shows it in the echo area. Editing near a shrunk field expands its column again.

To start every visit with shrunk columns, set org-startup-shrink-all-tables or use #+STARTUP: shrink in the file. Similarly, org-startup-align-all-tables and #+STARTUP: align re-align every table when the file opens, which helps when other tools write the file. If automatic re-alignment slows down very large tables, set org-table-automatic-realign to nil and align with C-c C-c when you choose.

A row that contains only cookies is removed when the document is exported. The exporters do not truncate shrunk columns either; ASCII export, for example, widens them back unless org-ascii-table-widen-columns is nil.

Column groups

Exported tables have no vertical lines by default, which usually looks cleaner. When the columns fall into logical groups, vertical lines between the groups help the reader. You define the groups in a special row whose first field is /. In the other fields, < starts a group, > ends one, and <> makes a column a group of its own.

#+OPTIONS: toc:nil num:nil
| Host  | CPU % | Mem % | Disk % | Notes                              |
|-------+-------+-------+--------+------------------------------------|
| /     |     < |       |      > | <l20>                              |
| web-1 |    34 |    61 |     72 | Serves the public site and the API |
| db-1  |    12 |    40 |     55 | Primary database                   |

The three usage columns form a group, so they appear between two vertical lines. The / row is not exported, and neither is the <l20> cookie in it.

 Host  | CPU %  Mem %  Disk % | Notes
-------+----------------------+------------------------------------
 web-1 |    34     61      72 | Serves the public site and the API
 db-1  |    12     40      55 | Primary database

The HTML exporter expresses the same grouping with three <colgroup> elements, which a style sheet can then draw as borders. It is enough to mark only the start of each group: a < after every place where you want a vertical line produces the same result.

The / marker is one of several marks that Org reads from the first column of a table. The others control recalculation and names and are explained in The Spreadsheet and Plotting.

Exchanging tables with other programs

A table is often the start or the end of a data pipeline. Org can read a table as Lisp data, write it to a file, and translate it into other formats.

Tables as Lisp data

org-table-to-lisp returns the table at point as a list of rows. Each row is a list of strings, and each hline is the symbol hline. For the latency table:

(("Service" "Region" "Latency (ms)") hline ("api" "eu-west" "42") ("auth" "us-east" "118") ("search" "ap-south" "87") ("billing" "eu-west" "35"))

This is the same shape that code blocks receive when a table is passed to them as a variable (see Working with Source Code (Babel)), and the shape that the translators below accept.

Exporting a single table

M-x org-table-export writes the table at point to a file, tab-separated by default (org-table-export-default-format is orgtbl-to-tsv). To fix the file name and format for a table, set the properties TABLE_EXPORT_FILE and TABLE_EXPORT_FORMAT in the entry that contains it:

* Benchmarks
:PROPERTIES:
:TABLE_EXPORT_FILE: latency.csv
:TABLE_EXPORT_FORMAT: orgtbl-to-csv
:END:

Translator functions

The format is a translator: a function that takes the Lisp form of a table and a property list of parameters, and returns a string. Org ships with translators for CSV and TSV (orgtbl-to-csv, orgtbl-to-tsv), for markup languages (orgtbl-to-html, orgtbl-to-latex, orgtbl-to-texinfo), and for Org and Unicode box drawing (orgtbl-to-orgtbl, orgtbl-to-unicode). All of them are built on orgtbl-to-generic, whose docstring lists every parameter. Applied to the latency table, orgtbl-to-csv returns:

Service,Region,Latency (ms)
api,eu-west,42
auth,us-east,118
search,ap-south,87
billing,eu-west,35

and orgtbl-to-latex returns a tabular environment whose column alignment follows the Org table:

\begin{tabular}{llr}
Service & Region & Latency (ms)\\
\hline
api & eu-west & 42\\
auth & us-east & 118\\
search & ap-south & 87\\
billing & eu-west & 35\\
\end{tabular}

A custom format is usually a thin wrapper around orgtbl-to-generic that sets the strings for the start and end of the table and of each line, and the field separator:

(defun my-orgtbl-to-pipe (table params)
  (orgtbl-to-generic
   table
   (org-combine-plists
    '(:tstart "BEGIN" :tend "END" :lstart "> " :sep " | ")
    params)))

Orgtbl mode: the editor everywhere

The table editor is useful well beyond Org files: in emails, commit messages, plain text notes or comments in source code. Orgtbl mode is a minor mode that provides the editor in any major mode. Toggle it with M-x orgtbl-mode, or enable it for a mode through its hook:

(add-hook 'message-mode-hook #'turn-on-orgtbl)

In Orgtbl mode, the table keys (TAB, RET, C-c C-c, the M- arrows and so on) act on tables only when point is in one; elsewhere they keep their usual meaning in the major mode.

Radio tables

Orgtbl mode can also maintain a table in a syntax the major mode understands, such as LaTeX or HTML, while you edit it as an Org table. This is a radio table: you keep the Org table as the source, hidden in a comment, and Orgtbl mode writes a translated copy between two marker lines.

flowchart LR
  S["Org table in a comment, after a SEND line"] -- "C-c C-c" --> T["Translator, e.g. orgtbl-to-latex"]
  T -- "translated text" --> R["Lines between BEGIN RECEIVE and END RECEIVE"]
  R -- "compiled by" --> P["LaTeX, C compiler, ..."]

Figure 6.2: In a radio table, the Org table is the source of truth and the translated copy is regenerated from it on every send.

Here is a LaTeX file with a radio table. The source table sits inside a comment environment (from the comment package), so LaTeX ignores it:

% BEGIN RECEIVE ORGTBL limits
% END RECEIVE ORGTBL limits
\begin{comment}
#+ORGTBL: SEND limits orgtbl-to-latex
| Setting  | Maximum |
|----------+---------|
| retries  |       5 |
| timeout  |      30 |
| backlog  |     128 |
\end{comment}

The #+ORGTBL: SEND line names the table (limits) and the translator. The receiver lines are comments in the host language and carry the same name. With Orgtbl mode on, pressing C-c C-c in the table translates it and replaces everything between the receiver lines:

% BEGIN RECEIVE ORGTBL limits
\begin{tabular}{lr}
Setting & Maximum\\
\hline
retries & 5\\
timeout & 30\\
backlog & 128\\
\end{tabular}
% END RECEIVE ORGTBL limits

Any parameters after the translator name are passed to it as a property list, and they override the translator’s defaults. Two parameters are handled before the translator runs: :skip N drops the first N lines (hlines count), and :skipcols (2 4) drops columns. For LaTeX, :splice t omits the tabular lines so that you can write them yourself.

M-x orgtbl-insert-radio-table inserts a template with the receiver lines and an empty source table for the current major mode. If you cannot hide the source table in a block comment, M-x orgtbl-toggle-comment comments and uncomments its lines.

Summary

  • A table is lines starting with |; |- starts an hline, and rows above the first hline are the header.
  • TAB, RET and C-c C-c align the table; type rough rows and let Org format them.
  • C-c | converts CSV, tab-separated or space-separated text into a table.
  • The M- and M-S- arrow keys move, insert and delete rows and columns; C-c ^ sorts the rows between hlines.
  • Cookies like <10> and <r> control display width and alignment; C-c TAB shrinks and expands columns.
  • A / row defines column groups, which become vertical lines on export.
  • org-table-to-lisp, org-table-export and the orgtbl-to-* translators move tables to and from other programs.
  • Orgtbl mode brings the editor to any buffer, and radio tables keep a translated copy in sync.

Further reading

The Spreadsheet and Plotting

An Org table can compute. You attach formulas to a table, and Org fills in fields from other fields: totals, averages, conversions, durations, text built from other columns. The formulas are stored as plain text under the table, so the computation lives in the same file as the data and the prose that explains it. This makes Org a good fit for the small calculations that appear in notes: a budget in a project plan, the hours in an invoice, the results of a benchmark.

Org’s spreadsheet is not a copy of a conventional spreadsheet program. It has column formulas that apply to a whole column without copying, it references rows relative to horizontal rules, and recalculation happens when you ask for it. This chapter explains how references work, how to write formulas in Calc and in Emacs Lisp, how to name things, how to recalculate and debug, and finally how to plot a table. It assumes you know the table editor from The Table Editor.

Every table in this chapter that shows results was recalculated with Org 9.8.13 in Emacs 31.1, and the output is pasted unchanged.

A first formula

Here is a small budget. The cost of each item is the quantity times the unit price, and the last row holds the total.

| Item     | Qty | Unit price | Cost |
|----------+-----+------------+------|
| Keyboard |   2 |      49.50 |      |
| Monitor  |   1 |     219.00 |      |
| Cables   |   5 |       3.20 |      |
|----------+-----+------------+------|
| Total    |     |            |      |

To fill the Cost column, move to the first Cost field, type =$2*$3;%.2f and press TAB. The leading = tells Org that this is a column formula: one formula for every field of the column. $2 and $3 mean “the second and third field of the same row”, and ;%.2f formats the result with two decimals.

For the total, move to the bottom field of the Cost column, type :=vsum(@I..@II);%.2f and press TAB. The leading := makes it a field formula, valid only for that field. @I..@II is the range between the first and the second horizontal rule, and vsum adds it up.

Each TAB stored a formula and computed only the field you typed it in. Org keeps both formulas in a #+TBLFM: line under the table, separated by ::, so at this point the table reads:

| Item     | Qty | Unit price |  Cost |
|----------+-----+------------+-------|
| Keyboard |   2 |      49.50 | 99.00 |
| Monitor  |   1 |     219.00 |       |
| Cables   |   5 |       3.20 |       |
|----------+-----+------------+-------|
| Total    |     |            | 99.00 |
#+TBLFM: $4=$2*$3;%.2f::@5$4=vsum(@I..@II);%.2f

To compute the rest, recalculate the whole table with C-u C-c * (or press C-c C-c on the #+TBLFM: line):

| Item     | Qty | Unit price |   Cost |
|----------+-----+------------+--------|
| Keyboard |   2 |      49.50 |  99.00 |
| Monitor  |   1 |     219.00 | 219.00 |
| Cables   |   5 |       3.20 |  16.00 |
|----------+-----+------------+--------|
| Total    |     |            | 334.00 |
#+TBLFM: $4=$2*$3;%.2f::@5$4=vsum(@I..@II);%.2f

Org stored the field formula under the absolute address of the field: @5$4 is row 5 (horizontal rules do not count), column 4. The column formula did not overwrite the header, because column formulas skip the rows above the first hline, and it did not overwrite the total, because a field formula takes precedence over a column formula in its field.

If you add rows with the table commands, Org updates @5$4 for you. You can also edit the #+TBLFM: line and write @>$4 (last row, fourth column) instead, which stays correct however the table grows. From now on, the table recalculates when you ask: change a quantity, press C-u C-c *, and the cost and the total follow.

References

A formula refers to other fields by their position. Org’s native notation is @ROW$COLUMN: @ introduces a row and $ a column. Rows are numbered from 1 and count only data lines; horizontal rules are not rows. Spreadsheet-style names like C2 also work as input, but Org shows formulas in its own notation unless you set org-table-use-standard-references to t.

Figure 7.1: Rows are counted without hlines, hlines have their own Roman-numeral names, and a relative reference is measured from the field being computed.

The grid in the figure was produced by Org itself: a range formula wrote each field’s own coordinates into it, using @# and $#, which expand to the row and column of the field being computed.

| A    | B    | C    | D    |
|------+------+------+------|
| @2$1 | @2$2 | @2$3 | @2$4 |
| @3$1 | @3$2 | @3$3 | @3$4 |
|------+------+------+------|
| @4$1 | @4$2 | @4$3 | @4$4 |
#+TBLFM: @2$1..@>$>='(format "@%s$%s" @# $#)

In a live buffer you do not need such a trick: C-c } overlays row and column numbers on the table, and C-c ? shows the coordinates of the field at point.

Absolute and relative references

A reference with an unsigned number is absolute: @2$3 is always the same field, whichever field the formula computes. A reference with a sign is relative: @-1 is the row above the current one, $+2 the column two to the right. If you leave out the row or the column, the current one is used, so $2 alone means “column 2 of this row” and @2 alone means “row 2 of this column”.

ReferenceMeaning
@2$3Row 2, column 3 (spreadsheet name C2).
$5Column 5 in the current row.
@2Row 2 in the current column.
@-1$-3One row up, three columns to the left.
@<, @>The first and the last row.
$<, $>The first and the last column. $>>> is the third column from the right.
@0, $0The current row and column.
@I, @II, …The first, second, … hline.
@-I, @+IThe first hline above, or below, the current row.
@III+2The second data row after the third hline.
@-I$2Column 2 of the row just below the hline above the current row.

The symbolic references @<, @>, $<, $> and the hline references are worth preferring. When you insert or delete rows and columns with the table commands, Org adjusts absolute references in the stored formulas, but a reference anchored to the table edge or to a rule does not need adjusting at all. A total written as vsum(@I..@II) stays correct no matter how many rows you add between the rules.

Hline references make grouped tables easy. In this table, each subtotal sums the rows between the second and the first rule above it:

| Quarter | Region | Sales |
|---------+--------+-------|
| Q1      | North  |   120 |
| Q1      | South  |    95 |
|---------+--------+-------|
| Q1      | Total  |   215 |
|---------+--------+-------|
| Q2      | North  |   140 |
| Q2      | South  |   110 |
|---------+--------+-------|
| Q2      | Total  |   250 |
#+TBLFM: @4$3=vsum(@-II..@-I)::@7$3=vsum(@-II..@-I)

Both formulas are identical apart from their target; the relative hline references find the right rows from each total.

Ranges

Two references joined by .. form a range, a rectangle that includes both corners. If both ends are in the current row, a short form is allowed ($2..$7); otherwise the first end must start with @.

RangeFields
$1..$3The first three fields of the current row.
@2$1..@4$3The 9 fields of the rectangle A2..C4.
$<<<..$>>From the third column to the last but one, in the current row.
@-1$-2..@-1Three fields in the row above, starting two columns to the left.
@I..IIBetween the first and the second hline (short for @I..@II).

A range becomes a vector of values. Calc’s vector functions (vsum, vmean, vmax, vmin, vcount and many others) take it directly. Empty fields are normally left out of the vector, which matters for averages; the section on Calc modes shows how to change that.

Kinds of formulas

The part of a formula before = decides where its result goes. Org knows five kinds:

Left-hand sideKindApplies to
$4=Column formulaEvery field of column 4, except header rows and fields with their own formula.
@>$4=Field formulaOne field.
@1$2..@4$3=Range formulaEvery field in the rectangle.
@3=Row formulaEvery field of row 3.
$total=Named field formulaThe field named total (see “Names and parameters” below).

A column formula must use a column number or $> on its left-hand side, never a column name. Only one formula per column is kept: typing a new =... in a column replaces the previous column formula. To reuse the stored formula in a field, type = alone.

You can enter formulas in three ways. Typing =... or :=... into a field and pressing TAB, RET or C-c C-c stores and applies it. C-c = (org-table-eval-formula) prompts for the column formula of the current column, and C-u C-c = for the field formula of the current field. Range, row and named formulas have no shortcut; write them in the formula editor (see below) or directly in the #+TBLFM: line, and apply them with C-c C-c on that line.

Clearing a field does not remove its formula, because the formula lives in the #+TBLFM: line; the next recalculation fills the field again. To remove a formula, delete it from that line, or give an empty answer to C-c =.

Formulas in Calc

By default, a formula is an algebraic expression for Calc, the calculator that comes with Emacs. Org substitutes the references with field values and passes the result to Calc. Calc handles numbers of any size, fractions, units, dates, vectors and symbolic algebra, so even complicated arithmetic usually needs only one line.

One rule of Calc catches everyone at least once: / binds more loosely than *. In Calc, a/b*c means a/(b*c). Compare the three columns in the middle:

|  a | b | c | a/b*c | (a/b)*c | a*c/b | sqrt(a) |
|----+---+---+-------+---------+-------+---------|
| 12 | 2 | 3 |     2 |      18 |    18 |   3.464 |
| 10 | 4 | 5 |   0.5 |    12.5 |  12.5 |   3.162 |
#+TBLFM: $4=$1/$2*$3::$5=($1/$2)*$3::$6=$1*$3/$2::$7=sqrt($1);%.3f

When a formula divides and multiplies, add the parentheses you mean, or put the multiplication first.

Modes and formats

After the formula, a semicolon introduces a mode string: letters that change how Calc computes and how Org prints the result. They combine freely, as in ;Dp3%.1e.

ModeEffect
p20Compute with 20 digits of precision (default 12).
n3, s3, e2, f4Show the result in normal, scientific, engineering or fixed format with that many digits.
D, RAngles in degrees (default) or radians.
F, SFraction mode, symbolic mode.
uSimplify units in the result.
T, t, UTreat values as durations (see below).
EKeep empty fields in ranges instead of dropping them.
NTreat every field as a number; non-numbers become 0.
LLiteral interpolation, for Lisp formulas only.
%.2fA printf-style format applied to the result.

Org’s defaults, set in org-calc-default-modes, keep the output short: Calc computes with 12 digits but displays at most 8 significant digits. A % format is the most common mode; without it, a result like 576 may appear as 576., which is how Calc writes a floating-point number with no fraction.

Empty fields

Empty fields are where Org differs most from other spreadsheets, and the E and N modes are how you control them. Consider measurements with a missing value:

| Run | t1 | t2 | t3 | Mean | Mean E | Mean EN |
|-----+----+----+----+------+--------+---------|
| a   | 12 | 15 | 18 |   15 |     15 |      15 |
| b   | 10 |    | 14 |   12 |    nan |       8 |
#+TBLFM: $5=vmean($2..$4)::$6=vmean($2..$4);E::$7=vmean($2..$4);EN
  • Without a mode, the empty field is dropped: the mean of 10 and 14 is 12.
  • With E, the empty field is kept as nan (not a number), so the result is nan. This is right when a missing value means the result is unknown.
  • With EN, the empty field counts as 0: the mean of 10, 0 and 14 is 8. Use this only when a blank really means zero.

Calc’s if function lets a formula react to empty input, for example if("$2" == "nan", string(""), $2*1.2);E leaves the result empty when $2 is empty.

Formulas in Emacs Lisp

Calc is excellent with numbers but awkward with text. When a formula needs string manipulation, conditionals or a call to an existing Lisp function, write it in Emacs Lisp. A formula that starts with '( is a Lisp form. Before evaluating it, Org replaces each reference with the field content.

How the content is inserted depends on the mode:

ModeA reference becomesUse for
(none)A Lisp string, "Ada"Text processing.
NA Lisp number, 12; non-numbers become 0Arithmetic.
LThe raw text, unquotedMixing strings and numbers; quote string references yourself as "$1".

The following table derives three columns from names. The first two formulas work on strings; the third uses L and writes the quotes itself.

| First | Last     | Login     | Chars | Initials |
|-------+----------+-----------+-------+----------|
| Ada   | Lovelace | alovelace |    11 | A.L.     |
| Alan  | Turing   | aturing   |    10 | A.T.     |
#+TBLFM: $3='(downcase (concat (substring $1 0 1) $2))::$4='(+ (length $1) (length $2))::$5='(concat (substring "$1" 0 1) "." (substring "$2" 0 1) ".");L

The default string interpolation is a common source of errors when you do arithmetic. In the first table below, (+ $1 $2) becomes (+ "1" "2"), which fails, and Org writes #ERROR into the field. With ;N the references become numbers, and the text foo becomes 0:

| a | b   | a+b    |
|---+-----+--------|
| 1 | 2   | #ERROR |
| 3 | foo | #ERROR |
#+TBLFM: $3='(+ $1 $2)

| a | b   | a+b |
|---+-----+-----|
| 1 | 2   |   3 |
| 3 | foo |   3 |
#+TBLFM: $3='(+ $1 $2);N

A range in a Lisp formula becomes a sequence of values separated by spaces, so you can wrap it in a list: '(apply #'+ '($1..$4));N adds four columns. Because a semicolon starts the mode string, a formula that contains a semicolon in a string needs an extra ; at the end, as in '(concat $1 ";");, to tell Org that the earlier semicolons belong to the formula.

Durations and times

Times of day and durations in the form HH:MM or HH:MM:SS are text to Calc. The modes T, U and t turn them into numbers of seconds for the computation and format the result:

  • T prints HH:MM:SS.
  • U prints HH:MM.
  • t prints a decimal number in the unit of org-table-duration-custom-format (hours by default).
| Task     | Start |   End |    Spent | Spent U | Hours |
|----------+-------+-------+----------+---------+-------|
| Review   | 09:15 | 10:40 | 01:25:00 |   01:25 |  1.42 |
| Meeting  | 13:00 | 14:30 | 01:30:00 |   01:30 |  1.50 |
| Write-up | 15:05 | 17:50 | 02:45:00 |   02:45 |  2.75 |
|----------+-------+-------+----------+---------+-------|
| Total    |       |       | 05:40:00 |   05:40 |  5.67 |
#+TBLFM: $4=$3-$2;T::$5=$3-$2;U::$6=$3-$2;t::@>$4=vsum(@I..@II);T::@>$5=vsum(@I..@II);U::@>$6=$4;t

The total of the Hours column is computed from the duration in the same row ($4 with t), not by adding the rounded decimal values, which avoids rounding errors. Negative durations work too, and plain integers count as seconds. Whether hours are padded to two digits is controlled by org-table-duration-hour-zero-padding. For timing work you actually do, Org’s clock is usually the better tool; see Clocking, Effort and Timers.

Names, constants and parameters

Formulas full of $4 and @II are compact but hard to read a month later. Org lets you give names to values at three levels.

Constants for a file or for all files

A #+CONSTANTS: line defines names for the whole file, and org-table-formula-constants defines them for every file. A property of the current entry (or of an ancestor) is available as $PROP_Name. All of these are written with a $ in formulas:

#+CONSTANTS: vat=0.19 fee=2.5

* Shop order
:PROPERTIES:
:Discount: 0.1
:END:

| Item |  Net | Gross |  Paid |
|------+------+-------+-------|
| Pen  | 4.00 |  4.76 |  6.78 |
| Pad  | 9.50 | 11.30 | 12.67 |
#+TBLFM: $3=$2*(1+$vat);%.2f::$4=$3*(1-$PROP_Discount)+$fee;%.2f

Taking the discount from a property means that the same table can be copied into another entry with a different Discount value and give the right result there.

Names inside a table

For names that belong to one table, reserve the first column for marking characters. A mark in the first field of a row gives the row a special role:

MarkMeaning of the row
!Its fields name the columns, so $Tot can stand for $6.
^Its fields name the fields in the row above.
_Its fields name the fields in the row below.
$Its fields define parameters such as max=50, used as $max.
#Recalculate this row automatically on TAB, RET and S-TAB, and with C-u C-c *.
*Recalculate this row with C-u C-c *, but not automatically.
/Do not export this row (useful for cookie and column-group rows).

C-# (org-table-rotate-recalc-marks) cycles the mark of the current row, or of all rows in the region. Here is an estimate that uses column names, a parameter and two named fields:

|---+---------+-------+------+------+---------|
|   | Item    | Hours | Rate |  Net |   Gross |
| ! |         |     h |    r |  net |   gross |
|---+---------+-------+------+------+---------|
| # | Design  |     6 |   80 |  480 |  576.00 |
| # | Build   |    14 |   70 |  980 | 1176.00 |
| # | Test    |     5 |   60 |  300 |  360.00 |
|---+---------+-------+------+------+---------|
| # | Total   |       |      | 1760 | 2112.00 |
| ^ |         |       |      | tnet |  tgross |
| $ | vat=0.2 |       |      |      |         |
|---+---------+-------+------+------+---------|
#+TBLFM: $5=$h*$r::$6=$net*(1+$vat);%.2f::$tnet=vsum(@II..@III)::$tgross=vsum(@II..@III);%.2f

The formulas now read almost like prose: net is hours times rate, gross is net plus VAT, and the two totals are named tnet and tgross. Note that the column formulas still use $5 and $6 on the left-hand side; column names are allowed only on the right, while a named field such as $tnet may also appear on the left.

In a table with marks, recalculation works differently. C-u C-c * recomputes only rows marked # or * and fields that have their own formula, and column formulas are not applied in rows whose first field is empty. Rows marked # also recompute as you move through them with TAB or RET, which gives semi-automatic recalculation while you type. If that makes editing slow in a large table, use * instead.

Using other tables

A formula can read from another table with remote(NAME,REF). NAME is the #+NAME: of a table in the same file, or the ID of an entry, possibly in another file, in which case the first table in that entry is used. REF is an absolute reference or range inside that table.

#+NAME: hours
| Week | Hours |
|------+-------|
|   46 |    32 |
|   47 |    41 |
|------+-------|
|  Sum |    73 |
#+TBLFM: @>$2=vsum(@I..@II)

| Rate | Weeks 46-47 | Invoice |
|------+-------------+---------|
|   65 |          73 |    4745 |
#+TBLFM: $2=remote(hours,@>$2)::$3=$1*$2

This lets you keep raw data in one place and build summaries elsewhere in the file. Recalculate the source table first, or use M-x org-table-iterate-buffer-tables, which recalculates all tables in the buffer until the values stop changing.

Lookups

To look up a value by key, combine remote with one of Org’s lookup functions in a Lisp formula. (org-lookup-first VAL S-LIST R-LIST) finds the first element of S-LIST that equals VAL and returns the element at the same position in R-LIST. org-lookup-last returns the last match, and org-lookup-all returns every match as a list, for use inside a larger Lisp expression. An optional fourth argument replaces equal as the comparison.

#+NAME: rates
| Currency | Per EUR |
|----------+---------|
| USD      |    1.08 |
| JPY      |  162.40 |
| CAD      |    1.49 |

| Item   | EUR | Currency |  Rate |    Local |
|--------+-----+----------+-------+----------|
| Hotel  | 240 | JPY      | 162.4 | 38976.00 |
| Train  |  85 | CAD      |  1.49 |   126.65 |
| Dinner |  60 | USD      |  1.08 |    64.80 |
#+TBLFM: $4='(org-lookup-first '$3 '(remote(rates,@2$1..@>$1)) '(remote(rates,@2$2..@>$2)));L::$5=$2*$4;%.2f

The L mode inserts the currency codes and rates without quotes, so the Lisp form compares symbols ('JPY against the list (USD JPY CAD)) and returns a number. When the ranges in a lookup may contain empty fields, add E so that the two lists stay aligned.

Editing and debugging formulas

Once a table has several formulas, the #+TBLFM: line becomes hard to read. Org offers several ways to see and edit formulas in context.

KeyCommandEffect
C-c =org-table-eval-formulaEdit the column formula of the current column in the minibuffer.
C-u C-c =org-table-eval-formulaEdit the field formula of the current field.
C-u C-u C-c =org-table-eval-formulaPut the active formula into the field, to edit it in place.
C-c ?org-table-field-infoShow the coordinates of the field, or highlight the fields that the reference at point refers to.
C-c }org-table-toggle-coordinate-overlaysShow or hide row and column numbers.
C-c {org-table-toggle-formula-debuggerTurn the formula debugger on or off.
C-c 'org-table-edit-formulasEdit all formulas of the table in a separate buffer.

The formula editor opened by C-c ' is the most comfortable of these. It lists one formula per line and highlights the fields that the reference at point refers to. Inside it:

KeyEffect
C-c C-c or C-x C-sStore the formulas and return; with C-u, also recalculate the table.
C-c C-qReturn without storing.
C-c C-rToggle between @3$2 notation and B3 notation.
S-UP, S-DOWN, S-LEFT, S-RIGHTShift the reference at point to the neighboring field.
TABPretty-print or indent a Lisp formula.
M-UP, M-DOWNScroll the window that shows the table.

When a formula fails, the field shows #ERROR. To see why, turn on the debugger with C-c { and recompute a single field, for example with C-u C-u C-c = RET. Org then shows each step: the formula after reference substitution, the expression sent to Calc or Lisp, and the result.

Several formula lines

A table may have more than one #+TBLFM: line. Pressing C-c C-c on one of them applies that line only, which lets you switch between alternative calculations. In this table, C-c C-c on the second line computed the reduced rate:

| Net |   Tax |
|-----+-------|
| 100 |  7.00 |
| 250 | 17.50 |
#+TBLFM: $2=$1*0.19;%.2f
#+TBLFM: $2=$1*0.07;%.2f

A normal recalculation (C-u C-c *) always uses the first line, and gives back the standard rate:

| Net |   Tax |
|-----+-------|
| 100 | 19.00 |
| 250 | 47.50 |
#+TBLFM: $2=$1*0.19;%.2f
#+TBLFM: $2=$1*0.07;%.2f

Recalculation

Org never recalculates on its own, except in rows marked #. This keeps editing fast and the file stable, but it means you must recalculate after changing input values.

KeyEffect
C-c *Recalculate the current row.
C-u C-c * or C-u C-c C-cRecalculate the whole table.
C-u C-u C-c * or C-u C-u C-c C-cRecalculate the table repeatedly until it stops changing (org-table-iterate).
C-c C-c on a #+TBLFM: lineApply that formula line to the whole table.
M-x org-table-recalculate-buffer-tablesRecalculate every table in the buffer.
M-x org-table-iterate-buffer-tablesIterate every table in the buffer until all are stable.

To know when one pass is enough, you need to know the order in which Org evaluates formulas. A full recalculation goes through the table once, in a fixed order:

flowchart TD
  A["C-u C-c * : recalculate table"] --> B["Read the TBLFM line, expand names"]
  B --> C["Column formulas: each data row, top to bottom, columns left to right"]
  C -- "skip fields that have a field formula" --> D["Field and range formulas"]
  D --> E["Align the table"]
  E --> F{"Iterating, and the table changed?"}
  F -- "yes, at most 10 passes" --> B
  F -- "no" --> G["Done"]

Figure 7.2: Column formulas run before field formulas, so a column formula that reads a field computed by a field formula sees the old value until the next pass.

One pass is enough when every formula reads only fields that are input or that were computed earlier in this order. A running balance breaks that rule. In the next table, the column formula adds each amount to the balance in the row above, and a field formula seeds the first balance:

|       Date | Amount | Balance |
|------------+--------+---------|
| 2026-11-01 |   1200 |         |
| 2026-11-03 |   -350 |         |
| 2026-11-10 |    -80 |         |
| 2026-11-15 |    400 |         |
#+TBLFM: $3=@-1$3+$2::@2$3=$2

A single C-u C-c * gives a wrong result, because the column formula for the second row ran before the field formula had filled the first balance:

|       Date | Amount | Balance |
|------------+--------+---------|
| 2026-11-01 |   1200 |    1200 |
| 2026-11-03 |   -350 |    -350 |
| 2026-11-10 |    -80 |    -430 |
| 2026-11-15 |    400 |     -30 |
#+TBLFM: $3=@-1$3+$2::@2$3=$2

C-u C-u C-c * repeats the calculation until the table no longer changes, and gives the correct balances:

|       Date | Amount | Balance |
|------------+--------+---------|
| 2026-11-01 |   1200 |    1200 |
| 2026-11-03 |   -350 |     850 |
| 2026-11-10 |    -80 |     770 |
| 2026-11-15 |    400 |    1170 |
#+TBLFM: $3=@-1$3+$2::@2$3=$2

When a table needs iteration, it is often clearer to remove the dependency instead. Here, a column formula that sums all amounts from the first rule down to the current row computes each balance directly, and one pass is enough:

|       Date | Amount | Balance |
|------------+--------+---------|
| 2026-11-01 |   1200 |    1200 |
| 2026-11-03 |   -350 |     850 |
| 2026-11-10 |    -80 |     770 |
| 2026-11-15 |    400 |    1170 |
#+TBLFM: $3=vsum(@I$2..@0$2)

Plotting

Numbers in a table often make more sense as a picture. Org can draw a table in two ways: through Gnuplot, or as ASCII bars inside the table itself.

Graphs with Gnuplot

C-c " g (org-plot/gnuplot) plots the table at point. It needs the Gnuplot program and the gnuplot Emacs package (gnuplot-mode). Options go in a #+PLOT: line directly above the table:

#+PLOT: title:"Build time per release" ind:1 deps:(2 3) type:2d with:linespoints set:"yrange [0:]" file:"build-time.png"
| Release | Debug (s) | Release (s) |
|---------+-----------+-------------|
|     1.0 |       212 |         340 |
|     1.1 |       198 |         322 |
|     1.2 |       175 |         301 |
|     1.3 |       160 |         288 |

Org writes the data rows to a temporary file, separated by tabs, and generates a Gnuplot script from the options. The column headers become the series titles. For the table above, Org 9.8.13 generated this script (file names are shortened here):

reset
set term png
set output '.../build-time.png'

set title 'Build time per release'
set yrange [0:]
set datafile separator "\t"
plot '/tmp/org-plot...' using 1:2 with linespoints title 'Debug (s)',\
    '/tmp/org-plot...' using 1:3 with linespoints title 'Release (s)'

Seeing the script explains the options: ind chooses the x column, deps the y columns, with the Gnuplot style, and set passes a raw Gnuplot command. The most useful options are:

OptionMeaning
titleTitle of the plot.
indColumn used for the x axis.
timeindLike ind, for a column of timestamps.
depsColumns to plot, as a list such as (2 3); default: all others.
type2d, 3d, grid or radar; more types can be added through org-plot/preset-plot-types.
withGnuplot style for each series: lines, points, boxes, histograms, …
fileWrite the plot to this file instead of a window.
labelsSeries names, replacing the column headers.
set, lineExtra Gnuplot commands; may be repeated.
transposePlot rows as series instead of columns.
min, max, ticksAxis limits and tick count, used by plot types such as radar.
timefmtHow Gnuplot should parse timestamps.
scriptUse your own Gnuplot script; $datafile in it is replaced by the data file name.

With file:, the plot is a file that you can link from the document and show inline (see Markup for Rich Contents), which turns the table and its chart into one self-contained report.

ASCII bar plots

For a quick look without any external program, C-c " a (orgtbl-ascii-plot) adds a column of text bars next to the column at point. The bars are an ordinary column formula that calls orgtbl-ascii-draw, so they update with the table:

| Month | Commits |              |
|-------+---------+--------------|
| Jan   |      42 | WWWWWWWW     |
| Feb   |      17 | WWW:         |
| Mar   |      63 | WWWWWWWWWWWW |
| Apr   |       8 | W!           |
#+TBLFM: $3='(orgtbl-ascii-draw $2 0 63 12)

The arguments of orgtbl-ascii-draw are the value, the value that gives an empty bar, the value that fills the bar, and the width of the bar in characters (12 by default). Values outside the range are shown as too small or too large. The last character of a bar is finer than a whole W, so short bars still show differences.

Summary

  • Type =formula in a field for a column formula and :=formula for a field formula; both are stored in #+TBLFM:.
  • @ROW$COLUMN addresses fields; rows count data lines only, @I and @-I address hlines, and @<, @>, $<, $> stay valid when the table grows.
  • Calc formulas handle numbers, vectors and units; remember that / binds more loosely than *.
  • Modes after ; set precision, formats, empty-field handling (E, N) and durations (T, U, t).
  • Lisp formulas start with '(; references are strings unless you use N or L.
  • #+CONSTANTS:, $PROP_ properties and marked rows (!, ^, _, $) give names to values.
  • remote() and org-lookup-first read from other tables.
  • Recalculate with C-u C-c *; iterate with C-u C-u C-c * when formulas depend on later results; debug with C-c ', C-c ? and C-c {.
  • C-c " g plots with Gnuplot from a #+PLOT: line, and C-c " a adds ASCII bars.

Further reading

TODO Items

Most task managers keep tasks in one place and notes in another. Org takes the opposite approach: a task is simply a headline that carries a keyword, and it lives in the same outline as the notes, meeting minutes and code snippets it came from. When you write “ask the vendor about the license” in the middle of a project log, you can turn that line into a task on the spot, and the surrounding text stays attached to it as context.

The obvious cost of this design is that tasks end up scattered across many headlines and many files. Org pays that cost back with commands that collect them again: sparse trees inside one buffer, and the agenda across all your files (see Agenda Views). This chapter covers the task side of that bargain: how a headline becomes a task, how tasks move through states, how Org records that movement, and how you split work into smaller pieces and measure progress on them.

The essential idea: a keyword at the start of a headline

A TODO item (or task) is a headline whose title begins with a TODO keyword. Out of the box Org knows 2 keywords: TODO, which means that something still needs to be done, and DONE, which means that it is finished.

* Infrastructure
** TODO Renew the TLS certificate
** DONE Rotate the database password
** Notes from the security review

Only the second and third headlines are tasks. The fourth is an ordinary headline, and it remains one until you give it a keyword. Nothing else about a task is special: it can have body text, children, tags, properties and timestamps like any other entry (see Document Structure).

Changing the state

You rarely type keywords by hand. The central command is C-c C-t (org-todo), which rotates the current headline through its states. With the default keywords the rotation has three steps:

stateDiagram-v2
    direction LR
    none: no keyword
    none --> TODO: C-c C-t
    TODO --> DONE: C-c C-t
    DONE --> none: C-c C-t

Figure 8.1: With the default setup, C-c C-t cycles a headline from plain text to TODO, to DONE, and back to plain text.

Several other commands change states as well:

KeyCommandEffect
C-c C-torg-todoRotate to the next state, or open the fast selection menu when keywords have selection keys.
S-RIGHT, S-LEFTMove to the next or previous state, like cycling in either direction.
S-M-RETorg-insert-todo-headingInsert a new task below the current entry, with the same keyword (or the first keyword when the current one is done or missing).
C-c / torg-show-todo-treeFold the buffer and show only tasks that are not done, together with their parents.
t in the agendaChange the state of the task on the current agenda line.

The C-c / t command builds a sparse tree: a view of the buffer where everything is folded except the matching headlines and the headlines above them. It answers the question “what is still open in this file?” without losing the structure of the file. With a prefix (C-u C-c / t, or C-c / T) it asks for a keyword, and you can name several at once, separated by |, for example WAIT|NEXT.

For a list of open tasks across all your files, press t in the agenda dispatcher (M-x org-agenda t, the command org-todo-list). That list belongs to the agenda, which has its own chapter.

Designing your own keywords

A shopping list needs only 2 states, but real work often passes through intermediate stages: a task waits for someone else, a bug is reproduced but not yet fixed, a draft is out for review. Org lets you define as many keywords as you need in the variable org-todo-keywords.

Keywords as workflow states

The most common use is a sequence: an ordered list of states that a task moves through. A vertical bar divides the list into two groups. Keywords before the bar are not-done states (the task still needs action); keywords after it are done states (no further action is needed).

(setq org-todo-keywords
      '((sequence "TODO" "NEXT" "WAIT" "|" "DONE" "CANCELED")))

With this setting, C-c C-t moves a headline through TODO, NEXT, WAIT, DONE and CANCELED, and then back to no keyword. If you leave out the bar, Org treats the last keyword as the only done state.

The distinction between done and not-done matters more than the order. The agenda hides done tasks from the TODO list, the CLOSED timestamp is written only when a task enters a done state, and statistics cookies (described later) count done children. CANCELED sits after the bar for this reason: a canceled task needs no action, so Org should treat it as finished even though it was never completed.

To jump straight to a specific state, give C-c C-t a numeric prefix: with the setting above, C-3 C-c C-t sets WAIT, the third keyword. Changes to org-todo-keywords take effect only when Org mode restarts in a buffer, so run M-x org-mode (or reopen the file) after you edit your configuration.

Keywords as types

Org also supports a second interpretation, in which the keywords before the bar name kinds of tasks rather than stages. The classic example is assigning work to people:

(setq org-todo-keywords '((type "Ana" "Ben" "Chen" "|" "DONE")))

The type symbol changes how C-c C-t behaves. Pressed several times in a row, it still steps through all the names so that you can pick the right person. Pressed later, on a headline that already carries a name, it jumps straight to DONE. In a batch test, two presses on a plain headline gave Ben, and a third press in a separate command gave DONE:

* Ben Review the budget
* DONE Review the budget

The manual itself recommends tags over type keywords for this purpose, since a headline can carry many tags but only one keyword. Treat this feature as a way to read older files rather than as a design to copy (see Tags, Properties and Column View).

Several sequences side by side

Different kinds of work deserve different workflows. A bug goes through REPORT, BUG and KNOWNCAUSE before it is FIXED, while an errand only needs TODO and DONE. You can define several sequences at once:

(setq org-todo-keywords
      '((sequence "TODO" "|" "DONE")
        (sequence "REPORT" "BUG" "KNOWNCAUSE" "|" "FIXED")
        (sequence "|" "CANCELED")))

Each keyword should appear in only one sequence, because Org uses the current keyword to decide which sequence a headline belongs to. Plain C-c C-t then stays inside that sequence. To switch to another sequence, use C-u C-u C-c C-t (or C-S-RIGHT and C-S-LEFT). S-RIGHT and S-LEFT ignore the boundaries and walk through every keyword of every sequence.

The following trace comes from a batch run with fast selection turned off (org-use-fast-todo-selection set to nil), starting from * TODO Crash on startup. Each line shows the prefix passed to org-todo and the resulting headline:

nil    -> * DONE Crash on startup
nil    -> * Crash on startup
nil    -> * TODO Crash on startup
(16)   -> * REPORT Crash on startup
nil    -> * BUG Crash on startup
nil    -> * KNOWNCAUSE Crash on startup
nil    -> * FIXED Crash on startup
nil    -> * Crash on startup
(16)   -> * CANCELED Crash on startup

The (16) entries are the double prefix, C-u C-u, which moves to the first keyword of the next sequence.

Fast access with selection keys

Cycling becomes tedious once you have more than 3 or 4 keywords. Instead, append a selection character in parentheses to each keyword:

(setq org-todo-keywords
      '((sequence "TODO(t)" "NEXT(n)" "WAIT(w)" "|" "DONE(d)" "CANCELED(c)")))

When at least one keyword has a key, C-c C-t no longer cycles. It opens a small menu, and a single key sets the state directly: C-c C-t w marks the task as waiting, and C-c C-t SPC removes the keyword. This behavior is controlled by org-use-fast-todo-selection, whose default value auto means “use the menu whenever keys are defined”. The characters @, ! and ^ cannot serve as selection keys because they have other meanings inside the parentheses, as the logging section below explains.

Per-file keywords

The variable sets keywords for every file. A single file can override it with in-buffer settings, which are lines that start with #+ (see Getting Started):

#+TODO: TODO(t) | DONE(d)
#+TODO: REPORT(r) BUG(b) KNOWNCAUSE(k) | FIXED(f)
#+TODO: | CANCELED(c)

Each #+TODO: line defines one sequence. #+SEQ_TODO: is a synonym, and #+TYP_TODO: defines a type set. Org reads these lines when it starts in a buffer, so after editing one, press C-c C-c with point on the line to restart Org in that buffer.

Per-file keywords are useful when a file has a purpose of its own: a bug tracker, a reading list (TOREAD, READING, READ) or a hiring pipeline. Keep the keywords for personal tasks in org-todo-keywords, and let specialized files declare their own.

Faces

Org draws not-done keywords with the face org-todo and done keywords with org-done. With many keywords, color helps you scan a list. The variable org-todo-keyword-faces maps keywords to faces; a string value is read as a color name:

(setq org-todo-keyword-faces
      '(("WAIT" . "orange")
        ("CANCELED" . (:foreground "gray" :weight bold))))

Whether a color string sets the foreground or the background depends on org-faces-easy-properties.

Triggering tag changes from state changes

Sometimes a state should also be visible as a tag, for example so that an agenda filter can find all waiting tasks. The variable org-todo-state-tags-triggers adds or removes tags when a task enters a state. Each entry names a state (a keyword string, "" for no keyword, or the symbols todo and done for any not-done or done state) and a list of (TAG . FLAG) pairs, where a non-nil flag adds the tag and nil removes it.

(setq org-todo-keywords '((sequence "TODO" "WAIT" "|" "DONE"))
      org-todo-state-tags-triggers
      '(("WAIT" ("waiting" . t))
        ("TODO" ("waiting"))
        (done ("waiting"))))

Changing a task to WAIT and then to DONE produced these headlines in a batch run:

* WAIT Get the signed contract back                                 :waiting:
* DONE Get the signed contract back

Be careful with the symbol todo. WAIT is itself a not-done state, so a rule (todo ("waiting")) would fire on the same change and remove the tag that the WAIT rule had just added. The function org-todo-trigger-tag-changes applies the rules for the exact keyword first and the rules for todo or done after them, so the later rule wins.

Dependencies between tasks

An outline already expresses that some tasks are parts of others. Org can turn that structure into a rule: a parent cannot be finished while its children are still open. Set org-enforce-todo-dependencies to t to enable the rule.

A second rule handles sequences of steps. If a headline has the property ORDERED set to t, each child task is blocked until all the siblings above it are done. Properties live in a PROPERTIES drawer under the headline (see Tags, Properties and Column View).

* TODO Publish the paper
** DONE Write the draft
** TODO Get approval from co-authors

* Migrate the database
:PROPERTIES:
:ORDERED:  t
:END:
** TODO Take a backup
** TODO Run the migration script

With dependencies enabled, trying to mark the first or the last headline as DONE leaves the file unchanged and prints a message instead. These are the two messages from a batch run:

TODO state change from TODO to DONE blocked (by "TODO Get approval from co-authors")
TODO state change from TODO to DONE blocked (by "** TODO Take a backup")

A blocked task also reports t for the special property BLOCKED, which you can use in searches and column view.

Several tools adjust or bypass the rules:

  • C-c C-x o (org-toggle-ordered-property) adds or removes the ORDERED property. Org uses a property rather than a tag here because the setting should apply to one entry only, while tags are inherited. If you want to see the setting at a glance anyway, org-track-ordered-property-with-tag mirrors it as a tag.
  • A NOBLOCKING property with value t exempts an entry from blocking.
  • C-u C-u C-u C-c C-t changes the state regardless of any blocking.
  • org-enforce-todo-checkbox-dependencies extends the rule to checkboxes: an entry with unchecked boxes cannot become done.
  • In the agenda, org-agenda-dim-blocked-tasks (on by default) shows blocked tasks in a dimmed face.

Dependencies only follow the outline. Org itself has no syntax for “task A in one file waits for task B in another”; the manual points to the org-depend.el module in the separate org-contrib repository for that.

Recording progress

A task list tells you what is open. A log tells you what happened: when a task was finished, how long it sat in WAIT, why it was canceled. Org can write that log into the file as you change states, so that the history stays next to the task.

Recording when a task was closed

The simplest log is a single timestamp that marks completion. Set org-log-done to time:

(setq org-log-done 'time)

Now, whenever a task moves from a not-done state to a done state, Org adds a CLOSED line right below the headline. Here is a task after one press of C-c C-t in a batch run:

* DONE Write the release notes
CLOSED: [2026-11-19 Thu 04:44]

The brackets mark an inactive timestamp, a date that records a fact without placing the entry on the agenda calendar (see Dates and Times). If you cycle the task back to TODO, Org removes the line again. If you remove the keyword altogether, the line is also removed, unless org-closed-keep-when-no-todo is non-nil.

Set org-log-done to note instead, and Org also asks for a short note when you close a task. The per-file equivalents are #+STARTUP: logdone and #+STARTUP: lognotedone.

Logging every state change

A CLOSED line records the end of a task, not its path. To log intermediate changes, add markers to the keywords in org-todo-keywords, inside the same parentheses as the selection key:

  • ! records a timestamp when the task enters this state.
  • @ records a timestamp and asks for a note.
  • A slash followed by ! or @ (for example w@/!) adds a rule for leaving the state: Org logs the departure, but only if the target state does not already log its own arrival.
(setq org-todo-keywords
      '((sequence "TODO(t)" "WAIT(w@/!)" "|" "DONE(d!)" "CANCELED(c@)"))
      org-log-into-drawer t)

This setup asks for a note when a task starts waiting or gets canceled, because those moments deserve an explanation. It records a bare timestamp when a task is done. Thanks to /!, it also stamps the moment a task leaves WAIT for TODO, even though TODO itself logs nothing.

stateDiagram-v2
    direction LR
    TODO --> WAIT: on entry, timestamp and note (@)
    WAIT --> TODO: on leaving WAIT, timestamp (/!)
    TODO --> DONE: on entry, timestamp (!)
    WAIT --> DONE: on entry, timestamp (!)
    TODO --> CANCELED: on entry, timestamp and note (@)
    WAIT --> CANCELED: on entry, timestamp and note (@)

Figure 8.2: Each keyword declares what Org records when a task enters it, and WAIT also declares a record for leaving it, which applies only when the target state records nothing itself.

Starting from * TODO Renew the TLS certificate, a batch run moved the task to WAIT (with a note), back to TODO, and then to DONE. The result:

* DONE Renew the TLS certificate
:LOGBOOK:
- State "DONE"       from "TODO"       [2026-11-19 Thu 04:24]
- State "TODO"       from "WAIT"       [2026-11-19 Thu 04:24]
- State "WAIT"       from "TODO"       [2026-11-19 Thu 04:24] \\
  Waiting for the CA to validate the domain.
:END:

Notice 3 details. The newest record comes first, as set by org-log-states-order-reversed (default t). The records sit inside a LOGBOOK drawer, because org-log-into-drawer is t; a drawer is a named block between :NAME: and :END: that Org folds away by default (see Document Structure). Without that setting the records would appear as a plain list directly under the headline, where they clutter the entry. Finally, the note appears after a \\ line break on its own indented line.

When Org asks for a note, it opens a small buffer. Type the note and press C-c C-c to store it. If you only want the timestamp this time, press C-c C-c on the empty buffer. You can also force a note on any state change with C-u C-c C-t, even when the keyword does not request one.

The same marker syntax works in per-file settings:

#+TODO: TODO(t) WAIT(w@/!) | DONE(d!) CANCELED(c@)

If you use both org-log-done and per-keyword logging, Org may write 2 timestamps for 1 change, but it never asks for 2 notes: the state-change note takes precedence over the closing note.

Logging rules for one subtree

Logging needs vary between projects. A client project may need a full audit trail, while a personal errand list needs none. The LOGGING property sets the rules for an entry and its subtree. Any non-empty value first resets every logging option to nil; the words in the value then turn individual options back on. A value can contain keyword markers such as NEXT(!) and logging words from #+STARTUP, such as lognotedone or logrepeat. The value nil disables logging completely. The related property LOG_INTO_DRAWER overrides org-log-into-drawer for the subtree.

#+STARTUP: logdone
#+TODO: TODO NEXT | DONE

* Project Atlas
:PROPERTIES:
:LOGGING:  NEXT(!) DONE(!)
:LOG_INTO_DRAWER: t
:END:
** TODO Draft the schema
* TODO Buy coffee beans

In a batch run, “Draft the schema” went to NEXT and then to DONE, and “Buy coffee beans” went straight to DONE. The file afterwards (the 2 header lines, which did not change, are left out):

* Project Atlas
:PROPERTIES:
:LOGGING:  NEXT(!) DONE(!)
:LOG_INTO_DRAWER: t
:END:
** DONE Draft the schema
:LOGBOOK:
- State "DONE"       from "NEXT"       [2026-11-19 Thu 04:30]
- State "NEXT"       from "TODO"       [2026-11-19 Thu 04:30]
:END:
* DONE Buy coffee beans
CLOSED: [2026-11-19 Thu 04:30]

The task inside Project Atlas has no CLOSED line. The LOGGING property reset logdone for that subtree, and the value does not turn it back on, so the only record of completion is the DONE(!) state line. The task outside the project still follows the file-wide #+STARTUP: logdone.

Which mechanism to choose

The 3 logging mechanisms overlap, so it helps to assign each one a job:

NeedMechanism
Know when each task was finishedorg-log-done set to time (CLOSED line).
Know why a task stalled or was dropped@ on the waiting and canceled keywords.
A full history of a task’s states! on every keyword, together with org-log-into-drawer.
Different rules for one projectA LOGGING property on the project headline.

The LOGBOOK drawer is also where clocking writes its CLOCK lines, so time tracking and state history end up side by side (see Clocking, Effort and Timers).

Priorities

Once you have more open tasks than you can do today, you need a way to say which ones matter most. Org’s answer is the priority cookie: a marker such as [#A] placed right after the keyword.

* TODO [#A] Patch the production outage
* TODO [#C] Tidy the wiki sidebar
* TODO Answer the conference invitation

By default there are 3 priorities, A (highest), B and C (lowest), and a headline without a cookie counts as B, the value of org-priority-default. Priorities do not change the behavior of the task itself; they matter when the agenda sorts entries. Any headline can carry a priority, not only tasks.

The keys:

  • C-c , (org-priority) asks for a priority character; SPC removes the cookie.
  • S-UP (org-priority-up) and S-DOWN (org-priority-down) step through the priorities.
  • , in the agenda sets the priority of the task on the current line.

Stepping starts from the default priority when a headline has no cookie (governed by org-priority-start-cycle-with-default) and removes the cookie again after the last value. A batch run pressed S-UP twice and then S-DOWN three times on a fresh task:

* TODO [#B] Fix the login bug
* TODO [#A] Fix the login bug
* TODO Fix the login bug

The first 2 lines show the state after each S-UP; the last line shows the state after the 3 S-DOWN presses, which went from A to B, to C, and then removed the cookie. Note that S-UP and S-DOWN also change dates when point is on a timestamp.

Changing the range

If 3 levels are too few, widen the range with org-priority-highest, org-priority-lowest and org-priority-default. The values are characters (uppercase letters A to Z) or integers from 0 to 64. A file can set all three at once with the order highest, lowest, default:

#+PRIORITIES: A E C

Numeric priorities look like [#1] and need numeric settings:

#+PRIORITIES: 1 10 5
* TODO [#1] Patch the production outage

Keep the highest value smaller (earlier in the alphabet, or a lower number) than the lowest. In Org 9.8, org-lint also checks priority cookies against these settings, and the speed keys 1, 2 and 3 (single-key commands at the start of a headline, see Getting Started) insert the highest, default and lowest priority instead of fixed letters.

Breaking tasks into subtasks

Large tasks are hard to start and hard to track. The natural Org solution is to add child headlines under the task, each a smaller task of its own. To see progress at a glance, put a statistics cookie in the parent headline: [/] shows a fraction and [%] shows a percentage. Org fills in the cookie and updates it whenever the state of a direct child changes.

* Prepare the 2.0 release [/]
** TODO Freeze the API [%]
*** DONE Review public functions
*** TODO Write deprecation notices
** TODO Update the changelog
** DONE Tag the release candidate

After C-u C-c # (org-update-statistics-cookies with a prefix, which updates every cookie in the file), the batch output was:

* Prepare the 2.0 release [1/3]
** TODO Freeze the API [50%]
*** DONE Review public functions
*** TODO Write deprecation notices
** TODO Update the changelog
** DONE Tag the release candidate

Marking “Write deprecation notices” as DONE then changed the cookie of its parent to [100%]. The top cookie stayed at [1/3], because “Freeze the API” itself was still TODO: each cookie counts only its direct children. The parent did not change state either; whether to close it is your decision.

If you add or delete children by editing text, the cookies can fall out of date. C-c # updates the cookie of the current entry, and C-u C-c # updates the whole file. C-c C-c on a cookie also updates it.

Counting deeper levels

The variable org-hierarchical-todo-statistics controls the scope: its default t restricts the count to direct children, and nil counts every task in the subtree. To change the scope of one cookie only, put the word recursive in the COOKIE_DATA property:

* Parent [1/3]
:PROPERTIES:
:COOKIE_DATA: todo recursive
:END:
** TODO Child
*** DONE Grandchild
*** TODO Grandchild 2

The cookie counts all 3 tasks below the parent, and 1 of them is done. The word todo in the same property tells the cookie to count child tasks rather than checkboxes, which matters when an entry has both.

Closing the parent automatically

Some people prefer the parent to follow its children: done when all subtasks are done, open again when one is reopened. Org does not do this by itself, but whenever a child changes state and the parent has a cookie, it runs org-after-todo-statistics-hook with the number of done and not-done children. A small function on that hook does the job:

(defun my/org-summary-todo (n-done n-not-done)
  "Mark the parent DONE when all children are done, TODO otherwise."
  (let (org-log-done org-todo-log-states)
    (org-todo (if (= n-not-done 0) "DONE" "TODO"))))

(add-hook 'org-after-todo-statistics-hook #'my/org-summary-todo)

The let form turns logging off while the function runs, so that the automatic change does not prompt for notes. With the hook installed, finishing the last child in this file:

* TODO Onboard the new teammate [/]
** DONE Create accounts
** TODO Pair on the first ticket

gave this result in a batch run:

* DONE Onboard the new teammate [2/2]
** DONE Create accounts
** DONE Pair on the first ticket

The hook fires only for headlines that carry a statistics cookie, so you choose per parent whether it should follow its children.

Checkboxes

Not every step deserves a headline. Child tasks appear in the global TODO list, can be scheduled and carry their own logs; for a checklist of small steps, that is too much. A checkbox is a lighter alternative: a plain list item that starts with [ ] (see Document Structure for plain lists). Checkboxes do not appear in the agenda’s TODO list, which keeps short steps out of your daily overview.

A checkbox has 3 states: [ ] (not checked), [-] (partly checked) and [X] (checked). A parent checkbox follows its children automatically, and a statistics cookie in the headline or in a list item counts the checkboxes directly below it.

* TODO Set up the new laptop [/]
- [ ] Install the operating system
- [ ] Restore dotfiles [/]
  - [ ] Emacs configuration
  - [ ] Shell configuration
- [ ] Enroll in the VPN

Toggling “Emacs configuration” with C-c C-c gave this state:

* TODO Set up the new laptop [0/3]
- [ ] Install the operating system
- [-] Restore dotfiles [1/2]
  - [X] Emacs configuration
  - [ ] Shell configuration
- [ ] Enroll in the VPN

Toggling “Shell configuration” and “Install the operating system” as well gave:

* TODO Set up the new laptop [2/3]
- [X] Install the operating system
- [X] Restore dotfiles [2/2]
  - [X] Emacs configuration
  - [X] Shell configuration
- [ ] Enroll in the VPN

The parent item “Restore dotfiles” moved from [ ] to [-] to [X] without being touched, and both cookies kept up.

flowchart LR
    A["toggle a child checkbox"] -->|"none, some or all checked"| B["parent item: [ ] [-] [X]"]
    B -->|"checked count"| C["item cookie [n/m]"]
    B -->|"checked count of direct items"| D["headline cookie [n/m]"]
    E["change a child TODO state"] -->|"done count"| D
    D -->|"n-done, n-not-done"| F["org-after-todo-statistics-hook"]

Figure 8.3: A change at the bottom of the tree propagates upward one level at a time: checkboxes update their parent item and the nearest cookie, and TODO children update the cookie of their parent headline, which can in turn run a hook.

The checkbox commands:

KeyCommandEffect
C-c C-corg-toggle-checkboxToggle the checkbox at point. With C-u, add or remove the checkbox itself; with C-u C-u, set it to [-].
C-c C-x C-borg-toggle-checkboxThe same, but also works on a region (all boxes follow the first) and, on a headline, on the boxes between it and the next headline.
M-S-RETorg-insert-todo-headingIn a list item, insert a new item with a checkbox.
C-c C-x C-rorg-toggle-radio-buttonTreat the box at point as a radio button: checking it unchecks its siblings.
C-c #org-update-statistics-cookiesRecount after manual edits.

To convert an existing list, put point on its first item and press C-u C-c C-c: when that item has no checkbox, Org gives one to each item in the list.

A few variations are worth knowing:

  • An ORDERED property on the headline forces checkboxes to be checked in order; checking one out of order raises an error.
  • A cookie counts only direct children by default. Set org-checkbox-hierarchical-statistics to nil to count every checkbox below it.
  • To make a whole list behave like radio buttons, put #+ATTR_ORG: :radio t before it, or enable org-list-checkbox-radio-mode.
  • When a headline has both child tasks and checkboxes, set COOKIE_DATA to checkbox or todo to say which one its cookie counts.

Headlines or checkboxes?

Use child headlines whenUse checkboxes when
A step needs its own date, priority, tags or notes.A step is a single action with no metadata.
A step should appear in the agenda.Steps should stay out of the agenda.
A step may need its own subtasks or log.The list is a checklist, such as a packing list or a release checklist.

You can mix both: a task headline for each deliverable, and a checklist inside each one.

Habits

A habit is a recurring task that you want to perform regularly, such as exercising or reviewing your inbox. Org treats habits as a special case of repeating tasks and draws a consistency graph for them in the agenda, so that you can see at a glance whether you are keeping up.

Habits live in an optional module that you load first:

(with-eval-after-load 'org
  (add-to-list 'org-modules 'org-habit))

A habit needs 4 things:

  1. A not-done keyword.
  2. The property STYLE set to habit.
  3. A SCHEDULED date with a repeater, usually of the .+ kind, which counts the next date from the day you complete the task. The repeater may have a second interval after a slash: .+2d/4d means “at most every 2 days, at least every 4 days”.
  4. Logging of the done state, so that Org has a history to draw. Without it the habit still works, but the graph has no data.

Scheduling and repeaters are covered in Dates and Times. Here is a habit with a few weeks of history in its LOGBOOK:

* TODO Water the plants
SCHEDULED: <2026-11-19 Thu .+2d/4d>
:PROPERTIES:
:STYLE:    habit
:LAST_REPEAT: [2026-11-18 Wed 08:10]
:END:
:LOGBOOK:
- State "DONE"       from "TODO"       [2026-11-18 Wed 08:10]
- State "DONE"       from "TODO"       [2026-11-14 Sat 09:02]
- State "DONE"       from "TODO"       [2026-11-12 Thu 07:45]
- State "DONE"       from "TODO"       [2026-11-08 Sun 10:30]
- State "DONE"       from "TODO"       [2026-11-06 Fri 08:15]
- State "DONE"       from "TODO"       [2026-11-01 Sun 09:00]
:END:

The day agenda for 19 November 2026, generated in batch with org-habit loaded and this file (habits.org, which also contains an ordinary scheduled task) as the only agenda file, looked like this:

Day-agenda (W47):
Thursday   19 November 2026
  habits:     Scheduled:  TODO Review the weekly metrics
  habits:     TODO Water the plants        *    * *   * *   *!

The graph starts at the column given by org-habit-graph-column (default 40) and overwrites any text there, so keep habit titles short. Each character is one day: an asterisk marks a day on which you completed the habit, and ! marks today. In a live Emacs, each day is also colored: blue when the task was not yet due, green when it could have been done, yellow when it would become overdue the next day, and red when it was overdue.

Related settings: org-habit-preceding-days (default 21) and org-habit-following-days (default 7) set the span of the graph, and org-habit-show-habits-only-for-today (default t) keeps habits off future days of the agenda. In the agenda, K hides or shows all habits, and C-u K toggles the “only today” option.

Summary

  • A headline becomes a task when it starts with a TODO keyword; C-c C-t changes the state.
  • org-todo-keywords (or #+TODO: lines) define sequences of states, split into not-done and done by |; selection keys in parentheses turn on fast selection.
  • org-enforce-todo-dependencies and the ORDERED property block tasks until their children or earlier siblings are done.
  • org-log-done, the ! and @ markers, org-log-into-drawer and the LOGGING property record when and why a task changed state.
  • Priority cookies such as [#A] rank tasks for agenda sorting.
  • Statistics cookies [/] and [%] measure progress over child tasks or checkboxes, and org-after-todo-statistics-hook can act on that progress.
  • Habits are repeating tasks with a STYLE of habit and a consistency graph in the agenda.

Further reading

Tags, Properties and Column View

An outline answers one question well: where does this entry belong? Real information rarely fits a single hierarchy, though. A task in the “Website relaunch” project may also be something you can only do at the office, something that blocks a customer, and something estimated at 3 hours. Org gives you two kinds of metadata for these cross-cutting facts. Tags are short labels attached to a headline. Properties are key-value pairs stored in a drawer under the headline.

Both kinds of metadata follow the outline: a child can inherit what its parent declares. Both can be queried with the same compact match language, which drives sparse trees, agenda views and dynamic blocks. Properties can also be laid out as a table with column view, which turns an outline into a small database that you can edit in place. This chapter covers each of these in turn.

Tags

The essential idea

A tag is a word between colons at the end of a headline. A headline can have several tags, written one after another with single colons between them:

* Website relaunch                                              :project:
** TODO Design the landing page                         :frontend:@home:
** TODO Migrate the user table                             :backend:crypt:
** DONE Choose a hosting provider                                :@office:

Tags may contain letters, digits, _, @, # and %. A common convention, used in the manual’s own examples, is to start context tags (places or tools you need) with @, so that @office and @home stand apart from topical tags such as backend.

Why tags rather than more headlines? Because a headline can sit in only one place in the tree, while it can carry any number of tags. Tags let you slice the same outline in several directions: by project through the tree, by context through @ tags, by area through topical tags.

Inheritance

Tags follow the tree. A headline has its own tags plus every tag of its ancestors. In the example above, “Migrate the user table” has its own tags backend and crypt and inherits project from its parent.

You can also declare tags for an entire file with the FILETAGS keyword. These tags behave as though they belonged to an invisible level 0 headline that contains the whole file:

#+FILETAGS: :acme:

Here is the complete file used for the examples in this section:

#+FILETAGS: :acme:
#+TAGS: [ dev : backend frontend ]
#+TAGS: { @office(o) @home(h) } laptop(l)

* Website relaunch                                              :project:
** TODO Design the landing page                         :frontend:@home:
** TODO Migrate the user table                             :backend:crypt:
** DONE Choose a hosting provider                                :@office:
* Personal
** TODO Renew passport                                           :errand:
flowchart TD
    F["#+FILETAGS: :acme:"] -->|"acme"| P["Website relaunch :project: (level 1)"]
    P -->|"acme, project"| M["Migrate the user table :backend:crypt: (level 2)"]
    F -->|"acme"| Q["Personal (level 1)"]
    Q -->|"acme"| R["Renew passport :errand: (level 2)"]
    M --> MT["effective tags: acme project backend crypt"]
    R --> RT["effective tags: acme errand"]

Figure 9.1: Each headline’s effective tags are its own tags plus everything that flows down from its ancestors and from FILETAGS.

The function org-get-tags returns the effective tags, and Org marks the inherited ones with a text property. Called on “Migrate the user table” in a batch run, it returned:

local: ("backend" "crypt")
all:   (#("acme" 0 4 (inherited t)) #("project" 0 7 (inherited t)) "backend" "crypt")

Inheritance is usually what you want, but not always. 2 variables restrict it:

  • org-use-tag-inheritance (default t) can be nil to turn inheritance off, a list of tags that are inherited, or a regular expression that matches them.
  • org-tags-exclude-from-inheritance (default nil) lists tags that are never inherited.

A typical candidate for exclusion is a tag that marks an action on one entry only. Org Crypt, for example, encrypts entries tagged crypt, and the manual’s setup for it excludes that tag so that children of an encrypted entry are not encrypted again:

(setq org-tags-exclude-from-inheritance '("crypt"))

Inheritance affects searches. In the agenda, tag-based views (tags, tags-todo) honor org-use-tag-inheritance when they select entries. Other agenda views select entries without tags, but still compute inherited tags so that you can filter by them later; the variable org-agenda-use-tag-inheritance (default (todo search agenda)) lists the views that do this, and setting it to nil makes those views faster.

Setting tags

You can type tags directly at the end of a headline, and M-TAB after a colon completes tag names. Usually, though, you use a command:

  • C-c C-q (org-set-tags-command) asks for the tags of the current headline and aligns them.
  • C-c C-c on a headline does the same.
  • C-u C-c C-q realigns the tags of every headline in the buffer.

Tags are right-aligned to the column in org-tags-column (default -77, where a negative value means “end at column 77”). Org realigns them automatically after promotion, demotion and state changes.

By default, completion offers every tag already used in the current buffer. For a controlled vocabulary, define the list yourself, either for all files with org-tag-alist or for one file with #+TAGS: lines:

#+TAGS: @office @home @phone
#+TAGS: laptop server

An empty #+TAGS: line switches a file back to the dynamic list even when org-tag-alist is set. Tags that should be available everywhere, in addition to each file’s own list, go into org-tag-persistent-alist; a file can ignore them with #+STARTUP: noptag. To complete over the tags of all agenda files instead of the current buffer, set org-complete-tags-always-offer-all-agenda-tags.

Fast tag selection

Typing tag names is slow when you tag dozens of entries a day. Fast tag selection assigns a single key to each tag, so that one keystroke toggles it. Give the keys in parentheses after the tag names:

#+TAGS: { @office(o) @home(h) } laptop(l) server(s)

or globally:

(setq org-tag-alist
      '((:startgroup . nil)
        ("@office" . ?o) ("@home" . ?h)
        (:endgroup . nil)
        ("laptop" . ?l) ("server" . ?s)))

Once at least one tag has a key, C-c C-c on a headline opens a selection window. It lists the inherited tags, the current tags and every defined tag with its key. Pressing a tag’s key adds or removes that tag; Org assigns keys automatically to tags that have none. Several keys have fixed meanings in this window:

KeyEffect
TABType a tag in the minibuffer, including one that is not in the list; separate several with commas.
SPCRemove all tags from the headline.
RETAccept the changes.
C-gCancel. q also cancels unless it is assigned to a tag.
!Suspend the mutually exclusive groups for this selection.
C-cToggle automatic exit after the next change.

The braces in the #+TAGS: line (or :startgroup and :endgroup in the variable) form a mutually exclusive group: selecting @home in the window removes @office, because a task cannot happen in two places. With the setup above, C-c C-c SPC h l RET replaces all tags with @home and laptop, and C-c C-c o RET switches the context to @office.

To break the window into rows, insert \n in a #+TAGS: line or :newline in the variable. If you usually change one tag at a time, set org-fast-tag-selection-single-key to t: the window then closes after the first key. Set it to expert and the window does not even appear unless you press an extra C-c. The number of tags shown is capped by org-fast-tag-selection-maximum-tags.

Tag hierarchies

Sometimes one tag is a broader term for several others. You might tag tasks backend or frontend, but also want to ask for “all development work”. A group tag expresses that relation. Square brackets define it, with a colon between the group tag and its members; the spaces around the brackets and the colon are required:

#+TAGS: [ dev : backend frontend ]

Searching for a group tag matches its members too. With the example file above, these searches gave the following results in a batch run (the function org-map-entries lists the headlines that match a search string):

dev    => ("Design the landing page" "Migrate the user table")
-dev   => ("Website relaunch" "Choose a hosting provider" "Personal" "Renew passport")

Neither headline carries the tag dev itself. Org expands the group into a regular expression over all members before matching, and a negated group excludes headlines that carry any member.

Groups can be nested, because a member can itself be a group tag. Members can also be regular expressions in braces, which suits tags that follow a naming pattern, such as one tag per project:

#+TAGS: [ Project : {P@.+} ]

* Kickoff meeting  :P@atlas:
* Budget review    :P@zephyr:
* Gym              :health:

A search for Project returned ("Kickoff meeting" "Budget review"). With group tags disabled, the same search returned nil.

Both kinds of member combine into a hierarchy when a group tag lists other group tags:

#+TAGS: [ work : dev Project ]
#+TAGS: [ dev : backend frontend ]
#+TAGS: [ Project : {P@.+} ]

* Fix the API rate limit  :backend:
* Kickoff meeting         :P@atlas:
* Gym                     :health:
flowchart TD
    W["work (group)"] --> D["dev (group)"]
    W --> P["Project (group)"]
    D --> B["backend"]
    D --> FE["frontend"]
    P --> R["{P@.+} (regex member)"]
    R --> PA["P@atlas, P@zephyr, ..."]

Searching this file gave the following results in a batch run:

work     => ("Fix the API rate limit" "Kickoff meeting")
dev      => ("Fix the API rate limit")
Project  => ("Kickoff meeting")
-work    => ("Gym")

Figure 9.2: A tag hierarchy is a tree of group tags; searching for any group tag matches every tag beneath it, including tags that only match a regular expression.

A group can also be mutually exclusive if you use braces with a colon, as in #+TAGS: { Context : @office @home @phone }. In org-tag-alist, use :startgrouptag, :grouptags and :endgrouptag for an ordinary group, and :startgroup, :grouptags and :endgroup for an exclusive one:

(setq org-tag-alist
      '((:startgrouptag) ("dev") (:grouptags)
        ("backend") ("frontend")
        (:endgrouptag)))

C-c C-x q (org-toggle-tags-groups) turns group expansion off and on for the current session, and setting org-group-tags to nil disables it permanently. Since Org 9.8, org-tags-sort-function accepts the function org-tags-sort-hierarchy, which orders tags according to their hierarchy, and the variable may also hold a list of functions, applied in turn to break ties.

The variable org-tag-faces gives individual tags their own face, in the same way that org-todo-keyword-faces does for TODO keywords (see TODO Items).

Properties

The essential idea

A tag says “this entry belongs to a category”. A property says “this entry has this value for this attribute”: the owner is Ana, the estimate is 3 hours, the customer is Globex. Properties are stored in a PROPERTIES drawer, which must come directly after the headline (and after its planning line with SCHEDULED or DEADLINE, when there is one):

* TODO Fix login timeout                                         :backend:
DEADLINE: <2026-11-21 Sat>
:PROPERTIES:
:Points:   2
:Customer: Globex
:END:

Each line holds one property: the key between colons, then the value. Keys are case-insensitive, so :Customer: and :CUSTOMER: name the same property.

Properties serve 2 purposes. First, they work like tags with values: one property Release with values 2.0 and 3.0 replaces a growing family of tags such as release_2 and release_3. Second, they turn a set of headlines into records with fields, which column view (later in this chapter) can display and edit as a table.

Editing properties

KeyCommandEffect
C-c C-x porg-set-propertyAsk for a key and a value, creating the drawer if needed.
M-TABpcompleteAfter a colon at the start of a line, complete property keys used in the file.
C-c C-c in a drawerorg-property-actionOffer property commands: s sets, d deletes, D deletes from every entry in the file, c computes the value from the column definition.
S-RIGHT, S-LEFTorg-property-next-allowed-value, org-property-previous-allowed-valueCycle through the allowed values.

To insert an empty drawer, use C-u M-x org-insert-drawer.

Allowed values

Free-text values invite typing errors: Globex, globex and GlobEx are 3 different values to a search. To restrict a property, define its allowed values in a property whose key ends with _ALL:

#+PROPERTY: Status_ALL todo review done

* Dune
:PROPERTIES:
:Status:   todo
:END:

The _ALL property is inherited, so one definition near the top of a tree (or in the file header) covers everything below it. With point on the :Status: line, S-RIGHT steps to the next allowed value. Two presses in a batch run produced:

:Status:   review
:Status:   done

Values that contain spaces need double quotes in the _ALL list, for example "In progress".

File-wide and global properties

A #+PROPERTY: line sets a property for the whole file, as if it were defined above the first headline:

#+PROPERTY: Owner Ana

A property drawer at the very top of the file, before any headline and with only comments above it, does the same.

To add to a value instead of replacing it, append + to the key. Each + line contributes one more value, separated by a space. This works across levels as well:

#+PROPERTY: var  foo=1
#+PROPERTY: var+ bar=2

* Library
:PROPERTIES:
:Genres:   Fiction
:END:
** Dune
:PROPERTIES:
:Genres+:  SF
:Genres+:  Classic
:END:

For “Dune”, a batch run returned "foo=1 bar=2" for var and "Fiction SF Classic" for Genres when looking up with inheritance, but only "SF Classic" without inheritance. A key may appear more than once in a drawer only with the + suffix; the result of repeating a key without it is undefined.

The pattern is common in code blocks, where header-args properties accumulate settings (see Working with Source Code):

#+PROPERTY: header-args :results silent
#+PROPERTY: header-args+ :exports both

For defaults across all files, set org-global-properties, an alist of keys and values that every entry can inherit.

Property inheritance

Tags are inherited by default; properties are not. Looking up inherited values means walking up the tree for every entry, which slows down searches, and most properties describe one entry only. When you do want inheritance, turn it on selectively with org-use-property-inheritance. Its value can be t (all properties), a list of property names, or a regular expression:

(setq org-use-property-inheritance '("Release" "Customer"))

When a property is inherited, Org looks for the value in this order, and stops at the first one it finds:

flowchart LR
    E["entry's own drawer"] -->|"not found"| A["parent, grandparent, ..."]
    A -->|"not found"| K["#+PROPERTY lines and top drawer"]
    K -->|"not found"| G["org-global-properties"]
    G -->|"not found"| N["nil"]

Figure 9.3: An inherited lookup climbs from the entry through its ancestors to the file and finally to the global defaults; the first value found wins.

A value of nil in a drawer explicitly “undefines” a property: the lookup stops there and returns nil.

A few properties are always inherited for their own purpose, whatever org-use-property-inheritance says:

PropertyPurpose
COLUMNSThe column view format for the subtree (see below).
CATEGORYThe category shown in agenda lines (see Agenda Views).
ARCHIVEThe archive location for the subtree (see Capture, Refile, Archive and Attachments).
LOGGINGLogging settings for the subtree (see TODO Items).

In Lisp, the function org-entry-get takes an inherit argument that makes the distinction visible. In a batch run on an entry whose parent defined Release as 3.0:

nil:       nil
t:         "3.0"
selective: nil
selective+var: "3.0"

With t the lookup always inherits; with selective it inherits only when org-use-property-inheritance allows it for that property, which was the case only in the last line.

Special properties

Much of what Org knows about an entry is not stored in a drawer: the TODO keyword, the priority, the tags, the deadline. Org exposes these as special properties, read-only names that you can use in searches and in column view exactly like real properties. Do not use these names as keys in a drawer.

PropertyValue
ITEMThe headline text.
TODOThe TODO keyword.
PRIORITYThe priority, as a single character.
TAGSThe tags written on the headline.
ALLTAGSAll tags, including inherited ones.
BLOCKEDt if the task is blocked by dependencies (see TODO Items).
CATEGORYThe category of the entry.
FILEThe file name.
DEADLINE, SCHEDULED, CLOSEDThe corresponding timestamps.
TIMESTAMP, TIMESTAMP_IAThe first active or inactive timestamp in the entry that is not part of a planning line.
CLOCKSUM, CLOCKSUM_TThe clocked time of the subtree, overall and for today, after org-clock-sum or org-clock-sum-today has run (see Clocking, Effort and Timers).

org-entry-properties returns both kinds. For “Port the CLI” in the release file shown later in this chapter, it returned the following (the absolute file name is shortened here):

(("CATEGORY" . "props") ("DONE" . "[X]") ("ESTIMATE" . "1-2") ("EFFORT" . "3:30")
 ("OWNER" . "Ben") ("BLOCKED" . "") ("FILE" . "...")
 ("PRIORITY" . "B") ("TODO" . "TODO") ("ITEM" . "Port the CLI"))

Note that the priority is reported as B even though the headline has no cookie: the special property reflects the default priority.

Searching with match strings

Tags and properties become useful when you can ask questions about them. Org uses one small query language, the match string, for all such questions. The same string works in three places:

  • C-c / m or C-c \ (org-match-sparse-tree) shows the matching headlines of the current buffer as a sparse tree; with C-u, only TODO entries.
  • m in the agenda dispatcher (org-tags-view) collects matches from all agenda files; M restricts the result to TODO entries.
  • The :match parameter of a column view dynamic block, custom agenda commands, and the Lisp function org-map-entries.

For a quick search on one property, C-c / p asks for a property name and a value and builds a sparse tree; a value in braces is treated as a regular expression.

Grammar

A match string is a list of alternatives separated by |. Each alternative is a list of terms that must all hold. A term is preceded by + (must match) or - (must not match); between terms without a sign you can write &. & binds more tightly than |, and there are no parentheses. Finally, an optional part after / tests TODO keywords.

flowchart LR
    S["match string"] -->|"split at the pipe"| A["alternatives (OR)"]
    A -->|"split at + - and"| T["terms (AND), each + or -"]
    T --> TG["tag: backend"]
    T --> RX["tag regexp: {^@}"]
    T --> PR["PROP OP VALUE"]
    S -->|"optional / part"| TD["TODO keywords: /!-WAIT"]
    PR --> V["number, quoted string, quoted date, {regexp}"]

Figure 9.4: A match string is OR over AND: alternatives split at the pipe symbol, terms inside an alternative are combined with AND, and each term tests a tag, a tag regexp or a property.

Tag terms

Using the example file from the tags section (which has acme as a file tag), a batch run of org-map-entries returned:

project                      => ("Website relaunch" "Design the landing page" "Migrate the user table" "Choose a hosting provider")
acme-project                 => ("Personal" "Renew passport")
{^@}                         => ("Design the landing page" "Choose a hosting provider")
crypt                        => ("Migrate the user table")
LEVEL=2+@home|errand         => ("Design the landing page" "Renew passport")
project/!                    => ("Design the landing page" "Migrate the user table")
-project+acme/-DONE          => ("Personal" "Renew passport")

Each line deserves a short explanation:

  • project matches the headline that carries the tag and all its descendants, which inherit it.
  • acme-project keeps the file tag and removes everything inside the project.
  • {^@} is a regular expression over tag names: here, every headline with a context tag.
  • LEVEL=2+@home|errand shows 2 alternatives; the first combines the special property LEVEL (the outline level) with a tag.
  • project/! keeps only entries with a not-done TODO keyword; the ! after the slash restricts the TODO part to not-done states.
  • -project+acme/-DONE combines tag terms with a negative TODO test.

Property terms

A property term has the form PROPERTY OPERATOR VALUE. The operators are =, <>, <, >, <= and >= (with == as a synonym for =, and != and /= for <>). How the comparison works depends on the way you write the value:

Value written asComparisonExample
A plain numberNumericPoints>=3
A string in double quotesStringCustomer="Globex"
A date in double quotes and angle bracketsTimeDEADLINE<="<+7d>"
A regular expression in braces= matches, <> does not matchCustomer={^Glo}

The date form accepts "<now>", "<today>", "<tomorrow>" and relative offsets such as "<+5d>" or "<-2m>" with the units d, w, m and y.

Every operator can be followed by *, as in <* or <>*. A starred operator matches only entries where the property actually exists. This matters for negative or “less than” tests, where a missing property would otherwise count as matching. The following file shows the difference:

* TODO Fix login timeout  :backend:
DEADLINE: <2026-11-21 Sat>
:PROPERTIES:
:Points:   2
:Customer: Globex
:END:
* TODO Redesign settings page  :frontend:
DEADLINE: <2026-12-15 Tue>
:PROPERTIES:
:Points:   8
:Customer: Initech
:END:
* WAIT Upgrade the CI runners  :ops:
* DONE Write the API docs  :backend:
:PROPERTIES:
:Points:   3
:END:

A batch run on 19 November 2026, with the keywords TODO, WAIT and DONE, returned:

Points<5                 => ("Fix login timeout" "Upgrade the CI runners" "Write the API docs")
Points<*5                => ("Fix login timeout" "Write the API docs")
Customer<>"Globex"       => ("Redesign settings page" "Upgrade the CI runners" "Write the API docs")
Customer<>*"Globex"      => ("Redesign settings page")
Customer={^Glo}          => ("Fix login timeout")
DEADLINE<="<+7d>"        => ("Fix login timeout")
backend-TODO="DONE"      => ("Fix login timeout")
/WAIT                    => ("Upgrade the CI runners")
-ops/!-WAIT              => ("Fix login timeout" "Redesign settings page")
TODO={TODO\|WAIT}        => ("Fix login timeout" "Redesign settings page" "Upgrade the CI runners")

“Upgrade the CI runners” has no Points property, so the unstarred Points<5 treats it as 0 and includes it, while Points<*5 leaves it out. The same applies to Customer<>"Globex".

Numeric comparison reads only the leading number of a value. A duration such as 3:30 compares as 3, and 45 (minutes) compares as 45, so do not use numeric operators on time values such as Effort. For those, use column view summaries or the agenda’s effort filters (see Clocking, Effort and Timers).

Property names that contain characters other than letters, digits and underscores must escape those characters with a backslash in a match string: boss\-prio="C". If inheritance is enabled for a property in org-use-property-inheritance, matching also sees inherited values, with the speed cost mentioned earlier.

Column view

The essential idea

Once your entries carry properties, you will want to see them side by side. Column view displays a subtree as a table: each headline becomes a row and each column shows one property. Org does this with overlays, so the file itself does not change, and you can still fold and unfold the outline while the table is active. You can also edit values directly in the table.

C-c C-x C-c (org-columns) turns column view on. It looks upward from point for a COLUMNS property and uses the subtree where it found one; if there is none, it uses the #+COLUMNS: line of the file or org-columns-default-format, whose default is %25ITEM %TODO %3PRIORITY %TAGS. Before the first headline, it shows the whole file. q (or C-c C-c when point is not on a checkbox) turns it off, and g or r refreshes it after edits made elsewhere.

Defining columns

A column format is a list of column definitions, each with the following shape:

%[WIDTH]PROPERTY[(TITLE)][{SUMMARY-TYPE}]

Only the percent sign and the property name are required. WIDTH fixes the width in characters, TITLE replaces the property name in the header, and SUMMARY-TYPE tells Org to compute the value of a parent row from its children.

Put the format in a COLUMNS property at the top of the tree where it applies, or in a #+COLUMNS: line for the whole file. A COLUMNS property applies to its entry and the entire subtree, so you can define a general format at level 1 and more specific ones deeper down.

Here is a small release plan, used for the rest of this section:

#+PROPERTY: Owner_ALL Ana Ben Chen

* Release 3.0
:PROPERTIES:
:COLUMNS:  %30ITEM %TODO %Owner %Effort{:} %Estimate{est+} %Done{X/}
:Release:  3.0
:ID:       release-3
:END:
** TODO Rewrite the parser
:PROPERTIES:
:Owner:    Ana
:Effort:   6:00
:Estimate: 2-4
:Done:     [ ]
:END:
** TODO Port the CLI
:PROPERTIES:
:Owner:    Ben
:Effort:   3:30
:Estimate: 1-2
:Done:     [X]
:END:
** DONE Update the docs
:PROPERTIES:
:Owner:    Chen
:Effort:   1:15
:Estimate: 0.5-1
:Done:     [X]
:END:

Summary types

A summary type aggregates the values of the direct children into the parent row. The most useful ones:

TypeResult
+Sum of numbers. +;%.1f formats the sum; $ is short for +;%.2f.
min, max, meanSmallest, largest, average number.
:Sum of times such as 1:30; plain numbers count as minutes. :min, :max, :mean work on times.
X[X] if all children are checked.
X/, X%Count of checked children, as [n/m] or [n%].
@min, @max, @meanMinimum, maximum or average age of timestamps.
est+Combination of low-high estimates.

The est+ type needs a word of explanation. An estimate such as 2-4 says “between 2 and 4 days”. Adding the lower and upper bounds of many such ranges produces an interval that is far too wide, because it assumes that every task goes either perfectly or terribly. est+ instead adds up the mean and variance of each range, and reports the combined mean minus and plus one standard deviation, rounded to whole numbers. You can define further summary types in org-columns-summary-types. Summary types are ignored for special properties.

Summaries are recursive: Org computes the deepest level first and works upward, so a grandparent summarizes its children’s summaries.

When the parent heading already has the summarized property, Org does not just display the computed value: it overwrites the value in the parent’s drawer. In a batch test, a parent with :Effort: 1:00 and children with 2:00 and 0:30 had its drawer changed to :EFFORT: 2:30 after org-columns. Do not keep hand-written values in a parent for a property that the format summarizes.

Editing in column view

Column view is also an editor. With point on a field:

KeyCommandEffect
LEFT, RIGHT, UP, DOWNMove between fields.
S-RIGHT/n, S-LEFT/porg-columns-next-allowed-value, org-columns-previous-allowed-valueCycle through the allowed values.
1 to 9, 0Select the first to ninth allowed value, or the tenth with 0.
eorg-columns-edit-valueEdit the value; for special properties, the usual interface (such as tag selection) appears.
vorg-columns-show-valueShow the full value of a truncated field.
aorg-columns-edit-allowedEdit the list of allowed values.
C-c C-corg-columns-toggle-or-columns-quitToggle a checkbox, or quit column view.
<, >org-columns-narrow, org-columns-widenMake the column narrower or wider.
S-M-RIGHT, S-M-LEFTorg-columns-new, org-columns-deleteInsert or delete a column.
M-LEFT, M-RIGHTorg-columns-move-left, org-columns-move-rightMove the column.
M-UP, M-DOWNorg-columns-move-row-up, org-columns-move-row-downMove the row.

Allowed values (_ALL properties) make editing much faster here: with Owner_ALL defined as above, 1, 2 and 3 set the owner to Ana, Ben and Chen. Column view also works in the agenda, where it shows entries collected from many files (see Agenda Views).

Capturing column view in a dynamic block

Column view is an overlay, so it does not appear in exports or printouts. To keep a copy of the table in the document, insert a columnview dynamic block: a block between #+BEGIN: and #+END: lines whose contents Org regenerates on request. C-c C-x x (org-dynamic-block-insert-dblock) followed by columnview inserts one, and org-columns-insert-dblock does the same directly.

* Status table
#+BEGIN: columnview :id "release-3" :indent t :hlines 1
#+END:

With point on the #+BEGIN: line, C-c C-c or C-c C-x C-u (org-dblock-update) fills the block. A batch run on the release plan produced:

* Status table
#+BEGIN: columnview :id "release-3" :indent t :hlines 1
| <30>                   |      |       |        |          |       |
| ITEM                   | TODO | Owner | Effort | Estimate | Done  |
|------------------------+------+-------+--------+----------+-------|
| Release 3.0            |      |       |  10:45 |      4-6 | [2/3] |
| \_  Rewrite the parser | TODO | Ana   |   6:00 |      2-4 | [ ]   |
| \_  Port the CLI       | TODO | Ben   |   3:30 |      1-2 | [X]   |
| \_  Update the docs    | DONE | Chen  |   1:15 |    0.5-1 | [X]   |
#+END:

The parent row shows the summaries: the efforts add up to 10:45, 2 of 3 tasks are checked, and est+ combines the three ranges (whose plain sums would be 3.5 to 7) into 4 to 6. The first row holds the width cookie <30> that came from the %30ITEM definition.

flowchart LR
    C["COLUMNS property or #+COLUMNS"] -->|"format"| O["org-columns: live overlay"]
    P["properties in the subtree"] -->|"values"| O
    O -->|"edits"| P
    C -->|"format"| B["columnview block"]
    P -->|"values"| B
    B -->|"C-c C-c"| T["static Org table, exportable"]

Figure 9.5: The same column definition feeds 2 outputs: an editable overlay on the outline, and a dynamic block that freezes the current values into an ordinary table.

The parameters of the block decide what it captures:

ParameterMeaning
:idWhich tree: local (the tree containing the block), global (the whole file), file:NAME (another file), or the value of an ID property.
:matchA match string that selects a subset of the headlines.
:maxlevelIgnore entries deeper than this level.
:hlinest for a rule after every row, or a number N for a rule before each headline of level N or less.
:vlinesDraw vertical lines between column groups.
:indentIndent ITEM according to the outline level.
:linkMake each ITEM a link to its headline.
:skip-empty-rowsLeave out rows whose only value is ITEM.
:exclude-tagsLeave out entries with any of these tags.
:formatUse this column format instead of the one in effect.
:formatterA function that writes the table; the default comes from org-columns-dblock-formatter.

The :id value release-3 in the example refers to the ID property of the release headline; M-x org-id-copy creates such an identifier for the current entry and copies it (see Hyperlinks). Formulas in a #+TBLFM: line after the table survive updates, and Org recalculates them after each update (see The Spreadsheet and Plotting).

The command org-update-all-dblocks, bound to C-u C-c C-x C-u, refreshes every dynamic block in the file. Clock tables use the same block mechanism (see Clocking, Effort and Timers), and you can write your own block types in Lisp (see Hacking and Extending Org).

Choosing between tags and properties

Both mechanisms attach metadata to headlines, and many facts could be stored either way. The following rules of thumb work well:

Prefer tags whenPrefer properties when
The fact is a yes-or-no label (@office, urgent).The fact has a value (Owner: Ana, Points: 3).
It should be visible on the headline itself.It is detail that can stay folded in a drawer.
It should apply to all children automatically.It describes one entry, or you enable inheritance for it.
You filter the agenda by it often.You compare, sort or sum it (column view, numeric matches).

Remember also that a single match string can combine both, as in backend+Points>=3/!.

Summary

  • Tags are labels at the end of a headline; they are inherited down the tree and from #+FILETAGS:.
  • C-c C-q or C-c C-c sets tags; selection keys in #+TAGS: or org-tag-alist enable fast tag selection, and braces define mutually exclusive groups.
  • Group tags in square brackets build a hierarchy that searches expand automatically.
  • Properties are key-value pairs in a PROPERTIES drawer; _ALL lists allowed values, + appends, and #+PROPERTY: sets file-wide values.
  • Property inheritance is off by default and enabled per property with org-use-property-inheritance.
  • Special properties such as TODO, PRIORITY and ALLTAGS expose built-in metadata to searches and columns.
  • Match strings combine tags, properties and TODO keywords; starred operators require the property to exist.
  • Column view shows properties as an editable table with summaries, and a columnview dynamic block captures it in the document.

Further reading

Dates and Times

A task list without dates tells you what to do but not when. Org attaches dates to entries with a single, compact notation, the timestamp, and then uses those timestamps everywhere: the agenda (Org’s combined calendar and task list, built from your files) reads them to build your day, the clock writes them to record your work, and capture templates insert them to record when an idea arrived.

This chapter explains the timestamp syntax first, then the commands that create and edit timestamps without typing them by hand, then the 2 planning keywords DEADLINE and SCHEDULED, and finally repeating tasks. The agenda, which is where most of these dates become visible, has its own chapter: Agenda Views. Recording working time is covered in Clocking, Effort and Timers.

All examples in this chapter assume that “today” is Thursday, 19 November 2026. The agenda lines and edited entries shown below were produced by Org 9.8.13 running in Emacs batch mode with the clock set to that date.

The timestamp: one notation for every date

In Org, a timestamp is a date, optionally followed by a time or a time range, written in a fixed format between angle brackets or square brackets. The word is broader than in everyday programming, where a timestamp usually records when something was created or modified. In Org, a timestamp can mark an appointment, a deadline, a planned start, a logged event, or an interval of work.

The format follows ISO 8601 order (year, month, day) with a day name for readability:

<2026-11-19 Thu>
<2026-11-19 Thu 14:00>
<2026-11-19 Thu 14:00-15:00>

The day name is optional when you type a timestamp yourself, but Org adds it whenever it inserts or modifies one. You will rarely type a timestamp by hand, because the commands described in the next section produce the correct format for you and also let you edit it with the arrow keys.

Active and inactive timestamps

The bracket type decides whether a timestamp influences the agenda.

FormNameEffect on the agenda
<2026-11-19 Thu>active timestampThe entry is shown on that date.
[2026-11-19 Thu]inactive timestampThe entry is not shown. The date is only a record.

Use an active timestamp when the date is a commitment that you want to see in your calendar. Use an inactive timestamp when the date is history: when you created a note, when a meeting took place, when a bug was first observed. Org itself writes inactive timestamps for logging (state changes, clock lines, refile notes) so that years of records do not flood your agenda.

The following file contains one entry of each kind:

* Design review with the platform team
  <2026-11-19 Thu 14:00-15:00>
* Lunch with Ana
  [2026-11-19 Thu]

In the agenda for 19 November, only the design review appears. The lunch remains a dated note, which you can still find with a search.

Plain timestamps, ranges and repeaters

A timestamp that is not preceded by a planning keyword is a plain timestamp. It works like an entry in a paper diary: the headline is shown in the agenda on exactly that date and nowhere else. An entry may contain several plain timestamps, for example one for each day a recurring workshop takes place.

There are 2 ways to express duration:

  • A time range inside a single timestamp, written with one hyphen between 2 times: <2026-11-19 Thu 14:00-15:00>.
  • A date range, made of 2 timestamps joined by a double hyphen: <2026-11-11 Wed>--<2026-11-13 Fri>. The agenda shows the entry on every day of the range and labels it with its position, such as (2/3) on the second day.

A repeater is a suffix such as +1w that makes a timestamp recur. The letter selects the unit: h (hours), d (days), w (weeks), m (months) or y (years). The following entry appears in the agenda every Wednesday from its start date on:

* Pick up the children from school
  <2026-11-18 Wed 15:30 +1w>

Repeaters behave differently when they appear in a deadline or a scheduled date of a task, because then marking the task done moves the date. That case is covered in Repeating tasks below. Org never repeats inactive timestamps.

Diary-style expressions

Some dates cannot be expressed with a fixed interval: “the second Thursday of every month”, or “every year on a birthday”. For these, Org accepts a diary sexp, an Emacs Lisp expression from the Emacs calendar package, inside a timestamp. The form is <%%(EXPRESSION)>, optionally followed by a time:

* Team retrospective
  <%%(diary-float t 4 2) 16:00-17:00>
* Conference trip
  <2026-11-11 Wed>--<2026-11-13 Fri>
* Birthdays
%%(org-anniversary 1990 11 12) Maria Silva turns %d

(diary-float t 4 2) means “any month, weekday 4 (Thursday), the 2nd occurrence”. The last line shows a second form: a sexp at the very beginning of a line, outside any brackets, followed by text. This form is evaluated in the same way, and %d is replaced by the number of years. The agenda for Thursday, 12 November 2026, generated from this file, reads:

Day-agenda (W46):
Thursday   12 November 2026
  sexp:       16:00-17:00 Team retrospective
  sexp:       (2/3):  Conference trip
  sexp:       Maria Silva turns 36

The standard diary- functions read their date arguments in an order that depends on the variable calendar-date-style, which makes shared files fragile. Org provides org-date, org-anniversary, org-cyclic and org-block, which work like their diary counterparts but always take year, month and day in ISO order. Prefer them in Org files.

Diary sexps are powerful, but Org cannot reason about them as it does about ordinary dates. In particular, when a sexp is used in a deadline, Org shows the entry on each matching day but cannot issue early warnings, because it does not know when the next match will occur.

Creating and editing timestamps

Typing <2026-11-19 Thu 14:00> by hand is slow and error prone. Org offers a family of commands that prompt for a date, insert the timestamp in the correct format, and later adjust it in place.

Inserting a timestamp

KeyCommandPurpose
C-c .org-timestampPrompt for a date and insert an active timestamp. On an existing timestamp, edit it.
C-c !org-timestamp-inactiveSame, but insert an inactive timestamp.
C-u C-c .org-timestampInclude a time of day.
C-u C-u C-c .org-timestampInsert the current date and time without prompting.
C-c . twiceorg-timestampPressed again directly after insertion, create a date range.

When you use the prefix argument to include the current time, Org can round the minutes; the variable org-time-stamp-rounding-minutes controls this.

A pair of commands connects timestamps with the Emacs calendar. C-c > (org-goto-calendar) opens the calendar at the date of the timestamp on the current line, or at today. C-c < (org-date-from-calendar) works the other way: typed in the Org buffer, it inserts a timestamp for the date that is selected in the calendar window.

The date prompt

The date prompt is where Org saves you the most time. It looks as if it expects a full date, but it accepts fragments and fills in the rest from a default date, which is normally today (or the existing timestamp when you edit one). A small calendar opens at the same time, and the minibuffer shows how Org currently interprets your input.

Org assumes that you are planning ahead. If you type a day or a month that has already passed this year, it moves the date into the future (controlled by org-read-date-prefer-future). The following table shows real interpretations with today set to Thursday, 19 November 2026:

InputResultWhy
14<2026-12-14 Mon>Day 14 of this month has passed, so next month.
12<2026-12-12 Sat>Same rule.
fri<2026-11-20 Fri>The nearest Friday, today or later.
dec 3<2026-12-03 Thu>Month name and day.
2/5<2027-02-05 Fri>Month/day; February 5 has passed in 2026, so 2027.
w48<2026-11-23 Mon>ISO week 48 of the current year.
2027-01-15 9:00<2027-01-15 Fri 09:00>Full ISO date with time.
15:00<2026-11-19 Thu 15:00>A time alone means today.
11am-1:15pm<2026-11-19 Thu 11:00-13:15>A time range.
11am+2:15<2026-11-19 Thu 11:00-13:15>A start time plus a duration.

Relative dates are often even faster. Start the input with a sign, a number and a unit letter:

InputResultMeaning
+3d<2026-11-22 Sun>3 days from today.
+2w<2026-12-03 Thu>2 weeks from today.
+1m<2026-12-19 Sat>1 month from today.
+2tue<2026-12-01 Tue>The second Tuesday from today.
+2h<2026-11-19 Thu 12:30>2 hours from now (the run used 10:30).

A single sign (+3d) counts from today; a double sign (++3d) counts from the default date, which is useful when you edit an existing timestamp and want to move it relative to its current value. . or +0 means today.

The calendar can be controlled without leaving the minibuffer. S-LEFT and S-RIGHT move by one day, S-UP and S-DOWN by one week, M-S-LEFT and M-S-RIGHT by one month, and < and > scroll the calendar. RET accepts the date at point in the calendar, combined with whatever you typed. C-. jumps back to today.

There are 2 limits to keep in mind. The prompt understands English month and weekday abbreviations; to use full names or another language, set parse-time-months and parse-time-weekdays. And by default, Org restricts dates to the range 1970 to 2037, which every Emacs build can represent; the docstring of org-read-date-force-compatible-dates explains how to lift this restriction.

Changing a timestamp in place

Once a timestamp exists, you can adjust it with the shifted arrow keys while point is on it:

  • S-LEFT and S-RIGHT (org-timestamp-down-day, org-timestamp-up-day) move the date by one day.
  • S-UP and S-DOWN (org-timestamp-up, org-timestamp-down) change the component under point: year, month, day, hour or minute. On a bracket, they toggle between active and inactive.

If the timestamp contains a time range such as 14:00-15:00, changing the start time moves the end time too, so the length of the block stays the same. To change the length, edit the end time. Note that on a headline but outside a timestamp, the same keys change the priority of the entry; they also conflict with shift-selection; see Org Beyond the Basics for ways to resolve such conflicts with other packages.

The set is completed by 2 further commands:

  • C-c C-c on a timestamp normalizes it, for example by adding or correcting the day name after you typed a date by hand.
  • C-c C-y (org-evaluate-time-range) computes the length of a range. With a prefix argument, it inserts the result after the range.

Displaying dates in a different format

Org always stores ISO dates, because it needs one predictable format to parse. If you prefer to read dates differently, you can overlay a custom format: set org-display-custom-times to t and describe the format in org-timestamp-custom-formats, a pair of format-time-string patterns for dates without and with a time. C-c C-x C-t (org-toggle-timestamp-overlays) switches the overlay on and off.

(setq org-display-custom-times t)
(setq org-timestamp-custom-formats
      '("%d %b %Y %a" . "%d %b %Y %a %H:%M"))

The overlay changes only the display, which has side effects. Point can no longer enter the timestamp, so S-UP and S-DOWN cannot select individual components, and table columns that contain dates may lose alignment if the custom format is longer than the ISO one. For most users the ISO format becomes familiar quickly, and it sorts correctly as plain text.

Deadlines and scheduled dates

Plain timestamps describe events. Tasks need something different: a date by which the work must be finished, and a date on which you intend to start. Org expresses these with 2 planning keywords, DEADLINE and SCHEDULED, placed on the line directly below the headline (the planning line):

* TODO Submit the conference talk proposal
  DEADLINE: <2026-11-24 Tue>
* TODO Refactor the billing module
  SCHEDULED: <2026-11-17 Tue>

Do not put any other text between the headline and the planning line; Org only recognizes the keywords in that position. A task can carry both keywords on the same line.

The important difference from a plain timestamp is that both keywords make Org follow the entry over time. A plain timestamp appears on one day and is forgotten. A deadline warns you in advance and stays visible after the date has passed; a scheduled task reappears every day until you mark it done.

What a deadline means

A DEADLINE states that the task should be finished on that date. In the agenda for today, Org starts warning about the deadline org-deadline-warning-days days in advance (14 by default). On the due date the entry is labeled Deadline:, and after it the entry keeps appearing on today’s agenda with the number of days it is overdue, until you mark it done.

You can change the warning period for a single deadline by appending a negative offset to the timestamp. DEADLINE: <2026-11-30 Mon -3d> starts warning only 3 days in advance, which suits small tasks that do not need 2 weeks of reminders.

What scheduling means

A SCHEDULED date states when you plan to start working on a task. The agenda lists the entry on that date with the label Scheduled:. If the day passes and the task is still open, Org carries it forward: it appears on every following day as Sched.Nx:, where N counts the days since the scheduled date.

A common mistake is to schedule meetings. A meeting is an appointment at a fixed time; give it a plain timestamp. Scheduling in Org means “this is when I intend to begin”, and the carry-forward behavior only makes sense for work that remains to be done.

Sometimes you want to schedule a task but hide it for a few days. A negative offset on a scheduled date does that: SCHEDULED: <2026-11-18 Wed -2d> keeps the scheduled date on the 18th but only shows the task from the 20th. For a repeating timestamp, -2d delays every occurrence, while --2d delays only the first one. The global default for this delay is org-scheduled-delay-days.

Seeing the rules in the agenda

The following file combines the cases discussed so far. It was loaded into the agenda with 3 different “today” values.

* TODO Submit the conference talk proposal
  DEADLINE: <2026-11-24 Tue>
* TODO Renew the TLS certificate
  DEADLINE: <2026-11-30 Mon -3d>
* TODO Send the quarterly invoice
  DEADLINE: <2026-11-16 Mon>
* TODO Refactor the billing module
  SCHEDULED: <2026-11-17 Tue>
* TODO Review the hiring rubric
  SCHEDULED: <2026-11-18 Wed -2d>
* Design review with the platform team
  <2026-11-19 Thu 14:00-15:00>
* Lunch with Ana
  [2026-11-19 Thu]

On Thursday, 19 November:

Day-agenda (W47):
Thursday   19 November 2026
  plan:       14:00-15:00 Design review with the platform team
  plan:       Sched. 2x:  TODO Refactor the billing module
  plan:        3 d. ago:  TODO Send the quarterly invoice
  plan:       In   5 d.:  TODO Submit the conference talk proposal

On Friday, 20 November, the delayed review appears for the first time:

Day-agenda (W47):
Friday     20 November 2026
  plan:       Sched. 3x:  TODO Refactor the billing module
  plan:       Sched. 2x:  TODO Review the hiring rubric
  plan:        4 d. ago:  TODO Send the quarterly invoice
  plan:       In   4 d.:  TODO Submit the conference talk proposal

On Friday, 27 November, the certificate deadline enters its 3-day warning period:

Day-agenda (W48):
Friday     27 November 2026
  plan:       Sched.10x:  TODO Refactor the billing module
  plan:       Sched. 9x:  TODO Review the hiring rubric
  plan:       11 d. ago:  TODO Send the quarterly invoice
  plan:        3 d. ago:  TODO Submit the conference talk proposal
  plan:       In   3 d.:  TODO Renew the TLS certificate

The lunch never appears, because its timestamp is inactive. The design review appears only on the 19th, because a plain timestamp does not follow you. The deadline on the 24th was first announced on 10 November (In 14 d.:), exactly 14 days before; on the 9th it was not yet listed.

Figure 10.1: Warning periods appear before a deadline, delays postpone a scheduled task, and both kinds of entry stay on today’s agenda until the task is done.

Several variables refine this behavior. org-agenda-skip-deadline-prewarning-if-scheduled suppresses the early warning for a task that is already scheduled, on the reasoning that you have planned when to do it. org-agenda-skip-scheduled-delay-if-deadline ignores the scheduled delay when the task also has a deadline. org-agenda-skip-scheduled-if-done hides scheduled entries on their date once they are done. The agenda chapter explains how to apply such settings to individual views.

Commands for deadlines and scheduling

KeyCommandPurpose
C-c C-dorg-deadlineInsert or change the deadline. With C-u, remove it.
C-c C-sorg-scheduleInsert or change the scheduled date. With C-u, remove it.
C-c / dorg-check-deadlinesShow a sparse tree of deadlines that are overdue or within the warning period.
C-c / borg-check-before-dateSparse tree of deadlines and scheduled dates before a given date.
C-c / aorg-check-after-dateSparse tree of deadlines and scheduled dates after a given date.

C-c C-d and C-c C-s use the same date prompt as C-c ., so relative input works: +1d schedules a task for tomorrow, and ++1w moves an existing date one week later than its current value. Both commands write the planning line directly below the headline and remove any CLOSED timestamp, since a task with a new date is evidently not closed.

When you move a date that was already set, Org can record the change. The variables org-log-reschedule and org-log-redeadline (both nil by default) can be set to time to log a timestamp or to note to ask for a short explanation. The same choices exist as #+STARTUP options per file: logreschedule, lognotereschedule, nologreschedule, and logredeadline, lognoteredeadline, nologredeadline. A history of postponements is useful during a review, because a task that has been rescheduled 6 times is probably not the right task.

C-c / d takes a numeric prefix to change the horizon. C-1 C-c / d shows the deadlines due by tomorrow; C-u C-c / d shows every deadline in the file. A sparse tree is a view of the outline that shows only the matching entries and the headings above them; it is introduced in Document Structure.

Repeating tasks

Many tasks return: paying the rent, renewing a certificate, writing a weekly report. Creating a new entry each time would be tedious, and a plain repeating timestamp does not help, because a task needs to be marked done. Org solves this with a repeater on the DEADLINE or SCHEDULED timestamp.

* TODO Pay the rent
  DEADLINE: <2026-10-01 Thu +1m>

When you mark this task done with C-c C-t, Org does not leave it in the DONE state. It moves the timestamp forward by the repeater interval and immediately sets the task back to its open state, so the next occurrence is ready. A record of the completion is kept in the entry.

flowchart LR
  A["TODO with repeater"] -->|"C-c C-t DONE"| B["Shift date by interval"]
  B --> C["Set LAST_REPEAT property"]
  C --> D["Log the state change"]
  D -->|"state reset"| A

Figure 10.2: Marking a repeating task done records the completion and returns the same entry to an open state with its next date.

The state that the task returns to is, in order of precedence: the REPEAT_TO_STATE property of the entry (a property is a key-value pair stored in the PROPERTIES drawer, a folded block between :PROPERTIES: and :END: below the headline), the value of org-todo-repeat-to-state if it is a string, the previous state if that variable is t, and otherwise the first state of the TODO sequence. If an entry contains several repeating timestamps, all of them are shifted. To close a repeating task for good, use C-- 1 C-c C-t (a numeric prefix of -1), which marks it done without repeating.

3 kinds of repeater

The repeater +1m shifts the date by exactly one interval, starting from the old date. That is correct for the rent: if you are 3 months behind, you owe 3 payments, and the task should stay overdue. For other tasks, catching up makes no sense. If you forgot to call a relative for 3 weeks, you do not want to call 3 times in one day. And some tasks should recur a fixed interval after you last did them, wherever the calendar stood.

Org has a repeater type for each of these situations:

RepeaterNext date after marking doneTypical use
+1mOld date plus exactly 1 interval, even if that is still in the past.Obligations that accumulate: rent, invoices.
++1wOld date plus as many intervals as needed to reach the future; the weekday is preserved.Habits tied to a day: a weekly call on Sunday.
.+1mToday plus 1 interval.Maintenance relative to the last action: replacing a filter.

The following file was marked done with C-c C-t on Thursday, 19 November 2026 at 10:30:

* TODO Pay the rent
  DEADLINE: <2026-10-01 Thu +1m>
* TODO Call Mother
  SCHEDULED: <2026-10-25 Sun ++1w>
* TODO Replace the water filter
  SCHEDULED: <2026-09-01 Tue .+1m>

Org produced this result:

* TODO Pay the rent
  DEADLINE: <2026-11-01 Sun +1m>
  :PROPERTIES:
  :LAST_REPEAT: [2026-11-19 Thu 10:30]
  :END:
  - State "DONE"       from "TODO"       [2026-11-19 Thu 10:30]
* TODO Call Mother
  SCHEDULED: <2026-11-22 Sun ++1w>
  :PROPERTIES:
  :LAST_REPEAT: [2026-11-19 Thu 10:30]
  :END:
  - State "DONE"       from "TODO"       [2026-11-19 Thu 10:30]
* TODO Replace the water filter
  SCHEDULED: <2026-12-19 Sat .+1m>
  :PROPERTIES:
  :LAST_REPEAT: [2026-11-19 Thu 10:30]
  :END:
  - State "DONE"       from "TODO"       [2026-11-19 Thu 10:30]

Read the 3 dates carefully. The rent moved by one month, from 1 October to 1 November, and is therefore still overdue: one payment is still missing. The call moved from 25 October in whole weeks until it reached the future and landed on Sunday, 22 November. The filter moved to exactly one month after the day of completion.

For repeaters counted in days, weeks, months or years, Org compares whole days and ignores the time of day. A task with DEADLINE: <2026-11-15 Sun 20:00 ++1d>, marked done at 10:30 on 19 November, moved to <2026-11-20 Fri 20:00 ++1d>: the next occurrence is always after today, even though 20:00 today was still ahead. (The manual describes the same-day case differently; the result above is what Org 9.8.13 does.) Only hourly repeaters look at the clock: .+1h sets the next occurrence one hour after the moment you finish, and ++1h moves forward in whole hours until the time is in the future.

You can combine a repeater with a warning period on a deadline. The repeater must come first: DEADLINE: <2026-12-01 Tue +1m -3d>.

flowchart TD
  Q1{"Does every missed occurrence still need doing?"} -->|yes| P["+ : fixed steps from the old date"]
  Q1 -->|no| Q2{"Must it stay on the same weekday or time?"}
  Q2 -->|yes| PP["++ : jump forward to the next future slot"]
  Q2 -->|no| DP[".+ : count from the day you finish"]

Figure 10.3: Choose the repeater by asking whether missed occurrences matter and whether the calendar position matters.

Logging repetitions

Each completion adds the LAST_REPEAT property and, by default, a line with the state change and the time. This is governed by org-log-repeat, whose default value time records a timestamp; note also asks for a note, and nil records nothing. The #+STARTUP options logrepeat, lognoterepeat and nologrepeat set the same behavior per file. If the log lines clutter your entries, set org-log-into-drawer to t so that they go into a LOGBOOK drawer (the same drawer the clock uses, see Clocking, Effort and Timers). State logging in general is described in TODO Items, which also covers habits, a special kind of repeating task with a consistency graph.

Mixing scheduled and deadline repeaters

A task can have both a scheduled date and a deadline. If only the scheduled date repeats, you may want the repetitions to stop after the deadline; set org-agenda-skip-scheduled-repeats-after-deadline to t. A scheduled date without a repeater is removed when a repeating task is marked done, because it referred only to the occurrence you have just finished. If both dates should advance together, give both the same repeater.

Copies instead of repeaters

A repeater keeps a single entry and moves its date. Sometimes you want separate entries instead, for example one entry per session of a 6-week course, each with its own notes. C-c C-x c (org-clone-subtree-with-time-shift) creates a number of copies of the current subtree (the heading with everything below it) and shifts the timestamps in each copy by an interval that you specify. This is described with the other structure-editing commands in Document Structure.

Choosing the right kind of date

The rules above lead to a short set of guidelines that work for most task systems:

SituationUse
A meeting, a call, a flightPlain active timestamp, with a time.
A note about when something happenedInactive timestamp.
Work that must be finished by a dateDEADLINE, with a shorter warning period for small tasks.
Work you intend to start on a dateSCHEDULED, with a delay if you want it hidden until later.
Recurring obligationRepeater on the planning timestamp, +, ++ or .+ as in Figure 10.3.
Irregular calendar rulesDiary sexp such as org-anniversary or diary-float.

Keep deadlines for real deadlines. If every task carries one, the warnings lose their meaning, and the agenda becomes a wall of red. The weekly review described in Putting It Together is a good moment to check that scheduled dates are still realistic.

Further reading

Clocking, Effort and Timers

Planning tells you what you intend to do; a record of time tells you what actually happened. Org can measure the time you spend on each task, store the measurements in the task itself, and summarize them in reports. Combined with effort estimates (the expected duration of a task), these records let you compare plans with reality and improve your estimates over time.

This chapter covers 3 related tools. Clocking records intervals of work on a headline (the title line of an entry, starting with stars). The clock table turns those records into reports. Timers measure time without attaching it to a task, which is useful for meeting notes or for a focused work session.

The timestamps used throughout are those introduced in Dates and Times. The outputs in this chapter were produced by Org 9.8.13 in Emacs batch mode, with the clock set to Thursday, 19 November 2026.

How clocking works

When you clock in on a task, Org writes a CLOCK: line with an inactive timestamp into that task. When you clock out, it completes the line with the end time and the duration. Each completed line is a clock entry, and the collection of clock entries in a subtree (a heading together with everything below it) is all the information Org needs to compute totals.

Here is a task before clocking:

* TODO Fresh task

After C-c C-x C-i (org-clock-in) at 09:00:

* TODO Fresh task
:LOGBOOK:
CLOCK: [2026-11-19 Thu 09:00]
:END:

After C-c C-x C-o (org-clock-out) at 10:47:

* TODO Fresh task
:LOGBOOK:
CLOCK: [2026-11-19 Thu 09:00]--[2026-11-19 Thu 10:47] =>  1:47
:END:

The clock lines are kept in a drawer, a named block between :NAME: and :END: that Org folds away by default. The clock uses the LOGBOOK drawer. With the default value of org-clock-into-drawer (t), even the first clock line goes into the drawer, as above. You can choose a different drawer name or a threshold number of lines through this variable, and override it for a subtree with the CLOCK_INTO_DRAWER or LOG_INTO_DRAWER property (a property is a key-value pair stored in the PROPERTIES drawer of an entry). State-change notes go into the same drawer when org-log-into-drawer is set (see TODO Items).

New clock lines are added at the top of the drawer, so the most recent work comes first. After a second session on the same task, the drawer looks like this:

* TODO Write the migration script
  :LOGBOOK:
  CLOCK: [2026-11-19 Thu 09:00]--[2026-11-19 Thu 10:47] =>  1:47
  CLOCK: [2026-11-18 Wed 14:00]--[2026-11-18 Wed 15:30] =>  1:30
  :END:

Only one clock at a time

Org runs a single clock. If you clock in on a second task while the first is running, Org clocks out of the first task at that moment. This makes switching tasks a one-key operation and guarantees that no time is counted twice. In the following run, the review was clocked in at 09:00, the ticket at 09:40 (which stopped the review), and the clock was stopped at 10:05:

* TODO Review pull request 418
:LOGBOOK:
CLOCK: [2026-11-19 Thu 09:00]--[2026-11-19 Thu 09:40] =>  0:40
:END:
* TODO Answer support ticket
:LOGBOOK:
CLOCK: [2026-11-19 Thu 09:40]--[2026-11-19 Thu 10:05] =>  0:25
:END:

Org also remembers which task was interrupted. Capture uses this to resume the previous clock after you have filed a quick note (see Capture, Refile, Archive and Attachments).

Marking the clocked task as done with C-c C-t stops the clock as well, provided org-clock-out-when-done keeps its default value t.

Totals are computed, not stored

Org never stores a total. Whenever a total is needed, it adds up the clock entries in a subtree, so a parent heading’s total always includes the time of all its children. This design has a practical consequence: you can correct a clock line by hand, move subtrees around, or archive finished tasks, and every report computed afterwards reflects the change.

flowchart LR
  K["C-c C-x C-i / C-o"] -->|"writes CLOCK lines"| L["LOGBOOK drawer"]
  L -->|"summed per subtree"| S["Clock sums"]
  S -->|"current task total"| M["Mode line"]
  S -->|"C-c C-x C-d"| O["Overlays on headlines"]
  S -->|"C-c C-c on BEGIN line"| T["Clocktable block"]
  S -->|"R in the agenda"| A["Agenda clock report"]
  S -->|"CLOCKSUM column"| C["Column view"]

Figure 11.1: Clock lines are the only stored data; every display of clocked time is computed from them on demand.

The clocking commands

The commands below are available in any Org buffer. The most important ones, clocking in and out, are worth binding globally if you clock often.

KeyCommandPurpose
C-c C-x C-iorg-clock-inStart the clock on the current entry.
C-c C-x C-oorg-clock-outStop the clock.
C-c C-x C-xorg-clock-in-lastClock in again on the last clocked task.
C-c C-x C-qorg-clock-cancelRemove the running clock line, for a clock started by mistake.
C-c C-x C-jorg-clock-gotoJump to the task that is being clocked.
C-c C-x C-dorg-clock-displayShow the total time of each subtree as overlays.
C-c C-x C-zorg-resolve-clocksLook for open clocks and resolve them.
C-c C-x C-eorg-clock-modify-effort-estimateChange the effort of the clocked task.

Clocking in

org-clock-in accepts prefix arguments that change where it clocks in:

  • C-u C-c C-x C-i offers a menu of recently clocked tasks. The number of tasks remembered is org-clock-history-length (5 by default).
  • C-u C-u C-c C-x C-i clocks in on the current task and marks it as the default task. The default task is always available under the key d in the selection menu, which makes it a convenient place for general time, such as “Email and admin”.
  • C-u C-u C-u C-c C-x C-i starts the clock at the moment the previous clock stopped, so that the gap between the 2 tasks is attributed to the new one. This is called continuous clocking.

While the clock runs, the mode line shows the task and the time spent on it. If the task has an effort estimate, the mode line shows the clocked time against that estimate. What counts as “the time spent” is set by org-clock-mode-line-total: current (only this session), today, repeat (since the last repetition of a repeating task), all, or auto, the default, which uses repeat for repeating tasks and all otherwise. The CLOCK_MODELINE_TOTAL property overrides the variable for one task.

The variable org-clock-in-switch-to-state changes the TODO state of a task when you clock in, for example from TODO to STARTED. Its value is a state name or a function that receives the current state and returns the new one.

(setq org-clock-in-switch-to-state "STARTED")

If you use this setting, make sure that STARTED is one of your TODO keywords (see TODO Items).

Clocking out and correcting entries

org-clock-out completes the running clock line and computes the duration. If you want to record what you achieved, set org-log-note-clock-out to t (or use #+STARTUP: lognoteclock-out), and Org will ask for a short note. Very short sessions can be discarded automatically with org-clock-out-remove-zero-time-clocks.

Clock lines are ordinary text. When you notice that you forgot to clock out before lunch, open the drawer and change the end time. If you edit a timestamp by typing, press C-c C-c (or C-c C-y) on the line to recompute the duration; if you change it with S-UP and S-DOWN, the duration updates by itself. Another 2 keys help with adjacent entries:

  • C-S-UP and C-S-DOWN (org-clock-timestamps-up, org-clock-timestamps-down) shift both timestamps of a clock line, keeping its duration.
  • S-M-UP and S-M-DOWN change the timestamp at point and also the touching timestamp of the previous or next clock line, so that 2 consecutive sessions stay contiguous. This only applies to clock lines created in the current Emacs session.

Keeping the clock across Emacs sessions

By default, Org forgets the clock history and any running clock when Emacs exits. The following configuration saves both and restores them at the next start:

(setq org-clock-persist t)
(org-clock-persistence-insinuate)

With the value history, only the list of recent tasks is saved; with clock, only the running clock. When a clock is restored, Org treats the interval while Emacs was closed as time to be resolved, as described below.

Resolving idle and lost time

A clock measures wall time, not attention. If you clock in and then leave your desk for an hour, the record is wrong. Org offers 3 mechanisms to keep the record honest.

Idle detection

Set org-clock-idle-time to a number of minutes. When you return after being idle for longer than that while a clock is running, Org asks what to do with the idle period:

KeyEffect
kKeep some or all of the idle minutes and continue clocking.
KKeep the minutes you specify, then clock out.
sSubtract the idle time and continue clocking from now.
SSubtract the idle time and clock out at the moment you became idle.
CCancel the clock entirely.

The uppercase variants always leave you clocked out. If you subtract time and then immediately clock in on another task, Org offers to assign the subtracted minutes to that task, which is exactly what you want when an interruption turned out to be work on something else.

How Org measures idleness depends on the system. On macOS, it uses the real user idle time. On X11, it can use an external program configured in org-clock-x11idle-program-name (such as xprintidle). Elsewhere, it measures only how long Emacs itself has been idle.

(setq org-clock-idle-time 15)

Dangling clocks

If Emacs crashes or is killed while a clock runs, the task is left with an open CLOCK: line. The next time you clock in, Org notices this dangling clock and asks how to resolve the time since it started, with the same choices as for idle time. You can also check all agenda files for open clocks at any moment with C-c C-x C-z (org-resolve-clocks).

Automatic clock-out

If you often forget to clock out before you leave, let Org do it. Set org-clock-auto-clockout-timer to a number of seconds and activate the feature:

(setq org-clock-auto-clockout-timer 1800)
(org-clock-auto-clockout-insinuate)

After 30 minutes of Emacs idle time, the clock stops. M-x org-clock-toggle-auto-clockout switches the feature on and off for the current session.

stateDiagram-v2
  [*] --> Stopped
  Stopped --> Running: clock in
  Running --> Running: clock in elsewhere (old clock closed)
  Running --> Stopped: clock out, DONE, cancel
  Running --> Resolving: idle longer than org-clock-idle-time
  Resolving --> Running: k or s
  Resolving --> Stopped: K, S or C
  Running --> Stopped: auto clock-out timer

Figure 11.2: A running clock leaves its state only through an explicit command, a state change to DONE, or one of the idle mechanisms.

Clock tables

A clock table is a report of clocked time, written into the buffer as an Org table. It is a dynamic block: a region between #+BEGIN: and #+END: whose content Org regenerates from the parameters on the #+BEGIN: line. Dynamic blocks in general are introduced in Tags, Properties and Column View.

Inserting and updating

Use C-c C-x x (org-dynamic-block-insert-dblock) and choose clocktable, or call M-x org-clock-report directly. Org inserts a block and fills it:

#+BEGIN: clocktable :maxlevel 2 :scope file
#+END:

To refresh the report, put point on the #+BEGIN: line and press C-c C-c or C-c C-x C-u (org-dblock-update). C-u C-c C-x C-u updates every dynamic block in the buffer. With point on the #+BEGIN: line, S-LEFT and S-RIGHT (org-clocktable-try-shift) move a :block period backwards or forwards, for example from today to today-1, and update the table.

A sample project

The following file records a week of work on a website. Its clock lines will be used for all reports in this section.

#+TITLE: Website relaunch

* Design
** DONE Wireframes
   :PROPERTIES:
   :Effort:   3:00
   :END:
   :LOGBOOK:
   CLOCK: [2026-11-16 Mon 09:00]--[2026-11-16 Mon 11:30] =>  2:30
   CLOCK: [2026-11-17 Tue 13:00]--[2026-11-17 Tue 14:15] =>  1:15
   :END:
** TODO Color palette                                               :client:
   :PROPERTIES:
   :Effort:   1:00
   :END:
   :LOGBOOK:
   CLOCK: [2026-11-18 Wed 10:00]--[2026-11-18 Wed 10:40] =>  0:40
   :END:
* Development
** TODO Content API
   :PROPERTIES:
   :Effort:   6:00
   :END:
   :LOGBOOK:
   CLOCK: [2026-11-17 Tue 09:00]--[2026-11-17 Tue 12:00] =>  3:00
   CLOCK: [2026-11-18 Wed 13:00]--[2026-11-18 Wed 16:30] =>  3:30
   :END:
** TODO Deployment pipeline
   :PROPERTIES:
   :Effort:   2:00
   :END:
   :LOGBOOK:
   CLOCK: [2026-11-19 Thu 08:00]--[2026-11-19 Thu 09:00] =>  1:00
   :END:

A basic report of the whole file, 2 levels deep:

#+BEGIN: clocktable :scope file :maxlevel 2
#+CAPTION: Clock summary at [2026-11-19 Thu 09:27]
| Headline                |    Time |      |
|-------------------------+---------+------|
| *Total time*            | *11:55* |      |
|-------------------------+---------+------|
| Design                  |    4:25 |      |
| \_  Wireframes          |         | 3:45 |
| \_  Color palette       |         | 0:40 |
| Development             |    7:30 |      |
| \_  Content API         |         | 6:30 |
| \_  Deployment pipeline |         | 1:00 |
#+END:

Each level has its own time column, so you can read the level 1 totals at a glance and the details on the right. TODO keywords are removed from the headlines. Clocks below :maxlevel are not lost; they are added to their nearest ancestor that is shown.

Choosing what to count

The parameters on the #+BEGIN: line fall into 2 groups: those that select clock entries and those that shape the table. Defaults for all of them can be set in org-clocktable-defaults.

flowchart LR
  F["Org files"] -->|":scope"| E["Entries in scope"]
  E -->|":match tag/property query"| E2["Matching entries"]
  E2 -->|":block or :tstart/:tend"| C["Clock entries in the period"]
  C -->|":step"| P["One table per day, week, ..."]
  C --> T["Table layout: :maxlevel, :properties, :tags, :formula"]
  P --> T
  T -->|":formatter"| OUT["Inserted table"]

Figure 11.3: A clock table first narrows files, entries and time, then formats what remains.

:scope decides which text is examined:

ValueScope
nilThe current buffer, respecting narrowing.
fileThe whole current buffer.
subtreeThe subtree that contains the clock table.
tree or treeNThe surrounding level 1 tree, or level N tree.
agendaAll agenda files.
("a.org" "b.org")An explicit list of files.
file-with-archives, agenda-with-archivesAs above, plus the archive files.

A function that returns a list of files is also accepted. Including archives matters if you archive finished tasks before writing a monthly report: archived clock lines still count, but only when the scope includes the archive files (see Capture, Refile, Archive and Attachments).

:block selects a period by name. Absolute forms are 2026-11-19, 2026-11, 2026-W47, 2026-Q4 and 2026. Relative forms are today, yesterday, thisweek, lastweek, thismonth, lastmonth, thisyear, lastyear, the numbered variants such as today-2 or thisweek-1, and untilnow. For an arbitrary interval, use :tstart and :tend with timestamps or relative expressions such as "<-1w>" and "<now>". Without either option, Org uses org-clock-display-default-range, which is the current year by default.

The following report covers 18 November, with an explicit start and end:

#+BEGIN: clocktable :scope file :maxlevel 2 :tstart "<2026-11-18 Wed>" :tend "<2026-11-19 Thu>"
#+CAPTION: Clock summary at [2026-11-19 Thu 09:33]
| Headline          |   Time |      |
|-------------------+--------+------|
| *Total time*      | *4:10* |      |
|-------------------+--------+------|
| Design            |   0:40 |      |
| \_  Color palette |        | 0:40 |
| Development       |   3:30 |      |
| \_  Content API   |        | 3:30 |
#+END:

:match restricts the report to entries that satisfy a query on tags (short labels at the end of a headline, such as :client:) and properties, using the syntax described in Tags, Properties and Column View. This is how you bill a client for the work tagged with their name:

#+BEGIN: clocktable :scope file :maxlevel 2 :match "client"
#+CAPTION: Clock summary at [2026-11-19 Thu 09:27]
| Headline          | Time   |      |
|-------------------+--------+------|
| *Total time*      | *0:40* |      |
|-------------------+--------+------|
| Design            | 0:40   |      |
| \_  Color palette |        | 0:40 |
#+END:

Splitting a period into steps

:step divides the period into days, weeks, semimonths, months, quarters or years and produces one table per step. It requires :block or :tstart and :tend. :stepskip0 omits empty steps, and :wstart and :mstart set the first day of a week (1 is Monday) and of a month. This is a convenient timesheet:

#+BEGIN: clocktable :scope file :maxlevel 1 :block thisweek :step day :stepskip0 t

Daily report: [2026-11-16 Mon]
| Headline     | Time   |
|--------------+--------|
| *Total time* | *2:30* |
|--------------+--------|
| Design       | 2:30   |

Daily report: [2026-11-17 Tue]
| Headline     |   Time |
|--------------+--------|
| *Total time* | *4:15* |
|--------------+--------|
| Design       |   1:15 |
| Development  |   3:00 |

Daily report: [2026-11-18 Wed]
| Headline     |   Time |
|--------------+--------|
| *Total time* | *4:10* |
|--------------+--------|
| Design       |   0:40 |
| Development  |   3:30 |

Daily report: [2026-11-19 Thu]
| Headline     | Time   |
|--------------+--------|
| *Total time* | *1:00* |
|--------------+--------|
| Development  | 1:00   |

#+END:

Shaping the table

The remaining parameters control the layout. These are the most useful ones:

ParameterEffect
:maxlevelDeepest heading level listed.
:linkTurn headlines into links to their entries.
:tagsAdd a column with the tags of each headline.
:propertiesAdd one column per listed property, for example ("Effort").
:inherit-propsUse inherited values for :properties.
:timestampAdd the entry’s scheduled, deadline or other timestamp.
:level, :indentShow a level column, or indent headlines by level.
:tcolumnsNumber of time columns; lower levels are combined.
:narrowTruncate the headline column, for example 40!.
:compactShorthand for :level nil :indent t :narrow 40! :tcolumns 1.
:emphasizeEmphasize level 1 and 2 entries.
:formulaA TBLFM formula added to the table; % adds a percentage column.
:sortSort by a column, such as (1 . ?a) for alphabetical order.
:fileskip0, :hidefiles, :filetitleControl file sections in multi-file reports.

A percentage column shows where the time went:

#+BEGIN: clocktable :scope file :maxlevel 2 :formula %
#+CAPTION: Clock summary at [2026-11-19 Thu 09:27]
| Headline                |    Time |      |     % |
|-------------------------+---------+------+-------|
| *Total time*            | *11:55* |      | 100.0 |
|-------------------------+---------+------+-------|
| Design                  |    4:25 |      |  37.1 |
| \_  Wireframes          |         | 3:45 |  31.5 |
| \_  Color palette       |         | 0:40 |   5.6 |
| Development             |    7:30 |      |  62.9 |
| \_  Content API         |         | 6:30 |  54.5 |
| \_  Deployment pipeline |         | 1:00 |   8.4 |
#+END:

Listing the Effort property next to the clocked time turns the report into a planning review. The :tags column shows which entry belongs to the client:

#+BEGIN: clocktable :scope file :maxlevel 2 :properties ("Effort") :tags t
#+CAPTION: Clock summary at [2026-11-19 Thu 09:27]
| Tags   | Effort | Headline                |    Time |      |
|--------+--------+-------------------------+---------+------|
|        |        | *Total time*            | *11:55* |      |
|--------+--------+-------------------------+---------+------|
|        |        | Design                  |    4:25 |      |
|        |   3:00 | \_  Wireframes          |         | 3:45 |
| client |   1:00 | \_  Color palette       |         | 0:40 |
|        |        | Development             |    7:30 |      |
|        |   6:00 | \_  Content API         |         | 6:30 |
|        |   2:00 | \_  Deployment pipeline |         | 1:00 |
#+END:

The wireframes took 45 minutes longer than estimated, and the Content API has already used 6:30 of its 6:00 although it is still open. The color palette and the deployment pipeline are within their estimates so far. If you write your own formula below the table instead of using :formula, it survives updates and is recalculated each time; formulas are explained in The Spreadsheet and Plotting.

When none of the built-in layouts fits, :formatter names a function that receives the collected clock data and inserts whatever it wants. The default formatter is org-clocktable-write-default, and its source is the best starting point for a custom one.

Clock reports in the agenda

The agenda, the overview of dated and open tasks that Org builds from your files, can show the same report below a daily or weekly view. Press R (org-agenda-clockreport-mode) to toggle it; the parameters come from org-agenda-clockreport-parameter-plist. l (org-agenda-log-mode) adds the clocked intervals and closed tasks of each day to the agenda itself. From the agenda you can also clock in and out with I and O. See Agenda Views for details.

Effort estimates

An effort estimate is the time you expect a task to take, stored in the Effort property (the name is set by org-effort-property). Estimates make 2 things possible: you can see whether a day’s plan fits into the available hours, and after the work you can compare the estimate with the clocked time.

Durations are written in the format of org-duration.el, which accepts several notations. The table below shows how Org reads some inputs, as computed by org-duration-to-minutes and printed back with org-duration-from-minutes:

InputMinutesPrinted as
0:45450:45
1:30901:30
2h1202:00
1d3h5min16251d 3:05
3d43203d 0:00

The units come from org-duration-units. By default a day (d) is 24 hours, not a working day, so 3d means 72 hours.

Setting estimates

KeyCommandPurpose
C-c C-x eorg-set-effortSet the effort of the current entry.
C-c C-x Eorg-inc-effortChange the effort to the next allowed value.
C-c C-x C-eorg-clock-modify-effort-estimateChange the effort of the clocked task.
e (agenda)org-agenda-set-effortSet the effort from the agenda.

The command is fast when the allowed values are fixed. Declare them in an Effort_ALL property, either per file or globally:

#+PROPERTY: Effort_ALL 0 0:10 0:30 1:00 2:00 3:00 4:00 6:00
#+COLUMNS: %40ITEM(Task) %17Effort(Estimated Effort){:} %CLOCKSUM
(setq org-global-properties
      '(("Effort_ALL" . "0 0:10 0:30 1:00 2:00 3:00 4:00 6:00")))
(setq org-columns-default-format
      "%40ITEM(Task) %17Effort(Estimated Effort){:} %CLOCKSUM")

The #+COLUMNS: line is for column view, a table-like overlay of properties on top of the outline, described in Tags, Properties and Column View. With this format, column view shows each task’s estimate, sums the estimates up the hierarchy (the {:} operator), and puts the clocked time next to it. In column view, S-LEFT and S-RIGHT cycle through the allowed values, which makes estimating a whole project a matter of a few keystrokes.

Using estimates in planning

When a clocked task has an estimate, the mode line shows the clocked time against it, so you notice when you exceed the plan while you are still working. In the agenda, column view sums the estimates of each day, and org-agenda-columns-add-appointments-to-effort-sum adds timed appointments to that sum, giving a picture of how much of the day is already committed. The agenda can also filter entries by effort with _ (org-agenda-filter-by-effort), for example to show only tasks that fit into the 30 minutes before a meeting.

The clock table with :properties ("Effort") shown earlier closes the loop. A habit of comparing the 2 columns during a weekly review (see Putting It Together) improves estimates faster than any rule of thumb.

Timers

Sometimes you need to measure time without assigning it to a task. Org provides 2 timers: a relative timer that counts up from zero and a countdown timer that counts down from a given duration. Neither writes CLOCK lines.

The relative timer

The relative timer is designed for notes taken while something unfolds: a meeting, a recorded talk, an incident review. Each note is stamped with the elapsed time, so you can later find the corresponding point in a recording.

KeyCommandPurpose
C-c C-x 0org-timer-startStart or reset the timer at 0. With C-u, start from an offset.
C-c C-x .org-timerInsert the current timer value.
C-c C-x -org-timer-itemInsert a list item stamped with the timer value.
M-RETorg-insert-headingIn a timer list, insert the next stamped item.
C-c C-x ,org-timer-pause-or-continuePause or resume.
C-c C-x _org-timer-stopStop the timer and remove it from the mode line.

A batch run that started the timer at 15:00 and inserted items 5 seconds, 5 minutes 17 seconds and 20 minutes 22 seconds later produced:

* Notes from the incident review
- 0:00:05 :: Timeline walkthrough begins
- 0:05:17 :: Root cause: expired credentials in the job runner
- 0:20:22 :: Action items assigned

The items are description list items (see Document Structure). If you started the timer too late, mark the region and use C-u C-u C-c C-x 0 to shift all timer values in it by a fixed amount. After a break, C-u C-c C-x 0 asks for a starting offset and proposes the timer value at point, so you can continue your notes from where you stopped.

The countdown timer

C-c C-x ; (org-timer-set-timer) asks for a duration and starts a countdown; the default duration comes from org-timer-default-timer, and a numeric prefix argument overrides it. In the agenda, the same command is on ;. When the countdown ends, Org shows a notification and runs org-timer-done-hook. Pause, resume and stop work with the same keys as for the relative timer.

A countdown is useful for time-boxed work: set it to 25 minutes, clock in on the task you want to focus on, and stop both when the timer rings. The clock records the work; the timer only tells you when to stop.

Putting the pieces together

The features in this chapter support a simple daily routine:

  1. In the morning, look at the agenda with column view to check that the estimates of the day’s tasks fit the available time.
  2. Clock in on each task as you start it; switching tasks is a single clock-in.
  3. Let idle detection and automatic clock-out catch interruptions and forgotten clocks.
  4. At the end of the week, update a clock table with :block lastweek, :properties ("Effort") and, if you work for several clients, one table per :match.

The data stays in your files as plain text, so the same records can feed an invoice, a retrospective, or a correction of next month’s estimates.

Further reading

Capture, Refile, Archive and Attachments

A task system is only as good as its input. Ideas, requests and reminders arrive while you are busy with something else, and if recording them takes more than a few seconds, they get lost or they break your concentration. Once recorded, they need to move to the place where they belong, and when they are finished, they need to get out of the way.

Org supports this whole path with 4 features. Capture records a new item quickly, from anywhere in Emacs, using a template. Refile moves an entry under another heading, in the same file or in another one. Archiving moves finished work out of your active files. Attachments connect files on disk to an entry. This chapter explains each feature and how they fit together.

The file contents shown in this chapter were produced by Org 9.8.13 in Emacs batch mode, on Thursday, 19 November 2026, in a home directory with an ~/org/ folder.

flowchart LR
  I(["Idea, email, request"]) -->|"capture: C-c c"| X["Inbox"]
  X -->|"refile: C-c C-w"| P["Project or area"]
  P -->|"clock, schedule, C-c C-t"| W["Work in progress"]
  W -->|"DONE"| D["Finished entry"]
  D -->|"archive: C-c C-x C-s"| A["Archive file"]
  P -.->|"attach: C-c C-a"| F[("Attachment directory")]

Figure 12.1: An item enters through capture, is filed by refile, gathers time and state while you work on it, and leaves the active files through archiving.

Capture

The idea

Capture separates 2 moments that are often mixed up: noticing something and deciding what to do with it. When you call capture, Org shows a small buffer with a prepared entry. You type a few words, press C-c C-c, and Emacs returns to exactly the window layout you had before. The entry has been stored in a predefined place, typically an inbox, a file or heading where unprocessed items wait for review.

Capture is a single command, org-capture. The manual suggests binding it globally, together with the commands for the agenda (the overview of dated and open tasks across your files, see Agenda Views) and for storing links:

(global-set-key (kbd "C-c c") #'org-capture)

The rest of this chapter assumes this binding. Without any configuration, capture stores notes in org-default-notes-file, so set that variable at least:

(setq org-directory "~/org")
(setq org-default-notes-file (concat org-directory "/inbox.org"))

Working in the capture buffer

C-c c shows a menu of capture templates; a single key selects one. Org then opens an indirect buffer narrowed to the new entry, so you see only what you are writing, although the entry already sits in its target file.

Key in the capture bufferCommandEffect
C-c C-corg-capture-finalizeStore the entry and restore the previous windows. With a prefix, jump to the entry.
C-c C-worg-capture-refileStore the entry and refile it to another location at once.
C-c C-korg-capture-killAbort and remove the entry.
sequenceDiagram
  participant U as You
  participant B as Current buffer
  participant C as Capture buffer
  participant T as Target file
  U->>B: C-c c, then template key
  B->>C: link to point, region, kill ring
  C->>T: entry inserted at target
  U->>C: type the note
  U->>C: C-c C-c
  C->>T: entry finalized and saved
  C->>B: previous windows restored

Figure 12.2: Capture collects context from the buffer you are in, writes into the target file at once, and returns you to where you were.

A few prefix arguments make capture useful for navigation as well:

  • C-u C-c c asks for a template and visits its target location, without capturing.
  • C-u C-u C-c c jumps to the item you captured last. The bookmark org-capture-last-stored points to the same place.
  • C-0 C-c c inserts the captured entry at point in the current Org buffer, instead of in the template’s target.
  • C-1 C-c c asks for a date and uses it instead of the current date, for example to file a journal entry under yesterday.

From the agenda, k c starts capture with the date at point in the agenda as the default date for timestamps in the template.

A first set of templates

Templates live in org-capture-templates. Each template is a list: a key, a description, a type, a target, a template string, and optional properties.

(setq org-capture-templates
      '(("t" "Task" entry (file+headline "inbox.org" "Inbox")
         "* TODO %?\n  %U\n  %a")
        ("n" "Note" entry (file+headline "inbox.org" "Inbox")
         "* %? :note:\n  %U\n  %i")
        ("j" "Journal" entry (file+olp+datetree "journal.org")
         "* %<%H:%M> %?")))

Relative file names are resolved against org-directory. With this configuration:

  • C-c c t creates a TODO entry under the heading Inbox in ~/org/inbox.org. Point is placed where %? stands; %U becomes an inactive timestamp with the current date and time, and %a becomes a link to the place where you started capture. If you start the capture while reading an email or a source file, the task links back to it.
  • C-c c n creates a note and includes the active region (%i), so you can mark a paragraph, capture it, and keep a quote.
  • C-c c j writes a journal entry into a date tree, an outline of years, months and days that Org creates as needed.

To show what Org writes, the following templates were run in batch with fixed input. They use %i for the text and :immediate-finish, which stores the entry without opening the capture buffer:

(setq org-capture-templates
      '(("t" "Task" entry (file+headline "inbox.org" "Inbox")
         "* TODO %i\n  :PROPERTIES:\n  :CREATED:  %U\n  :END:"
         :immediate-finish t)
        ("j" "Journal" entry (file+olp+datetree "journal.org")
         "* %<%H:%M> %i" :immediate-finish t)
        ("w" "Week log" item (file+olp+datetree "weeks.org")
         "- %i" :tree-type week :immediate-finish t)))

After 2 tasks, one journal entry and one week log item, the files contained:

#+TITLE: Inbox

* Inbox

** TODO Book the venue for the team offsite
  :PROPERTIES:
  :CREATED:  [2026-11-19 Thu 09:12]
  :END:

** TODO Reply to the security audit questions
  :PROPERTIES:
  :CREATED:  [2026-11-19 Thu 09:12]
  :END:
* 2026
** 2026-11 November
*** 2026-11-19 Thursday
**** 09:12 Paired with Lee on the cache bug.
* 2026
** 2026-W47
*** 2026-11-19 Thursday
- Merged the logging refactor

The first block is inbox.org; Org adjusted the level of each entry to fit below * Inbox. The second is journal.org, with the default year, month and day tree. The third is weeks.org, where :tree-type week replaced months with ISO weeks and the item type added a list item instead of a heading.

Template types

The third element of a template states what kind of thing is inserted:

TypeInserted as
entryAn Org heading with its body. The most common type.
itemA plain list item, in the first list at the target.
checkitemA checkbox item; only the default template differs from item.
table-lineA new row in the first table at the target.
plainText inserted as it is.

table-line makes simple logs easy: a template such as "| %U | %^{Weight} |" appends a row to a table, and the spreadsheet chapter (The Spreadsheet and Plotting) shows how to compute with such tables.

Targets

The fourth element says where the item goes. In Org files, a target usually names a heading, and the new entry becomes its child.

TargetLocation
(file "path")The beginning or end of the file.
(id "ID")The entry whose ID property (a unique identifier stored in its PROPERTIES drawer) has this value; see Hyperlinks.
(file+headline "path" "Heading")A heading that is unique in the file.
(file+olp "path" "Level 1" "Level 2")A heading given by its full outline path.
(file+regexp "path" "regexp")The first match of a regular expression.
(file+olp+datetree "path" ["Level 1" ...])Today’s node in a date tree, optionally below a heading.
(file+function "path" FUNCTION)A position chosen by your function inside the file.
(clock)The task that is currently clocked.
(here)The position of point.
(function FUNCTION)Your function visits a file and moves point.

An empty string as the file name means org-default-notes-file. The file can also be given as a variable or a function. Use file+olp when a heading name is not unique: “Notes” may well appear under several projects.

%-escapes

The template string can contain %-escapes, placeholders that Org replaces when the template is expanded. The most useful ones are:

EscapeReplaced by
%?Nothing; point is placed here after expansion.
%iThe active region, if there is one. Indentation before %i is repeated on every line.
%a, %A, %lA link to the capture origin; %A asks for a description, %l inserts the bare link.
%t, %TAn active timestamp: date, or date and time.
%u, %UThe same as inactive timestamps.
%<FORMAT>The current time in a format-time-string format, such as %<%H:%M>.
%^t, %^T, %^u, %^UAsk for a date with the date prompt.
%^g, %^GAsk for tags (short labels at the end of the headline), with completion from the target file or from all agenda files.
%^{Prompt}Ask for a string. %^{Prompt|default|choice2} offers a default and choices.
%^{PROP}pAsk for the value of property PROP.
%\1, %\2Repeat the answer to the first, second prompt.
%c, %xThe head of the kill ring, the X clipboard.
%k, %KThe title of, and a link to, the clocked task.
%f, %FThe file name, and the full path, of the buffer where capture started.
%[FILE]The contents of a file.
%(SEXP)The result of an Emacs Lisp expression, which must return a string.

Some link types provide extra keywords such as %:subject and %:from for email, or %:link and %:description for org-protocol (see Org Beyond the Basics). The full list is in the manual section on template expansion.

A template that asks a few questions can replace a small form:

(setq org-capture-templates
      '(("m" "Meeting" entry (file+olp+datetree "meetings.org")
         "* %^{Topic} with %^{Who}\n  :PROPERTIES:\n  :PEOPLE:   %\\2\n  :END:\n  %T\n  %?"
         :clock-in t :clock-resume t)))

This template asks for a topic and the people involved, reuses the second answer in a property, adds an active timestamp with the current time below the property drawer (a property drawer must come directly after the headline), and clocks into the new meeting entry. Note the doubled backslash in %\\2: inside an Emacs Lisp string, a backslash must itself be escaped.

Template properties

Keywords after the template string adjust its behavior:

PropertyEffect
:prependInsert as the first child instead of the last.
:immediate-finishStore without showing the capture buffer.
:jump-to-capturedVisit the new entry afterwards.
:empty-lines, :empty-lines-before, :empty-lines-afterBlank lines around the entry.
:clock-inClock in on the new entry while you write it.
:clock-resumeWhen finished, resume the clock that capture interrupted.
:clock-keepKeep the new entry’s clock running after finishing; takes precedence over :clock-resume.
:time-promptAsk for the date to use for date trees and timestamps.
:tree-typeFor date trees: week, month, or a list such as (year quarter month).
:unnarrowedShow the whole target buffer, not only the new entry.
:table-line-posRow position for table-line, such as "II-3".
:kill-bufferClose the target buffer if capture had to open it.
:no-saveDo not save the target file.
:refile-targetsUse these refile targets when refiling from the capture buffer.
:hook, :prepare-finalize, :before-finalize, :after-finalizeFunctions run at the corresponding stage.

:clock-in together with :clock-resume is a pattern worth remembering. When a colleague interrupts you with a question, capture a note with such a template: the clock moves to the interruption, and after C-c C-c it returns to the task you were working on. The interruption is recorded with its own time, as described in Clocking, Effort and Timers.

Grouping and context

Templates with 2-character keys are grouped under a prefix. Declare the prefix with a 2-element entry before the templates that use it:

(setq org-capture-templates
      '(("w" "Work")
        ("wt" "Work task" entry (file+headline "work.org" "Inbox")
         "* TODO %?\n  %U")
        ("wm" "Work meeting" entry (file+olp+datetree "work.org" "Meetings")
         "* %?\n  %T")))

org-capture-templates-contexts limits templates to certain situations, for example offering a template for email patches only in message-mode:

(setq org-capture-templates-contexts
      '(("p" ((in-mode . "message-mode")))))

To bind a key to one template directly, call org-capture with the template key:

(global-set-key (kbd "C-c x")
                (lambda () (interactive) (org-capture nil "t")))

If you do not define a template for the key C, it opens the Customize interface for org-capture-templates, which is a convenient way to build templates with a form.

Refile and copy

Moving entries without cut and paste

Captured items accumulate in the inbox. During a review, you decide for each item where it belongs and move it there. Refiling does this in one step: C-c C-w (org-refile) asks for a target heading with completion and moves the entry, with its subtree (the heading and everything below it), below that heading. Whether it becomes the first or the last child depends on org-reverse-note-order.

Without configuration, the only targets are the level 1 headings of the current file. Real systems need more, so configure org-refile-targets. Each element pairs a set of files with a rule for choosing headings in them:

(setq org-refile-targets
      '((nil :maxlevel . 3)
        (org-agenda-files :maxlevel . 2)))
(setq org-refile-use-outline-path 'file)
(setq org-outline-path-complete-in-steps nil)
(setq org-refile-allow-creating-parent-nodes 'confirm)

The file part is nil (the current buffer), a list of files, or a symbol whose value or function result gives the files, such as org-agenda-files. The heading rule is one of :maxlevel, :level, :tag, :todo or :regexp, or t for every heading. For a final check on each candidate, set org-refile-target-verify-function.

org-refile-use-outline-path presents targets as paths, which is the only way to distinguish 2 headings with the same name. The value file adds the file name as the first component, which also lets you refile to the top level of a file. org-outline-path-complete-in-steps set to nil completes the whole path at once, which works best with a completion interface that shows all candidates. With org-refile-allow-creating-parent-nodes set to confirm, you can type a new heading name at the end of a path, and Org creates it after asking.

A refile session

Consider an inbox and a project file:

* Inbox
** TODO Book the venue for the team offsite
** TODO Reply to the security audit questions
* Projects
** Team offsite
*** DONE Collect date preferences
    CLOSED: [2026-11-12 Thu 16:03]
** Security audit

With org-refile-targets set to ((("projects.org") :maxlevel . 2)) and org-refile-use-outline-path set to file, Org offered these targets:

projects.org
projects.org/Projects
projects.org/Projects/Team offsite
projects.org/Projects/Security audit

After refiling the first task to Team offsite and the second to Security audit, with org-log-refile set to time, the inbox was empty and the project file read:

* Projects
** Team offsite
*** DONE Collect date preferences
    CLOSED: [2026-11-12 Thu 16:03]
*** TODO Book the venue for the team offsite
- Refiled on [2026-11-19 Thu 09:25]
** Security audit
*** TODO Reply to the security audit questions
- Refiled on [2026-11-19 Thu 09:25]

Org adjusted the heading levels and recorded when each entry was moved. org-log-refile accepts time or note, like other logging variables, and the #+STARTUP options logrefile, lognoterefile and nologrefile set it per file. The note line is not indented because org-adapt-indentation is nil by default.

Variants of the refile command

KeyEffect
C-c C-wRefile the entry, or all entries in the active region.
C-u C-c C-wUse the refile interface to jump to a heading, without moving anything.
C-u C-u C-c C-wJump to the place where the last refile went (org-refile-goto-last-stored).
C-2 C-c C-wRefile as a child of the clocked task.
C-3 C-c C-wRefile but keep the original (see also org-refile-keep).
C-0 C-c C-wClear the target cache (org-refile-cache-clear).
C-c M-wCopy instead of move (org-refile-copy).
C-c C-M-wRefile with org-reverse-note-order inverted (org-refile-reverse).

Collecting targets across many large files takes time. org-refile-use-cache keeps the list between calls; after you add new headings, clear the cache with C-0 C-c C-w. Copying an entry that has an ID property creates a duplicate ID, so prefer moving when IDs matter.

The capture buffer also understands C-c C-w. It finalizes the capture and refiles the new entry in one step, which is useful when you already know where an item belongs.

Archiving

Why archive

Finished tasks are valuable as history, but they slow down the agenda and clutter your outlines. Archiving removes them from the active files while keeping them searchable. Org offers 3 ways to archive, which differ in how far the entry moves:

MethodKeyWhere the entry goes
Archive fileC-c C-x C-s or C-c $Another file, by default FILE_archive next to the original.
Archive siblingC-c C-x AA child of a sibling heading named Archive in the same subtree.
Archive tagC-c C-x aNowhere; the entry is tagged ARCHIVE and treated as inactive.

C-c C-x C-a (org-archive-subtree-default) runs the method named in org-archive-default-command, which is the archive file method by default. Set org-archive-default-command to your preferred method and this key is the only one you need.

Moving to an archive file

C-c C-x C-s (org-archive-subtree) moves the subtree at point to the location given by org-archive-location. Its default value "%s_archive::" means “a file named after the current file plus _archive, at the top level”. Archiving the finished task from the project file above gave this archive file (the header lines that Org adds to a new archive file are omitted):

* DONE Collect date preferences
    CLOSED: [2026-11-12 Thu 16:03]
    :PROPERTIES:
    :ARCHIVE_TIME: 2026-11-19 Thu 09:25
    :ARCHIVE_FILE: ~/org/projects.org
    :ARCHIVE_OLPATH: Projects/Team offsite
    :ARCHIVE_CATEGORY: projects
    :ARCHIVE_TODO: DONE
    :END:

The ARCHIVE_* properties record where the entry came from, so it can be understood without its former context. org-archive-save-context-info selects which of these properties are written.

org-archive-location has 2 parts separated by ::: a file name, in which %s stands for the current file name, and an optional heading under which archived entries are placed. Some useful values:

ValueMeaning
"%s_archive::"projects.org_archive, top level. The default.
"::* Archived Tasks"The same file, under the heading Archived Tasks.
"~/org/archive.org::* From %s"One central archive, grouped by source file.
"~/org/archive.org::datetree/"A central archive in a date tree, by the CLOSED date.

A file can set its own location with the keyword #+ARCHIVE: %s_done::, and a subtree with the ARCHIVE property.

For bulk archiving, 2 prefix arguments help. C-u C-c C-x C-s checks each child of the current heading and offers to archive those without open TODO entries. C-u C-u C-c C-x C-s does the same for children whose timestamps are all in the past.

Archived entries keep their clock lines. A clock table with :scope file-with-archives or agenda-with-archives still counts them (see Clocking, Effort and Timers), and the agenda can include archives temporarily with v a.

Archiving inside the file

Sometimes moving an entry to another file loses too much: inherited tags, the position in the outline, the neighbors. The 2 internal methods keep the entry close.

The archive tag method marks a heading with the tag ARCHIVE. The entry stays where it is, but Org treats it as switched off: visibility cycling does not open it (use C-c C-TAB to force it), sparse trees (filtered views of the outline) and the agenda ignore its contents, export includes only the headline, and column view skips it. C-c C-x a (org-toggle-archive-tag) sets or removes the tag; with C-u, it offers to tag each child that has no open TODO.

The archive sibling method moves the entry under a sibling heading called Archive, which carries the ARCHIVE tag and is created if necessary. The following example started with 2 finished tasks and one open task; C-c C-x A on each finished task produced:

* Projects
** TODO Draft the statement of work                                  :ATTACH:
:PROPERTIES:
:ID:       9c043097-6a26-452e-a6d2-2efee7d58881
:END:
** Archive                                                          :ARCHIVE:
*** DONE Kick-off meeting
:PROPERTIES:
:ARCHIVE_TIME: 2026-11-19 Thu 09:25
:END:
*** DONE Send the NDA
:PROPERTIES:
:ARCHIVE_TIME: 2026-11-19 Thu 09:25
:END:

(The ATTACH tag and the ID on the first task come from the attachment example in the next section.)

flowchart TD
  Q1{"Should the entry leave the file?"} -->|yes| F["C-c C-x C-s: archive file"]
  Q1 -->|no| Q2{"Should it move out of the way in the outline?"}
  Q2 -->|yes| S["C-c C-x A: archive sibling"]
  Q2 -->|no| T["C-c C-x a: ARCHIVE tag"]

Figure 12.3: The 3 archiving methods differ only in how far the finished entry moves.

Attachments

Files that belong to an entry

Some tasks come with files: a contract to review, screenshots for a bug, a dataset for an analysis. A link to a file anywhere on disk works (see Hyperlinks), but the file may be moved or deleted. Attachments give each entry its own directory, managed by Org, and a link type to refer to the files in it.

By default, the directory is derived from the entry’s ID property, which Org creates when needed, and it lives under org-attach-id-dir (data/ next to the Org file). Org also adds the tag ATTACH to the entry (the tag name is org-attach-auto-tag). Attaching scope.pdf to the task above created:

data/9c/043097-6a26-452e-a6d2-2efee7d58881/scope.pdf

The first 2 characters of the ID form a subdirectory, which keeps directories small when you have thousands of attachments. Because the path depends only on the ID, you never have to choose a folder name. If you move Org files between directories, set org-attach-id-dir to an absolute path so that the attachments stay reachable.

Alternatively, an entry can have a DIR property that names its directory explicitly. DIR takes precedence over ID, also when it is inherited from a parent.

The attachment dispatcher

All attachment commands are behind C-c C-a (org-attach), which shows a menu and waits for a second key:

KeyCommandPurpose
aorg-attach-attachAttach a file, using org-attach-method.
c, m, lAttach by copying, moving, or linking.
borg-attach-bufferSave a buffer as an attachment.
norg-attach-newCreate a new attachment in a buffer.
zorg-attach-syncSynchronize after you changed the directory yourself.
o, Oorg-attach-open, org-attach-open-in-emacsOpen an attachment externally, or in Emacs.
f, Forg-attach-reveal, org-attach-reveal-in-emacsOpen the attachment directory.
d, Dorg-attach-delete-one, org-attach-delete-allDelete one or all attachments.
s, Sorg-attach-set-directory, org-attach-unset-directorySet or remove a DIR property.

org-attach-method is cp (copy) by default; mv, ln (hard link) and lns (symbolic link) are the alternatives. Set org-attach-expert to hide the help window once you know the keys.

Linking to attachments

Inside the entry, refer to an attachment with an attachment: link. The link is resolved against the attachment directory of the entry, so the Org text does not need to know where that directory is:

* TODO Draft the statement of work                                  :ATTACH:
:PROPERTIES:
:ID:       9c043097-6a26-452e-a6d2-2efee7d58881
:END:
Compare the draft with the client's [[attachment:scope.pdf][scope document]].

With org-attach-use-inheritance, subheadings resolve such links through the attachment directory of a parent, which is convenient for a document whose images all belong to the chapter heading. org-attach-store-link-p stores a link while you attach a file, ready for insertion with C-c C-l.

More attachment features

  • Archiving: org-attach-archive-delete decides whether the attachments of an archived subtree are deleted.
  • Version control: after (require 'org-attach-git), Org commits changes in attachment directories that are Git repositories.
  • Dired: M-x org-attach-dired-to-subtree attaches the file at point, or the marked files, in a Dired window to the subtree in the other window.

RSS feeds as an input

Capture handles input that you type; feeds handle input that arrives by itself. Org can read RSS and Atom feeds and turn each new item into an entry under a heading. Configure the feeds in org-feed-alist:

(setq org-feed-alist
      '(("Org releases"
         "https://example.org/releases.atom"
         "~/org/feeds.org" "Release notes")))

C-c C-x g (org-feed-update-all) fetches all feeds and adds new items; C-c C-x G (org-feed-goto-inbox) jumps to the heading of a feed. Org keeps the state of each feed in a FEEDSTATUS drawer below that heading, so the same item is never added twice. The docstring of org-feed-alist describes how to filter and format items.

A complete inbox workflow

The features in this chapter combine into a pipeline that many Org users rely on. The configuration below is the book’s own suggestion, built only from the variables described above:

(setq org-directory "~/org")
(setq org-default-notes-file (concat org-directory "/inbox.org"))
(setq org-capture-templates
      '(("t" "Task" entry (file "inbox.org")
         "* TODO %?\n  %U\n  %a")
        ("i" "Interruption" entry (file "inbox.org")
         "* %? :interruption:\n  %U"
         :clock-in t :clock-resume t)))
(setq org-refile-targets '((org-agenda-files :maxlevel . 3)))
(setq org-refile-use-outline-path 'file)
(setq org-outline-path-complete-in-steps nil)
(setq org-log-refile 'time)
  1. Capture everything with C-c c t; record interruptions with C-c c i so their time is clocked.
  2. Once a day, open the inbox and refile each item with C-c C-w, or delete it.
  3. Work from the agenda (Agenda Views); clock and schedule as described in the previous chapters.
  4. During the weekly review (Putting It Together), archive finished subtrees with C-c C-x C-s.

Further reading

Agenda Views

Org lets you keep tasks where they belong: a bug fix next to the notes about the bug, a meeting under the project it concerns, a birthday in a personal file. The price of this freedom is that the things you must act on are scattered across many headlines and many files. The agenda is the part of Org that gathers them again. It reads a set of files, selects entries by date, TODO state, tags, properties or text, and presents the result in a single buffer from which you can also edit the original entries.

This chapter starts with the files the agenda reads and the dispatcher that starts every view. It then walks through the built-in views, explains how each line is formatted and sorted, lists the commands you use inside the agenda buffer, and ends with custom views, export and batch use. The chapters on TODO Items, Tags, Properties and Column View and Dates and Times describe the data that the agenda displays; this chapter is about collecting and presenting it.

All output in this chapter was produced by Org 9.8.13 in Emacs batch mode, with the system clock set to Wednesday, 11 March 2026, 08:05. Lines such as Sched. 2x: or 1 d. ago: are relative to that moment, so they will look different if you run the same files on another day.

The sample files

This chapter uses 2 small agenda files. The first collects work projects. Each project is a level-1 headline with the tag project, and its children are the tasks:

* Website redesign                                                  :project:
** NEXT Draft the new navigation                                       :web:
SCHEDULED: <2026-03-11 Wed>
:PROPERTIES:
:Effort:   1:00
:END:
** TODO Review the color palette with design
DEADLINE: <2026-03-13 Fri>
** TODO Remove unused pages
** WAITING Final copy from marketing
* Quarterly report                                                  :project:
** TODO Collect sales figures
DEADLINE: <2026-03-10 Tue>
** TODO [#A] Write the summary
SCHEDULED: <2026-03-09 Mon>
* Conference talk                                                   :project:
** DONE Submit the abstract
CLOSED: [2026-03-10 Tue 16:10]
* Meetings
** Team standup
<2026-03-09 Mon 09:30-09:45 +1w>
** 1:1 with Maria
<2026-03-12 Thu 14:00>

The second file holds personal tasks, an appointment and a diary-style expression for an anniversary:

#+CATEGORY: home

* TODO Renew passport                                                :errand:
DEADLINE: <2026-03-20 Fri>
* TODO Call the plumber                                                :call:
SCHEDULED: <2026-03-10 Tue>
* NEXT Buy groceries                                                 :errand:
* Anniversaries
%%(org-anniversary 1990 3 12) Alex turns %d
* Dentist appointment
<2026-03-11 Wed 15:00-16:00>

The files are saved as work.org and home.org. The configuration below defines the TODO keywords for both files and registers them as agenda files:

(setq org-todo-keywords
      '((sequence "TODO(t)" "NEXT(n)" "WAITING(w)" "|" "DONE(d)" "CANCELED(c)")))
(setq org-agenda-files '("~/org/work.org" "~/org/home.org"))

From files to a view

Every agenda view is built in the same way. Org takes a list of files, scans them for entries that satisfy the view’s criteria, formats each entry as one line, sorts the lines, and inserts them into a read-only buffer named *Org Agenda*. Each line remembers where its entry lives, so commands in the agenda buffer can change the original file. Figure 13.1 shows this pipeline.

flowchart TD
  F["org-agenda-files"] -->|"files, or a restriction"| D["Dispatcher: C-c a"]
  D -->|"view type and match"| S["Select entries"]
  S -->|"skip functions, limits"| P["Format prefix, sort"]
  P -->|"one line per entry"| B["*Org Agenda* buffer"]
  B -->|"t, C-c C-s, :, ..."| O["Original Org entries"]
  O -->|"r or g rebuilds"| S

Figure 13.1: The agenda reads entries from your files, formats them as lines, and sends edits back to the files they came from.

The design has an important consequence: the agenda never stores data of its own. If you change a TODO state in the agenda, the change is written to the Org file; if you edit the Org file, the next rebuild of the agenda reflects it. There is only one copy of each piece of information.

Agenda files

The variable org-agenda-files lists the files the agenda reads. An element can be a file or a directory; a directory contributes every file with the .org extension that it contains. If the value is a single file name instead of a list, Org reads the list of agenda files from that file, one name per line.

You can edit the variable directly, but Org also provides commands that maintain it from inside an Org buffer:

KeyCommandEffect
C-c [org-agenda-file-to-frontAdd the current file to the front of the list, or move it there. With a prefix argument, add or move it to the end.
C-c ]org-remove-fileRemove the current file from the list.
C-' or C-,org-cycle-agenda-filesVisit the agenda files one after another.

The order of the list also matters a little: when the sorting rules described later consider 2 entries equal, the agenda keeps the order of their categories, which follows org-agenda-files.

Sometimes you want a view of only one file or one subtree, for example during a project meeting. The command C-c C-x < (org-agenda-set-restriction-lock) restricts all following agenda commands to the subtree at point, or to the whole file if you call it with C-u or before the first headline. The restriction stays in force until you remove it with C-c C-x > (org-agenda-remove-restriction-lock). For a single command, the dispatcher offers a lighter alternative, described next.

The dispatcher

All agenda views start from the agenda dispatcher, the command org-agenda. It shows a menu and waits for one more key that selects the view. The manual recommends binding it globally; C-c a is the conventional choice:

(global-set-key (kbd "C-c a") #'org-agenda)

The default entries of the dispatcher are:

KeyView
aThe weekly or daily agenda: a calendar of dated entries.
t / TThe global TODO list; T first asks for a TODO keyword.
m / MHeadlines matching a tags and properties expression; M keeps only TODO entries.
s / SA search view that selects entries by words or regular expressions; S keeps only TODO entries.
/A multi-occur search for a regular expression across the agenda files.
# / !The list of stuck projects; ! customizes how stuck projects are recognized.
<Restrict the next command to the current buffer, or to the narrowed part of it.
< <Restrict the next command to the active region, or to the current subtree.
>Remove a restriction.
eWrite the export files of custom commands (see “Exporting agenda views” below).
CCustomize org-agenda-custom-commands.
*Toggle sticky agenda buffers.

The restriction keys are prefixes: after < you still press the key of the view, so C-c a < t produces a TODO list of the current file only.

Custom commands, described later in this chapter, appear in the same menu. Org looks up the key among the custom commands before it checks the built-in keys, so a custom command bound to e or t hides the built-in command with that key. Choose letters that the dispatcher does not use.

By default Org keeps a single agenda buffer and rebuilds it every time you choose a view. If you switch between several expensive views, sticky agendas keep one buffer per view instead. You turn them on with * in the dispatcher, with org-toggle-sticky-agenda, or permanently with org-agenda-sticky. A sticky view is not refreshed automatically when you return to it; press r or g to rebuild it.

The weekly and daily agenda

The view under a (org-agenda-list) behaves like a page of a paper diary. For each day of the displayed span, it lists the entries that are relevant on that day:

  • entries with a plain active timestamp on that day, such as appointments;
  • entries scheduled on that day, and on today’s page, entries scheduled earlier that are still open;
  • deadlines on that day, and on today’s page, deadlines that are close or already past;
  • diary-style sexp entries that match the day;
  • with log mode turned on, entries closed or clocked on that day.

This is the week of the sample files:

Week-agenda (W11):
Monday      9 March 2026 W11
  work:        9:30-9:45  Team standup
  work:       Scheduled:  TODO [#A] Write the summary                :project::
Tuesday    10 March 2026
  home:       Scheduled:  TODO Call the plumber                          :call:
  work:       Deadline:   TODO Collect sales figures                 :project::
Wednesday  11 March 2026
               8:00...... ----------------
               8:05...... now - - - - - - - - - - - - - - - - - - - - - - - - -
              10:00...... ----------------
              12:00...... ----------------
              14:00...... ----------------
  home:       15:00-16:00 Dentist appointment
              16:00...... ----------------
              18:00...... ----------------
              20:00...... ----------------
  work:       Sched. 2x:  TODO [#A] Write the summary                :project::
  home:       Sched. 1x:  TODO Call the plumber                          :call:
  work:       Scheduled:  NEXT Draft the new navigation          :project::web:
  work:        1 d. ago:  TODO Collect sales figures                 :project::
  work:       In   2 d.:  TODO Review the color palette with design  :project::
  home:       In   9 d.:  TODO Renew passport                          :errand:
Thursday   12 March 2026
  work:       14:00...... 1:1 with Maria
  home:       Alex turns 36
Friday     13 March 2026
  work:       Deadline:   TODO Review the color palette with design  :project::
Saturday   14 March 2026
Sunday     15 March 2026

Several details in this output deserve explanation, because together they describe how Org thinks about time.

  • Today is special. Overdue and upcoming items appear only on today’s page. Sched. 2x: means that the summary was scheduled 2 days ago and is still open; 1 d. ago: marks a deadline that passed yesterday; In 2 d.: warns about a deadline 2 days ahead. The warning period defaults to org-deadline-warning-days, which is 14 days, so the passport deadline 9 days away already appears.
  • Items stay until they are done. A scheduled task that you do not finish keeps appearing on today’s page, every day, until you close it. This is why the summary appears on Monday (where it was scheduled) and again on Wednesday, with a growing counter.
  • The time grid frames the day. Today’s page shows timed entries between grid lines at 8:00, 10:00 and so on, plus a now marker at the current time. Entries without a time follow below the grid.
  • Repeaters produce one occurrence per period. The standup has the repeater +1w, so it appears on Monday of every week, without any copy in the file.
  • Diary expressions are evaluated. The %%(org-anniversary 1990 3 12) line produces Alex turns 36 on 12 March, with %d replaced by the number of years.

For more detail on deadlines, scheduling, warning periods and repeaters, see Dates and Times.

Choosing the span and the start day

The variable org-agenda-span sets the default length of the view. It accepts a number of days or one of the symbols day, week, month and year; the default is week. Weekly views start on the day given by org-agenda-start-on-weekday, which is 1 (Monday) by default; set it to nil to start on the current day. The variable org-agenda-start-day moves the start, either to a fixed date such as "2026-03-12" or relative to today, such as "+10d". In weekly and two-week views, org-agenda-start-on-weekday takes precedence over it.

A single-day view of 11 March shows only the part of the week that concerns today:

Day-agenda (W11):
Wednesday  11 March 2026
               8:00...... ----------------
               8:05...... now - - - - - - - - - - - - - - - - - - - - - - - - -
              10:00...... ----------------
              12:00...... ----------------
              14:00...... ----------------
  home:       15:00-16:00 Dentist appointment
              16:00...... ----------------
              18:00...... ----------------
              20:00...... ----------------
  work:       Sched. 2x:  TODO [#A] Write the summary                :project::
  home:       Sched. 1x:  TODO Call the plumber                          :call:
  work:       Scheduled:  NEXT Draft the new navigation          :project::web:
  work:        1 d. ago:  TODO Collect sales figures                 :project::
  work:       In   2 d.:  TODO Review the color palette with design  :project::
  home:       In   9 d.:  TODO Renew passport                          :errand:

The same single-day view for Thursday, 12 March (produced with org-agenda-start-day set to "2026-03-12") contains no overdue items at all, because they belong to today:

Day-agenda (W11):
Thursday   12 March 2026
               8:00...... ----------------
              10:00...... ----------------
              12:00...... ----------------
  work:       14:00...... 1:1 with Maria
              14:00...... ----------------
              16:00...... ----------------
              18:00...... ----------------
              20:00...... ----------------
  home:       Alex turns 36

The time grid

The grid is controlled by 2 variables. org-agenda-use-time-grid turns it on or off, and org-agenda-time-grid describes when it appears and which times it marks. Its default conditions are daily, today and require-timed: the grid appears in a single-day view (as in the Thursday example above) and on today’s page in a longer view, but only when the day has at least one timed entry. The default grid lines are at 8:00, 10:00, 12:00, 14:00, 16:00, 18:00 and 20:00. The now line uses the string in org-agenda-current-time-string. In the agenda buffer, G toggles the grid for the current view.

Org finds the time of an entry in its timestamp (<2026-03-11 Wed 15:00-16:00>), in its scheduled or deadline timestamp, or in the headline text itself, where something like 12:45 or 8:30-1pm is recognized. The last behavior is controlled by org-agenda-search-headline-for-time.

Done items, the diary and log mode

A few variables decide whether finished work remains visible. org-agenda-skip-scheduled-if-done and org-agenda-skip-deadline-if-done hide DONE entries on the day they were scheduled or due; both are nil by default, so a finished task stays on its original date as a record. Warnings about past or upcoming dates disappear in any case once the task is done.

If you also keep an Emacs diary file, set org-agenda-include-diary to t and its entries appear in the agenda. For anniversaries and holidays, the alternative used in the sample file is often simpler: write a diary-style expression such as %%(org-anniversary 1990 3 12) directly in an Org file. The expression must start at the beginning of the line.

Log mode adds what you have already done. Press l in the agenda (or set org-agenda-start-with-log-mode) and the agenda also lists entries closed on each day and entries with clocked time, according to org-agenda-log-mode-items. With log mode on, the Tuesday of the sample week gains a line for the abstract that was closed at 16:10:

Tuesday    10 March 2026
  work:       16:10...... Closed:     DONE Submit the abstract       :project::
  home:       Scheduled:  TODO Call the plumber                          :call:
  work:       Deadline:   TODO Collect sales figures                 :project::

C-u l also shows state changes, and C-u C-u l shows only the logged entries. Recording state changes is the subject of TODO Items; recording clocked time is the subject of Clocking, Effort and Timers.

The global TODO list

The weekly agenda answers “what is due when?”. The global TODO list (t, org-todo-list) answers “what is still open?”. It lists every entry whose TODO keyword is not a DONE state, regardless of dates:

Global list of TODO items of type: ALL
Press ‘N r’ (e.g. ‘0 r’) to search again: (0)[ALL] (1)CANCELED (2)DONE
                      (3)WAITING (4)NEXT (5)TODO
  work:       TODO [#A] Write the summary                            :project::
  work:       NEXT Draft the new navigation                      :project::web:
  work:       TODO Review the color palette with design              :project::
  work:       TODO Remove unused pages                               :project::
  work:       WAITING Final copy from marketing                      :project::
  work:       TODO Collect sales figures                             :project::
  home:       TODO Renew passport                                      :errand:
  home:       TODO Call the plumber                                      :call:
  home:       NEXT Buy groceries                                       :errand:

The header explains how to narrow the list to one keyword: 4 r rebuilds it with only NEXT entries. T (or C-u t) asks for the keyword first, and accepts several keywords separated by |.

A long-lived TODO list quickly becomes too long to read. 2 groups of variables keep it focused:

  • org-agenda-todo-ignore-scheduled, org-agenda-todo-ignore-deadlines, org-agenda-todo-ignore-timestamp and org-agenda-todo-ignore-with-date remove entries that already have a date. The reasoning is that a dated task is visible in the weekly agenda, so it need not appear here as well.
  • org-agenda-todo-list-sublevels, which is t by default, decides whether TODO entries below another TODO entry are listed. Set it to nil to see only the top-level task of each hierarchy.

Match views: tags, properties and TODO states

A match view (m, org-tags-view) selects headlines with a match string, a small query language over tags, properties and TODO keywords. The full grammar is described in Tags, Properties and Column View; a few examples are enough to show what the agenda does with it.

The string errand|call selects headlines tagged errand or call:

Headlines with TAGS match: errand|call
Press ‘C-u r’ to search again
  home:       TODO Renew passport                                      :errand:
  home:       TODO Call the plumber                                      :call:
  home:       NEXT Buy groceries                                       :errand:

The part after a slash restricts the TODO keyword. project/NEXT|WAITING selects entries tagged project whose keyword is NEXT or WAITING:

Headlines with TAGS match: project/NEXT|WAITING
Press ‘C-u r’ to search again
  work:       NEXT Draft the new navigation                      :project::web:
  work:       WAITING Final copy from marketing                      :project::

None of these tasks carries the tag project itself; they inherit it from their parent headline. The agenda shows this in the tag column: inherited tags come first, and a double colon separates them from the entry’s own tags, so :project::web: means “inherited project, local web”. If you prefer to hide inherited tags, set org-agenda-show-inherited-tags to nil; T in the agenda still shows all tags of the entry at point.

M (or org-tags-view with a prefix argument) works like m but only considers headlines with a TODO keyword that is not done.

Search view

The search view (s, org-search-view) finds entries by their text, including the body below the headline. It is the right tool for notes that have no keyword or tag to select them by.

Without a leading +, the whole string is searched as a phrase, so computer equipment matches the 2 words even when they are separated by a line break. With a leading +, the string becomes a Boolean query: words prefixed with + must occur, words prefixed with - must not, and regular expressions are written in braces. For example, +invoice -paid {20[0-9][0-9]} finds entries that mention an invoice and a year but do not mention paid.

Inside a search view, 4 keys refine the query without retyping it:

KeyAdds
[a word that must occur
]a word that must not occur
{a regular expression that must match
}a regular expression that must not match

The search view reads the agenda files and also the files in org-agenda-text-search-extra-files. This makes it useful for reference notes that you never want in your daily agenda: list them there instead of in org-agenda-files. A stored search for the word color (defined later as the custom command n) returns the one entry that mentions it:

Entries mentioning color
  work:       TODO Review the color palette with design              :project::

Stuck projects

Task-management methods such as GTD (Getting Things Done) ask you to make sure that every project has a defined next step. A stuck project is one without such a step: it will never appear in your lists of things to do, so it silently stops moving. The view under # (org-agenda-list-stuck-projects) finds these projects.

Org cannot know what a “project” or a “next step” means in your files, so you describe it in org-stuck-projects. The value has 4 elements:

  1. a match string that identifies projects;
  2. a list of TODO keywords that count as a next step;
  3. a list of tags that count as a next step;
  4. a regular expression that, if found anywhere in the project, marks it as not stuck.

A project is reported as stuck when its subtree contains none of these markers. The default value assumes that projects are level-2 headlines, which rarely matches anyone’s files, so you almost always have to set the variable yourself. A first attempt for the sample files could look like this:

(setq org-stuck-projects
      '("+project/-DONE" ("NEXT" "TODO") nil ""))

The result shows a common mistake:

List of stuck projects:
  work:       WAITING Final copy from marketing                      :project::
  work:       Conference talk                                         :project:

Conference talk is correct: its only task is done. The WAITING task, however, is not a project. It appears because the match string +project also matches headlines that inherit the tag, and the WAITING entry has no NEXT or TODO below it. There are 2 ways to fix the definition. You can limit the match to level-1 headlines:

(setq org-stuck-projects
      '("+project+LEVEL=1/-DONE" ("NEXT" "TODO") nil ""))

Or you can stop the project tag from being inherited at all, which also cleans up the tag column of every view:

(setq org-tags-exclude-from-inheritance '("project"))

With either change, only Conference talk remains. The Putting It Together chapter uses a stricter definition, where only NEXT counts as a next step.

How lines are formatted and sorted

Categories

Each agenda line starts with a category, a short label for the area an entry belongs to. By default it is the file name without the extension, which is why the sample shows work:. A #+CATEGORY: keyword sets it for a whole file (as in home.org), and a CATEGORY property sets it for one subtree. Keep categories short: the default format reserves 12 columns for them. The variable org-agenda-category-icon-alist can add an icon per category.

The prefix

The text before the headline is the prefix, and its format is set by org-agenda-prefix-format. The variable holds one format string per kind of view:

View typeDefault format
agenda" %i %-12:c%?-12t% s"
todo" %i %-12:c"
tags" %i %-12:c"
search" %i %-12:c"

The most useful codes are:

CodeMeaning
%cthe category
%ithe category icon
%tthe time of day, if any
%sscheduling or deadline information, such as Sched. 2x:
%ethe effort estimate
%Tthe last local tag
%lthe level, as spaces
%bbreadcrumbs: the titles of the parent headlines

Between % and the letter you can give a width, as in printf. A colon after the width (%-12:c) appends a colon to non-empty values, and %?-12t produces the 12 columns only when the time is present. Figure 13.2 labels the parts of one line from the weekly agenda.

Figure 13.2: Every agenda line is a formatted prefix followed by a cleaned-up headline, so changing the prefix format changes what each line tells you.

Changing the prefix is a cheap way to make a view more informative. The custom command p, defined later in this chapter, uses " %-6e %b": the effort estimate followed by the path of parent headlines.

Global list of TODO items of type: ALL
Press ‘N r’ (e.g. ‘0 r’) to search again: (0)[ALL] (1)CANCELED (2)DONE
                      (3)WAITING (4)NEXT (5)TODO
         Quarterly report->TODO [#A] Write the summary               :project::
  1:00   Website redesign->NEXT Draft the new navigation         :project::web:
         Website redesign->TODO Review the color palette with design :project::
         Website redesign->TODO Remove unused pages                  :project::
         Website redesign->WAITING Final copy from marketing         :project::
         Quarterly report->TODO Collect sales figures                :project::
         TODO Renew passport                                           :errand:
         TODO Call the plumber                                           :call:
         NEXT Buy groceries                                            :errand:

Tags are aligned according to org-agenda-tags-column, which by default aligns them to the right edge of the window. org-agenda-remove-tags removes them from the lines completely.

Sorting

Lines are sorted before they are inserted, and the rules depend on the view. The variable org-agenda-sorting-strategy holds a list of criteria per view type. Its default is:

((agenda habit-down time-up urgency-down category-keep)
 (todo   urgency-down category-keep)
 (tags   urgency-down category-keep)
 (search category-keep))

Read the agenda entry from left to right: habits come last, timed entries are sorted by time, then entries are sorted by urgency, and entries of equal urgency keep the order of their categories.

Urgency starts from the priority. With the default priority range, C, B and A are worth 0, 1000 and 2000, and an entry without a cookie counts as the default priority B. The functions that collect agenda entries (in org-agenda.el) then adjust the value. A scheduled entry gets 99 points plus the number of days since its scheduled date; a deadline on today’s page gets the number of days it is overdue, which is negative for deadlines still ahead. For today’s page of the sample week this gives:

EntryCalculationUrgency
Write the summary2000 + 99 + 2 days late2101
Call the plumber1000 + 99 + 1 day late1100
Draft the new navigation1000 + 99 + 01099
Collect sales figures1000 + 1 day overdue1001
Review the color palette1000 - 2 days ahead998
Renew passport1000 - 9 days ahead991

This is exactly the order of the untimed lines on Wednesday, even though it mixes the categories work and home. The practical result is that late scheduled work rises above deadlines that are not yet due, and an A priority outweighs any realistic delay. The CSV output at the end of this chapter shows only the priority part (2000 and 1000), not the adjusted urgency.

Other sorting criteria include priority-down, effort-up, alpha-up, tag-up and todo-state-up; the docstring of the variable lists them all.

Working in the agenda buffer

The agenda buffer is read-only, but it is not passive. Almost every command that you use on a headline in an Org buffer has a counterpart in the agenda that acts on the entry behind the current line. This is called remote editing.

Moving and visiting

KeyCommandEffect
n / porg-agenda-next-line / org-agenda-previous-lineMove between lines.
SPCorg-agenda-show-and-scroll-upShow the entry in another window, keep point in the agenda.
TABorg-agenda-gotoGo to the entry in another window.
RETorg-agenda-switch-toGo to the entry and delete other windows.
Forg-agenda-follow-modeToggle Follow mode, which shows each entry as you move.
Lorg-agenda-recenterShow the entry and recenter that window.
C-c C-oorg-agenda-open-linkFollow a link in the entry.
C-c C-x borg-agenda-tree-to-indirect-bufferShow the entry’s subtree in an indirect buffer.

Changing what is displayed

KeyCommandEffect
d / worg-agenda-day-view / org-agenda-week-viewSwitch to a day or week span.
v m / v yorg-agenda-month-view / org-agenda-year-viewSwitch to a month or year span.
f / borg-agenda-later / org-agenda-earlierMove forward or backward by one span.
.org-agenda-goto-todayReturn to today.
jorg-agenda-goto-dateJump to a date.
r / gorg-agenda-redoRebuild the view from the files.
lorg-agenda-log-modeToggle log mode.
v aorg-agenda-archives-modeInclude archived trees; v A also includes archive files.
Rorg-agenda-clockreport-modeShow a clock table for the displayed span.
Eorg-agenda-entry-text-modeShow the first lines of each entry’s body.
Gorg-agenda-toggle-time-gridToggle the time grid.
Dorg-agenda-toggle-diaryToggle diary entries.
AAppend another view to the current one.
sorg-save-all-org-buffersSave all Org buffers.

Month and year views are slow to build, so v m and v y do not become the default for later refreshes, while d and w do.

Editing entries remotely

KeyCommandEffect on the original entry
torg-agenda-todoChange the TODO state.
,org-agenda-prioritySet the priority; + and - raise or lower it.
:org-agenda-set-tagsSet tags.
eorg-agenda-set-effortSet the effort estimate.
zorg-agenda-add-noteAdd a note, filed where state-change notes go.
C-c C-sorg-agenda-scheduleSchedule; with a prefix argument, remove the schedule.
C-c C-dorg-agenda-deadlineSet a deadline; with a prefix argument, remove it.
S-RIGHT / S-LEFTorg-agenda-do-date-later / org-agenda-do-date-earlierMove the date by one day.
>org-agenda-date-promptChange the date through the date prompt.
I / O / Xorg-agenda-clock-in / org-agenda-clock-out / org-agenda-clock-cancelStart, stop or cancel the clock.
C-c C-worg-agenda-refileRefile the entry.
$org-agenda-archiveArchive the subtree.
C-korg-agenda-killDelete the entry and its subtree.
korg-agenda-captureCapture, using the date at point as the default date.
C-_org-agenda-undoUndo the last remote edit, in the agenda and in the file.

Some of these commands change the file without redrawing the line. After moving a date with S-RIGHT, for example, the line stays where it is until you press r or g. This is deliberate: rebuilding the whole view after each small edit would be slow and would move point.

A typical morning pass over today’s page therefore looks like this: move with n, press t to mark finished tasks, S-RIGHT to postpone what will not happen today, C-c C-w to move stray items to their project, and finally g to see the cleaned-up day.

Acting on many entries at once

When the same change applies to several lines, mark them first and then act on all of them. m marks the line at point, u unmarks it, * marks every visible line, U removes all marks, and % marks lines matching a regular expression. B (org-agenda-bulk-action) then asks for an action:

Key after BAction
tChange the TODO state of all marked entries.
+ / -Add or remove a tag.
s / dSchedule, or set a deadline. At the schedule prompt, ++2w shifts every existing date by 2 weeks.
rRefile all marked entries to one target.
$ / AArchive, or move to the archive sibling.
SScatter the entries randomly over the next N days.
fApply a function to every marked entry.

Filters and limits

A view defines which entries are collected. Filters then hide some of the collected lines without rebuilding the view, which makes them fast enough to use interactively:

KeyCommandFilters by
/org-agenda-filterA combined expression, such as +work-call+<0:30
\org-agenda-filter-by-tagA tag
<org-agenda-filter-by-categoryThe category of the line at point
=org-agenda-filter-by-regexpA regular expression
_org-agenda-filter-by-effortThe effort estimate
^org-agenda-filter-by-top-headlineThe top-level headline of the line at point
|org-agenda-filter-remove-allRemove all filters

A single C-u before a filter command inverts it, and C-u C-u adds the new condition to those already active. The combined filter / accepts categories, tags, effort comparisons and regular expressions in one string; elements prefixed with - exclude lines.

Limits work at an earlier stage: they restrict which entries are collected at all. The variables org-agenda-max-entries, org-agenda-max-todos, org-agenda-max-tags and org-agenda-max-effort cap the number of entries, TODO entries, tagged entries and the total effort in minutes. They are most useful as local settings of a custom command; a list of “the next 5 tasks” is one example. The key ~ (org-agenda-limit-interactively) applies a temporary limit to the current view.

Leaving the agenda

q (org-agenda-quit) removes the agenda buffer. x (org-agenda-exit) also kills the buffers that Org opened only to build the agenda, while buffers you opened yourself stay. Where the agenda window appears in the first place is decided by org-agenda-window-setup, and org-agenda-restore-windows-after-quit decides whether the previous window layout comes back when you leave.

Custom agenda views

Built-in views take a query every time. Once you notice that you type the same match string every day, or that you always look at 2 views one after the other, it is time for a custom agenda command. Custom commands are defined in org-agenda-custom-commands and appear in the dispatcher next to the built-in ones. They serve 2 purposes: storing searches under a key, and combining several views into one buffer.

Figure 13.3 shows the parts of one entry in the variable.

Figure 13.3: A custom command pairs a dispatcher key with one or more blocks, and each layer of the entry can carry its own variable settings.

The simplest entry has a key, a description, a view type, a match string and an optional list of settings. The following configuration defines 5 commands that are used in this chapter:

(setq org-agenda-custom-commands
      '(("c" "Errands and calls" tags-todo "errand|call"
         ((org-agenda-prefix-format "  [ ] ")
          (org-agenda-remove-tags t)))
        ("u" "Unplanned project tasks" tags-todo "project"
         ((org-agenda-skip-function
           '(org-agenda-skip-entry-if 'scheduled 'deadline))
          (org-agenda-overriding-header "Project tasks without a date")))
        ("p" "Tasks with breadcrumbs" todo ""
         ((org-agenda-prefix-format "  %-6e %b")))
        ("n" "Notes about colors" search "color"
         ((org-agenda-overriding-header "Entries mentioning color")))
        ("X" "Week as text" agenda ""
         ((org-agenda-use-time-grid nil))
         ("~/agenda/week.txt"))))

The available view types are:

TypeEquivalent built-in view
agendathe weekly or daily agenda (a)
agenda*the same, limited to entries with a time of day (appointments)
todothe TODO list for given keywords (T)
alltodothe global TODO list (t)
tagsa match view (m)
tags-todoa match view of TODO entries (M)
searcha search view (s)
stuckthe stuck projects list (#)
todo-tree, tags-tree, occur-treea sparse tree in the current buffer instead of an agenda buffer

The settings list binds variables while the view is built, so any agenda option can be changed for one command. The command c turns the errand list into a checklist that fits on a piece of paper:

Headlines with TAGS match: errand|call
Press ‘C-u r’ to search again
  [ ] TODO Renew passport
  [ ] TODO Call the plumber
  [ ] NEXT Buy groceries

If you define many commands, group them under prefix keys. An entry of the form ("h" . "Home searches") describes the prefix, and commands with keys such as "ha" and "hb" are then reached with C-c a h a and C-c a h b.

Block agendas

A block agenda puts the results of several views into one buffer, one block after another. Instead of a single type and match, the entry contains a list of blocks, each of the form (type match settings):

(add-to-list 'org-agenda-custom-commands
             '("d" "Daily overview"
               ((agenda "" ((org-agenda-span 'day)))
                (todo "NEXT"
                      ((org-agenda-overriding-header "Next actions")))
                (todo "WAITING"
                      ((org-agenda-overriding-header "Waiting for others"))))
               ((org-agenda-block-separator ?-))))

This command answers the 3 questions of a working day in one screen: what is fixed today, what can I do next, and what am I waiting for.

Day-agenda (W11):
Wednesday  11 March 2026
               8:00...... ----------------
               8:05...... now - - - - - - - - - - - - - - - - - - - - - - - - -
              10:00...... ----------------
              12:00...... ----------------
              14:00...... ----------------
  home:       15:00-16:00 Dentist appointment
              16:00...... ----------------
              18:00...... ----------------
              20:00...... ----------------
  work:       Sched. 2x:  TODO [#A] Write the summary                :project::
  home:       Sched. 1x:  TODO Call the plumber                          :call:
  work:       Scheduled:  NEXT Draft the new navigation          :project::web:
  work:        1 d. ago:  TODO Collect sales figures                 :project::
  work:       In   2 d.:  TODO Review the color palette with design  :project::
  home:       In   9 d.:  TODO Renew passport                          :errand:

-------------------------------------------------------------------------------
Next actions
  work:       NEXT Draft the new navigation                      :project::web:
  home:       NEXT Buy groceries                                       :errand:

-------------------------------------------------------------------------------
Waiting for others
  work:       WAITING Final copy from marketing                      :project::

Notice the 2 places where settings appear. Settings inside a block apply only to that block: the span of 1 day affects only the agenda block. Settings after the list of blocks apply to every block: here org-agenda-block-separator replaces the default separator line (drawn with ─, or with = where that character cannot be displayed) with dashes. The variable org-agenda-overriding-header replaces the default header of a block with your own text, which matters more in a block agenda than anywhere else, because the default headers (“Global list of TODO items of type: NEXT”) do not say why a block is there.

Some options are read only when the agenda buffer is first set up, not when each block is built. org-agenda-start-with-log-mode is one of them: in Org 9.8.13 it takes effect when placed in the shared settings of a block agenda, and has no effect inside a single block. When an option seems to be ignored in a block, try the shared settings.

Skip functions

Match strings select entries by tags, properties and keywords. Sometimes the condition you need is different, for example “project tasks that have no date yet”. A skip function handles such cases: Org calls it at each candidate entry, and if it returns a buffer position, the entry is skipped and the search continues from that position; if it returns nil, the entry is kept.

You set a skip function with org-agenda-skip-function in the settings of a command. Org provides 2 ready-made helpers. org-agenda-skip-entry-if skips the current entry when a condition holds; org-agenda-skip-subtree-if skips the whole subtree. The conditions include scheduled, notscheduled, deadline, notdeadline, timestamp, nottimestamp, regexp, notregexp, todo and nottodo. The command u from the configuration above combines a match string with a skip function:

("u" "Unplanned project tasks" tags-todo "project"
 ((org-agenda-skip-function
   '(org-agenda-skip-entry-if 'scheduled 'deadline))
  (org-agenda-overriding-header "Project tasks without a date")))

It returns the project tasks that are neither scheduled nor have a deadline, which are the tasks most likely to be forgotten:

Project tasks without a date
  work:       TODO Remove unused pages                               :project::
  work:       WAITING Final copy from marketing                      :project::

When no helper fits, write a function. It runs with point at the beginning of the candidate entry and must return nil to keep it, or a position to continue from. This function keeps only entries whose Effort property is set:

(defun my-agenda-skip-without-effort ()
  "Skip entries that have no Effort property."
  (unless (org-entry-get nil "Effort")
    (or (outline-next-heading) (point-max))))

Use it in a command like any other skip function. Over the sample files, a TODO list with this skip function keeps only the one task that has an estimate:

("f" "Estimated tasks" alltodo ""
 ((org-agenda-skip-function #'my-agenda-skip-without-effort)))
Global list of TODO items of type: ALL
Press ‘N r’ (e.g. ‘0 r’) to search again: (0)[ALL] (1)CANCELED (2)DONE
                      (3)WAITING (4)NEXT (5)TODO
  work:       NEXT Draft the new navigation                      :project::web:

The variable org-agenda-skip-function-global applies a skip function to every view, which is occasionally useful for excluding a whole class of entries everywhere.

Commands that depend on context

org-agenda-custom-commands-contexts makes a command available only in certain situations, for example only when the current buffer is in a particular major mode. Each entry names a command key and one or more conditions:

(setq org-agenda-custom-commands-contexts
      '(("c" (in-mode . "message-mode"))))

With this setting, c appears in the dispatcher only when you start it from a message-mode buffer. The docstring of the variable lists the other conditions, such as in-file, in-buffer and their negations not-in-mode, not-in-file and not-in-buffer.

Exporting agenda views

An agenda view can be written to a file, which is useful for printing a week on paper, for sharing a status list, or for feeding another program.

Writing the current view

C-x C-w (org-agenda-write) writes the current agenda buffer to a file. The extension of the file name selects the format:

ExtensionResult
.htmlHTML, which requires the htmlize package
.psPostScript
.pdfPDF, converted from PostScript by the external program ps2pdf
.icsiCalendar, for the entries shown in the view
.organ Org file containing the subtrees of the listed entries
any otherplain text

Settings in org-agenda-exporter-settings are applied while the file is written.

Views with permanent output files

If you export the same views regularly, attach file names to the custom commands. The file list is the last element of an entry, after the settings, as in the command X above. Running a command interactively does not create its files; instead, e in the dispatcher (org-store-agenda-views) writes the files of every command that has them. This is what the command X produces:

Week-agenda (W11):
Monday      9 March 2026 W11
  work:        9:30-9:45  Team standup
  work:       Scheduled:  TODO [#A] Write the summary                :project::
Tuesday    10 March 2026
  home:       Scheduled:  TODO Call the plumber                          :call:
  work:       Deadline:   TODO Collect sales figures                 :project::
Wednesday  11 March 2026
  home:       15:00-16:00 Dentist appointment
  work:       Sched. 2x:  TODO [#A] Write the summary                :project::
  home:       Sched. 1x:  TODO Call the plumber                          :call:
  work:       Scheduled:  NEXT Draft the new navigation          :project::web:
  work:        1 d. ago:  TODO Collect sales figures                 :project::
  work:       In   2 d.:  TODO Review the color palette with design  :project::
  home:       In   9 d.:  TODO Renew passport                          :errand:
Thursday   12 March 2026
  work:       14:00...... 1:1 with Maria
  home:       Alex turns 36
Friday     13 March 2026
  work:       Deadline:   TODO Review the color palette with design  :project::
Saturday   14 March 2026
Sunday     15 March 2026

The setting org-agenda-use-time-grid is nil in this command because grid lines are noise on paper.

The agenda from the command line

Because Emacs can run without a display, agenda views can be produced by scripts and scheduled jobs. Org offers 3 entry points for batch use:

  • org-batch-store-agenda-views writes the files of all custom commands that have them, like e in the dispatcher.
  • org-batch-agenda prints a view to standard output. Its first argument is a one-letter command key, or a longer match string for a match view.
  • org-batch-agenda-csv prints the same view as comma-separated values for further processing.

All 3 accept pairs of variable names and values that are bound while the view is built. The examples in this chapter were produced with commands of this shape:

emacs -Q --batch -l setup.el \
  --eval '(org-batch-agenda "a" org-agenda-span (quote day))'

where setup.el contained the configuration shown at the beginning of the chapter. The CSV variant of the same day, with the time grid turned off, looks like this:

home,Dentist appointment,timestamp,,,2026-03-11,15:00-16:00,,,1000,2026-03-11
work,Write the summary,past-scheduled,TODO,project,2026-03-09,,Sched. 2x:,A,2000,2026-03-11
home,Call the plumber,past-scheduled,TODO,call,2026-03-10,,Sched. 1x:,,1000,2026-03-11
work,Draft the new navigation,scheduled,NEXT,project:web,2026-03-11,,Scheduled:,,1000,2026-03-11
work,Collect sales figures,deadline,TODO,project,2026-03-10,,1 d. ago:,,1000,2026-03-11
work,Review the color palette with design,upcoming-deadline,TODO,project,2026-03-11,,In   2 d.:,,1000,2026-03-11
home,Renew passport,upcoming-deadline,TODO,errand,2026-03-11,,In   9 d.:,,1000,2026-03-11

The fields are, in order: category, headline, type of entry, TODO keyword, tags, date, time, extra planning text, priority letter, numeric priority, and the agenda day on which the line appears. The type field is the most informative: it distinguishes timestamp, scheduled, past-scheduled, deadline, upcoming-deadline, closed and other cases that the text view shows only through the prefix.

Column view in the agenda

Column view, described in Tags, Properties and Column View, shows the properties of entries as a table. C-c C-x C-c (org-agenda-columns) turns it on in the agenda as well, which is useful for comparing effort estimates with clocked time across all the tasks of a day or a search.

Because agenda entries come from different files, Org must decide which column format to use. It takes the first of these that is set: org-overriding-columns-format (meant to be set in the settings of a custom command), org-columns-default-format-for-agenda, the format of the first entry in the view, and finally org-columns-default-format.

Keep 2 cautions in mind. Summary values in agenda column view add up the lines that are displayed, and an entry may appear twice (as scheduled and as a deadline, or as a parent and its child), so sums can count some values twice. And the special property CLOCKSUM always shows the total time clocked on an entry, not the time within the displayed span; use CLOCKSUM_T for today’s time, or clock report mode (R) for the span.

Keeping the agenda fast

The agenda reads every agenda file each time it is built, so its speed depends on the size of those files. If building a view becomes slow, try these settings before anything else:

(setq org-agenda-inhibit-startup t)          ; do not apply startup visibility
(setq org-agenda-dim-blocked-tasks nil)      ; skip the blocking check
(setq org-agenda-use-tag-inheritance nil)    ; no inherited tags in views
(setq org-agenda-ignore-properties '(stats)) ; do not update statistics cookies

Each of these settings has a cost. With org-agenda-use-tag-inheritance set to nil, for example, the weekly agenda, the TODO list and the search view no longer know about inherited tags, so a tag filter for project misses the tasks inside a project. (Match views are not affected; they follow org-use-tag-inheritance.) Apply them selectively, in the settings of the custom commands that need speed, rather than globally. Keeping the agenda files small helps as well: archive finished subtrees regularly, as described in Capture, Refile, Archive and Attachments.

Summary

  • The agenda collects entries from org-agenda-files and shows them as lines that point back to the original headlines.
  • The dispatcher (C-c a) offers a calendar view (a), a TODO list (t), match views (m, M), a text search (s) and stuck projects (#).
  • Overdue and upcoming items appear on today’s page only, and stay there until they are done.
  • Remote editing keys such as t, C-c C-s and C-c C-w change the files directly; r or g rebuild the view.
  • Custom commands store searches, combine views into block agendas, adjust options per view, and attach output files for printing and scripts.

Further reading

Working with Source Code (Babel)

Org can hold source code as well as prose, and it can do more with that code than display it. It can run a block and write the result back into the document, pass data from a table into a program and from one program into another, extract the code into ordinary source files, and decide what appears when the document is exported. The machinery behind all of this is called Babel (Org Babel), after its ability to mix many programming languages in one file.

This chapter starts with the shape of a code block and the three things Org can do with it. It then covers evaluation and results, header arguments and where they come from, passing data between blocks, sessions and caching, export, tangling and noweb references, and finally running Babel from the command line and the security model that protects you from code you did not write.

Every result shown in this chapter was produced by Org 9.8.13 running in Emacs 31 in batch mode. Python examples ran with Python 3.

Why code blocks exist

Two traditions meet in Babel. The first is literate programming: a program is written as an essay for people, and the compiler receives the code extracted from that essay. The second is reproducible research: the data, the code that analyzes it, the results, and the discussion of those results live in one file, so that anyone can run the analysis again and check the claims.

In practice you use Babel for much smaller things too:

  • a notes file where shell commands can be run in place and their output kept next to the explanation;
  • an Emacs configuration written as an Org document and extracted into init.el;
  • a report whose tables are computed by code at export time;
  • a runbook where each step is a block you can execute and record.

A source code block (also code block or src block) is the unit Org works with. Org can do three independent things with one:

OperationCommandWhat happens
EvaluateC-c C-c on the blockThe code runs; its result is inserted below the block.
TangleC-c C-v tThe code is written to an external source file.
ExportC-c C-eThe code, its result, both, or neither appear in the exported document.
flowchart LR
  B["code block"] -->|"C-c C-c"| E["evaluate"]
  B -->|"C-c C-v t"| T["tangle"]
  B -->|"C-c C-e"| X["export"]
  E -->|"result"| R["#+RESULTS: in the Org buffer"]
  T -->|"expanded body"| F["source file on disk"]
  X -->|":exports code/results/both/none"| D["HTML, LaTeX, Markdown ..."]
  X -.->|"may evaluate first"| E

Figure 14.1: One code block feeds three separate operations, and export may trigger evaluation on its own.

Header arguments (covered below) control each operation separately: a block can be tangled but never evaluated, evaluated but never exported, or any other combination.

The anatomy of a code block

A code block sits between #+BEGIN_SRC and #+END_SRC lines. The opening line names the language and may carry switches and header arguments. An optional #+NAME: line above the block gives it a name, which lets other blocks, tables and links refer to it.

#+NAME: version-info
#+BEGIN_SRC emacs-lisp
(format "Org %s on Emacs %d" (org-version) emacs-major-version)
#+END_SRC

The general shape is:

#+NAME: <name>
#+BEGIN_SRC <language> <switches> <header arguments>
  <body>
#+END_SRC

The keywords are case-insensitive: #+begin_src works as well as #+BEGIN_SRC. If you omit the language, you cannot give switches or header arguments either, because Org would read the first of them as the language. Names must be unique in a file; with duplicate names, the behavior is undefined.

You rarely type the delimiters by hand. C-c C-, (org-insert-structure-template) asks for a block type and inserts the pair; the entry s in org-structure-template-alist produces a src block. With text selected, the same command wraps the region in the block.

Inline code

For a short computation inside a sentence, use an inline code block:

The answer is src_emacs-lisp{(* 6 7)}.

An inline block may take header arguments in brackets, src_python[:results value]{return 2**10}. Inline blocks cannot have names. After evaluation Org places the result right after the block, wrapped in a results macro so that the next evaluation can find and replace it:

Inline: src_emacs-lisp{(* 6 7)} {{{results(=42=)}}} and src_python[:results value]{return 2**10} {{{results(=1024=)}}}.

The =...= around the value comes from org-babel-inline-result-wrap, whose default "=%s=" formats the result as verbatim text.

Editing a block in its own mode

Typing code directly in the Org buffer works for a few lines. For anything longer, press C-c ' (org-edit-special) inside the block. Org opens a separate buffer in the language’s major mode, with its indentation, completion and linting. C-c ' again writes the code back and closes the buffer; C-x C-s writes it back without closing.

A few variables shape this experience:

VariableEffect
org-src-fontify-nativelyHighlight code in the Org buffer using the language’s major mode (default t).
org-src-tab-acts-nativelyMake TAB in a block indent as the language mode would (default t).
org-src-lang-modesMap a language name to a major mode, for example ("shell" . sh).
org-src-window-setupWhere the edit buffer appears (default reorganize-frame).
org-src-content-indentationIndentation added to the block body when Org writes it back (default 2).
org-src-preserve-indentationWhen non-nil, keep the body exactly as written, flush left.

Indentation matters for whitespace-sensitive languages. If Python code inside your blocks shifts in surprising ways, set org-src-preserve-indentation to t and write the code from the first column.

Enabling languages

Org ships a Babel backend for each supported language, in files named ob-<language>.el. Version 9.8.13 includes backends for awk, C (and C++, D), C#, calc, Clojure, CSS, ditaa, Graphviz dot, Emacs Lisp, Eshell, Forth, Fortran, gnuplot, Groovy, Haskell, Java, JavaScript, Julia, LaTeX, LilyPond, Lisp, Lua, Makefile, MATLAB, Maxima, OCaml, Octave, Org, Perl, PlantUML, Processing, Python, R, Ruby, Sass, Scheme, GNU Screen, sed, shell, SQL and SQLite. Many more live in external packages.

By default only Emacs Lisp can be evaluated. The variable org-babel-load-languages lists the languages to activate, and org-babel-do-load-languages sets it and loads the backends:

(org-babel-do-load-languages
 'org-babel-load-languages
 '((emacs-lisp . t)
   (shell . t)
   (python . t)))

A nil instead of t disables a language. Loading a backend with require, for example (require 'ob-python), enables that language as well.

The language name on the #+BEGIN_SRC line selects the backend. For shell code you can write shell, or the name of a specific shell (sh, bash, zsh), which also chooses the interpreter.

Evaluating a block

Put point anywhere in a block and press C-c C-c. Org runs the code, collects the result and inserts it after a #+RESULTS: line below the block. If the block is named, the result line repeats the name. Running the block again replaces the old result.

#+NAME: version-info
#+BEGIN_SRC emacs-lisp
(format "Org %s on Emacs %d" (org-version) emacs-major-version)
#+END_SRC

#+RESULTS: version-info
: Org 9.8.13 on Emacs 31

C-c C-v e does the same as C-c C-c on a block. If you would rather keep C-c C-c from ever running code, set org-babel-no-eval-on-ctrl-c-ctrl-c to t.

Org asks for confirmation before each evaluation. That prompt is a security feature, and the last section explains how to tune it. To evaluate many blocks at once, use C-c C-v b (org-babel-execute-buffer) for the whole buffer or C-c C-v s (org-babel-execute-subtree) for the current subtree. To delete a result, use C-c C-v k (org-babel-remove-result-one-or-many).

Value or output: how the result is collected

The first question Org asks about a result is where it comes from. The :results header argument offers two collection modes:

  • value (the default for most languages) treats the block as the body of a function and takes its return value.
  • output runs the block as a script and takes everything it printed to standard output.

The difference is clearest in Python, where a value result needs an explicit return:

#+BEGIN_SRC python :results value
return sum(range(1, 11))
#+END_SRC

#+RESULTS:
: 55

#+BEGIN_SRC python :results output
for n in range(1, 4):
    print(n, n * n)
#+END_SRC

#+RESULTS:
: 1 1
: 2 4
: 3 9

Without return, a Python value block yields None, even when its last line is an expression:

#+BEGIN_SRC python
x = 21
x * 2
#+END_SRC

#+RESULTS:
: None

Shell blocks print by nature, so their “value” is their standard output. Org then tries to read that output as a table, which is why two lines become a one-column table here:

#+BEGIN_SRC shell
ls /etc/hostname
echo done
#+END_SRC

#+RESULTS:
| /etc/hostname |
| done          |

Add :results output when you want the text as it is.

Type, format and handling

After collection, three more classes of :results options decide how the result is interpreted, wrapped and placed. You may combine one option from each class, as in :results output verbatim replace.

flowchart LR
  C["code runs"] --> K["Collection<br/>value | output"]
  K -->|"raw result"| T["Type<br/>table, list, scalar, file"]
  T -->|"Org data"| F["Format<br/>raw, drawer, code, html, org ..."]
  F -->|"formatted text"| H["Handling<br/>replace, append, silent ..."]
  H --> B["Org buffer"]

Figure 14.2: A result passes through four independent choices, each set by one word in :results.

Type says what kind of Org object the result should become:

TypeResult
table or vectorAn Org table; a single value becomes a 1 by 1 table.
listAn Org plain list.
scalar or verbatimLiteral text, never converted into a table.
fileThe result is written to a file and a link to it is inserted.

When you give no type, the backend guesses. A Lisp list of lists becomes a table, and in Python a None row becomes a horizontal rule:

#+BEGIN_SRC python
return [["n", "square"], None, [1, 1], [2, 4], [3, 9]]
#+END_SRC

#+RESULTS:
| n | square |
|---+--------|
| 1 |      1 |
| 2 |      4 |
| 3 |      9 |

The same data can take other shapes:

#+BEGIN_SRC emacs-lisp :results list
'("apples" "pears" "plums")
#+END_SRC

#+RESULTS:
- apples
- pears
- plums

#+BEGIN_SRC emacs-lisp :results verbatim
'(1 2 3)
#+END_SRC

#+RESULTS:
: (1 2 3)

A file result needs a file name from the :file header argument; Org writes the result there and inserts a link:

#+BEGIN_SRC shell :results file :file hello.txt
echo "written by a code block"
#+END_SRC

#+RESULTS:
[[file:hello.txt]]

This is the usual way to include generated images: a plotting block writes a PNG and the link displays it inline. When the code itself writes the file (as a plotting library usually does), add link or graphics (:results file link) so that Org only inserts the link and does not overwrite the file with the block’s return value. The related header arguments :output-dir, :file-ext, :file-desc and :file-mode control the directory, the extension, the link description and the file permissions.

Format decides how the result is wrapped:

FormatWrapping
rawNone: the text is inserted as Org markup.
drawerLike raw, but inside a :results: drawer, so Org can find and replace it.
codeInside a source block of the same language.
orgInside a #+begin_src org block.
html, latexInside an export block for that backend.
ppPretty-printed code (Emacs Lisp, Python, Ruby).

The drawer format is the practical choice for a block that generates Org text, because a raw result has no end marker and cannot be replaced cleanly on the next run:

#+BEGIN_SRC emacs-lisp :results drawer
"- item one\n- item two"
#+END_SRC

#+RESULTS:
:results:
- item one
- item two
:end:

The separate :wrap header argument wraps the result in any block you name, and it takes precedence over the format:

#+BEGIN_SRC emacs-lisp :wrap quote
"A wrapped result."
#+END_SRC

#+RESULTS:
#+begin_quote
A wrapped result.
#+end_quote

Handling decides what happens to the previous result. replace (default) overwrites it; append and prepend keep it and add the new one below or above; silent shows the result only in the echo area; none computes the result but does not show it (other blocks can still use it); discard throws it away entirely.

The :post header argument runs another named block on the result before insertion. Inside the :post call the variable *this* holds the result, as in :post round-numbers(data=*this*).

Header arguments and where they come from

A header argument is a setting for one aspect of a block, written as a keyword and a value: :results output, :tangle yes, :var n=5. Some apply to all languages; some exist only for one backend (for example :lexical for Emacs Lisp).

Writing the same arguments on every block would be tedious, so Org reads header arguments from several places and merges them. A more local setting always overrides a more general one:

flowchart TB
  A["org-babel-default-header-args"] -->|"overridden by"| B["org-babel-default-header-args:LANG"]
  B -->|"overridden by"| C["#+PROPERTY: header-args and :header-args: in drawers"]
  C -->|"overridden by"| D["header-args:LANG properties"]
  D -->|"overridden by"| E["arguments on the #+BEGIN_SRC line"]
  E -->|"overridden by"| F["#+HEADER: lines"]
  F -->|"overridden by"| G["#+CALL: and call_ arguments"]

Figure 14.3: Header arguments are merged from the most general source to the most specific one, and the last value wins.

The following file shows each level winning in turn. A global default sets source for all Emacs Lisp blocks, and each later level overrides it:

(setq org-babel-default-header-args:emacs-lisp
      '((:var . "source=\"global default\"")))
#+PROPERTY: header-args:emacs-lisp :var source="buffer property"

* Default level
#+BEGIN_SRC emacs-lisp
source
#+END_SRC

#+RESULTS:
: buffer property

* Subtree level
:PROPERTIES:
:header-args:emacs-lisp: :var source="subtree property"
:END:

#+BEGIN_SRC emacs-lisp
source
#+END_SRC

#+RESULTS:
: subtree property

#+BEGIN_SRC emacs-lisp :var source="block line"
source
#+END_SRC

#+RESULTS:
: block line

#+HEADER: :var source="HEADER line"
#+BEGIN_SRC emacs-lisp :var source="block line"
source
#+END_SRC

#+RESULTS:
: HEADER line

#+NAME: report
#+BEGIN_SRC emacs-lisp :var source="block line"
source
#+END_SRC

#+RESULTS: report
: block line

#+CALL: report(source="CALL arguments")

#+RESULTS:
: CALL arguments

Without the #+PROPERTY line, the first block returns global default.

The levels in practice:

  • System-wide defaults. org-babel-default-header-args holds the defaults for every block: :session none, :results replace, :exports code, :cache no, :noweb no, :hlines no, :tangle no. Inline blocks use org-babel-default-inline-header-args instead, which exports results rather than code. Per-language variables are named org-babel-default-header-args:<lang>; for Emacs Lisp the default is ((:lexical . "no")), so Emacs Lisp blocks use dynamic binding unless you write :lexical yes.
  • Buffer-wide. A #+PROPERTY: header-args ... line applies to the whole file; #+PROPERTY: header-args:python ... applies to Python blocks only.
  • Subtree. A header-args (or header-args:<lang>) property in a heading’s property drawer applies to all blocks in that subtree. These properties are always inherited, whatever org-use-property-inheritance says. Writing the property name with a + suffix (:header-args+:) appends to an inherited value instead of replacing it. See Tags, Properties and Column View for property syntax.
  • Block. Arguments on the #+BEGIN_SRC line, and on any #+HEADER: lines directly above it. #+HEADER: is useful when the opening line would become too long.
  • Call. Arguments given in a #+CALL: line or an inline call_ override everything else for that call.

To change a global default without losing the others, replace one entry:

(setq org-babel-default-header-args
      (cons '(:noweb . "yes")
            (assq-delete-all :noweb org-babel-default-header-args)))

When you are unsure which value a block will actually see, put point in it and press C-c C-v I (org-babel-view-src-block-info): it displays the language, name and the merged header arguments. C-c C-v j (org-babel-insert-header-arg) inserts an argument with completion, and C-c C-v c (org-babel-check-src-block) reports misspelled ones.

Passing data between blocks and tables

Most of Babel’s power comes from the :var header argument. It binds a variable in the block to a value, and the value can be a literal, a named table, a named list, a named example block, or the result of another named block. The syntax is the same in every language:

:var NAME=VALUE

Here a table of expenses feeds a Python block, which feeds an Emacs Lisp block:

#+NAME: expenses
| item   | amount |
|--------+--------|
| rent   |   1200 |
| food   |    450 |
| travel |    180 |

#+NAME: total
#+BEGIN_SRC python :var rows=expenses
return sum(amount for _, amount in rows)
#+END_SRC

#+RESULTS: total
: 1830

#+NAME: share
#+BEGIN_SRC emacs-lisp :var sum=total() :var people=3
(/ sum people)
#+END_SRC

#+RESULTS: share
: 610

Several points are visible here:

  • A table arrives as a list of rows. Because the table has a header row followed by a rule, Org removed the header before passing it, so rows contains only the data rows.
  • total() with parentheses means “evaluate the block named total and use its result”. Inside the parentheses you can pass arguments: total(rows=other-table).
  • Numbers in tables arrive as numbers, so the code can add them without conversion.
flowchart LR
  T["#+NAME: expenses<br/>(table)"] -->|":var rows=expenses"| P["#+NAME: total<br/>(python)"]
  P -->|":var sum=total()"| L["#+NAME: share<br/>(emacs-lisp)"]
  L -->|"result"| R1["#+RESULTS: share"]
  L -->|"call_share(people=2)"| I["inline result in a sentence"]
  N["#+NAME: header-comment"] -->|"noweb reference"| C["#+NAME: config<br/>(:noweb yes)"]
  C -->|"tangle"| F["source file"]

Figure 14.4: :var passes values and results between blocks at evaluation time, while noweb references splice code into other blocks.

Column names and row names

When the input table has a header row separated by a rule, the default :colnames nil removes the header before the code runs and puts it back on the result. With :colnames yes the first row is treated as a header even without a rule; with :colnames no Org does no header processing at all. Here the header survives the transformation:

#+BEGIN_SRC python :var rows=expenses :colnames yes
return [[item.upper(), amount * 2] for item, amount in rows]
#+END_SRC

#+RESULTS:
| item   | amount |
|--------+--------|
| RENT   |   2400 |
| FOOD   |    900 |
| TRAVEL |    360 |

:rownames yes does the same for the first column. The related :hlines argument decides whether horizontal rules inside a table are passed through (yes) or removed (no, the default for ordinary blocks).

Indexing into a value

Square brackets after a reference select part of it. Indexes start at 0, negative indexes count from the end, a comma separates dimensions, a:b selects an inclusive range, and an empty index or * selects everything in that dimension. Indexing happens before header processing, so the header row and the rule below it count as rows 0 and 1:

#+BEGIN_SRC emacs-lisp :var cell=expenses[2,1]
cell
#+END_SRC

#+RESULTS:
: 1200

Lisp values

A value that starts with (, [, ' or ` is evaluated as Emacs Lisp before the block runs. This gives a block information about its environment, such as the file it lives in:

#+BEGIN_SRC emacs-lisp :var file=(file-name-nondirectory (buffer-file-name))
file
#+END_SRC

#+RESULTS:
: var.org

Values read from tables and lists are never evaluated this way, so a cell containing (a b c) stays a string.

Calling a block like a function

A named block with :var defaults behaves like a function with default arguments. The #+CALL: keyword calls it from anywhere in the document and inserts the result below the call:

#+CALL: share(people=4)

#+RESULTS:
: 457

The full syntax allows header arguments in two places. Arguments in brackets after the name (inside header arguments) apply when the block runs; arguments after the closing parenthesis (end header arguments) apply to the result of the call:

#+CALL: <name>[<inside header arguments>](<arguments>) <end header arguments>

The inline form, call_<name>(<arguments>), puts the result into running text:

Each person pays call_share(people=2) {{{results(=915=)}}} per month.

A block in another file can be called by prefixing its name with the file name: #+CALL: tools.org:clean-data(). Table formulas can call blocks as well, through the org-sbe function described in The Spreadsheet and Plotting.

The environment of a block

Sessions

By default every evaluation starts a fresh interpreter process that ends when the block finishes. This keeps blocks independent, but it also means that a variable defined in one block does not exist in the next. The :session header argument runs blocks in a shared, long-lived interpreter instead:

#+BEGIN_SRC python :session demo
counter = 10
#+END_SRC

#+RESULTS:
: None

#+BEGIN_SRC python :session demo
counter += 5
counter
#+END_SRC

#+RESULTS:
: 15

#+BEGIN_SRC python
counter
#+END_SRC

The last block runs outside the session, where counter is undefined, so the Python process fails and Org inserts no result. Notice also that in a session the value of the last expression is the result, without return, because Org reads it from the interactive interpreter.

Sessions suit exploratory work: load a large data set once and query it from many small blocks. Their cost is hidden state. The document no longer describes the full computation, because the result of a block depends on which blocks ran before it and in what order. Before you share a document built with sessions, restart the session and run the buffer from the top (C-c C-v b).

A session is a buffer you can visit. C-c C-v z (org-babel-switch-to-session-with-code) opens it next to the code. Not every language supports sessions; C and ditaa, for example, do not, and Emacs Lisp blocks always run inside Emacs itself.

Working directory, prologue and epilogue

:dir sets the working directory for one evaluation, and it accepts remote TRAMP paths, so a block can run on another machine. :mkdirp yes creates the directory when it is missing.

#+BEGIN_SRC shell :dir /tmp
pwd
#+END_SRC

#+RESULTS:
: /tmp

:prologue and :epilogue add code before and after the body at execution time, without showing it in the block:

#+BEGIN_SRC shell :prologue "set -e" :epilogue "echo finished"
echo working
#+END_SRC

#+RESULTS:
| working  |
| finished |

They are most useful as defaults, for example a reset command before every gnuplot block, set in org-babel-default-header-args:gnuplot.

Controlling when code runs

Caching expensive blocks

With :cache yes, Org stores a SHA1 hash of the block’s code and arguments on the result line. On the next evaluation, if the hash still matches, Org returns the stored result without running the code:

#+NAME: slow
#+BEGIN_SRC emacs-lisp :cache yes
(* 3 14)
#+END_SRC

#+RESULTS[90b23cf30fa76883bba5b3579e5c75468e1a7ff4]: slow
: 42

The hash covers the arguments, including the values of :var references, so a cached block that depends on another block re-runs when the upstream result changes. Caching is safe only for pure computations: code whose result depends only on its inputs. A block that reads the clock, the file system or a random number generator should not be cached, and caching inside sessions can give surprising results. The hash also ignores code pulled in by noweb references.

Limiting evaluation

The :eval header argument decides whether a block may run at all:

ValueMeaning
yesRun, subject to the confirmation setting (default).
never or noNever run.
queryAlways ask before running.
never-export or no-exportDo not run during export, but allow interactive runs.
query-exportAsk before running during export.
#+BEGIN_SRC emacs-lisp :eval never
(error "never runs")
#+END_SRC

:eval never is a good way to keep a dangerous or slow block in a document as documentation. :eval never-export is the usual choice for a report whose results you have already computed and checked by hand.

Exporting code blocks

When you export a document, the :exports header argument decides what each block contributes:

ValueExported content
codeThe code only (default for ordinary blocks).
resultsThe result only (default for inline blocks).
bothThe code followed by the result.
noneNothing.

Given this file:

#+OPTIONS: toc:nil
#+TITLE: Export demo

#+NAME: answer
#+BEGIN_SRC emacs-lisp :exports both
(* 6 7)
#+END_SRC

#+BEGIN_SRC emacs-lisp :exports results
(format "Computed during export: %d" (+ 1 2))
#+END_SRC

#+BEGIN_SRC emacs-lisp :exports none
(message "not exported")
#+END_SRC

#+BEGIN_SRC emacs-lisp
"code only"
#+END_SRC

Inline: src_emacs-lisp{(+ 40 2)}.

the Markdown exporter produces:

    (* 6 7)

    42

    Computed during export: 3

    "code only"

Inline: `42`.

Two blocks were evaluated during the export, because their results were needed. Org does not evaluate blocks whose results are not exported (code or none), except blocks that use a session, which follow their :eval setting. Org also evaluates blocks in subtrees excluded from export, but never in commented subtrees.

Two settings turn evaluation off during export:

  • :eval never-export on a block (or as a buffer-wide property) stops evaluation but still processes the other header arguments, so existing results are exported as they are.
  • Setting org-export-use-babel to nil disables Babel entirely during export. Header arguments then have no effect at all: :exports is ignored, and every block is exported as code.

A name on a block also names its result in the export, so a link to a block exported with :exports results points to the result. The Exporting chapter covers the export process itself.

Tangling: extracting source files

Tangling writes the bodies of code blocks to ordinary source files. It is how a literate program becomes a program again, and how an Org configuration file becomes init.el. The :tangle header argument decides where each block goes:

  • no (default): the block is not tangled;
  • yes: tangle to a file named after the Org file, with an extension derived from the language;
  • a file name: tangle to that file, relative to the Org file’s directory.

Several blocks may tangle to the same file; Org writes them in document order. C-c C-v t (org-babel-tangle) tangles the whole buffer, and with a prefix argument only the current block. C-c C-v f (org-babel-tangle-file) asks for a file to tangle.

The following file defines a small Python program and tangles every block to greet.py:

#+PROPERTY: header-args:python :tangle yes :comments link

* Imports
#+BEGIN_SRC python
import sys
#+END_SRC

* Entry point
#+BEGIN_SRC python
def main(name):
    print(f"Hello, {name}")

if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else "world")
#+END_SRC

Running org-babel-tangle produced greet.py:

# [[file:greet.org::*Imports][Imports:1]]
import sys
# Imports:1 ends here

# [[file:greet.org::*Entry point][Entry point:1]]
def main(name):
    print(f"Hello, {name}")

if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else "world")
# Entry point:1 ends here

The comment lines come from :comments link. They let you jump from the tangled file back to the Org source with org-babel-tangle-jump-to-org, and they let org-babel-detangle copy edits made in the tangled file back into the Org blocks. Org reindents the bodies when it writes them back, using org-src-content-indentation.

The tangling header arguments:

ArgumentPurpose
:commentsno (default), link, org (the preceding text as a comment), both, or noweb (link comments around expanded references too).
:padlineyes (default) puts a blank line between blocks; no does not.
:shebangA first line such as "#!/bin/sh"; the file is also made executable.
:tangle-modeFile permissions, such as o755, rw-r--r-- or (identity #o444).
:mkdirpyes creates missing parent directories.
:no-expandWrite the body without expanding variables and noweb references.

Blocks in commented subtrees (headings that start with COMMENT) are never tangled, which gives a quick way to switch off part of a configuration.

Four hooks let you act around tangling: org-babel-pre-tangle-hook runs in the Org buffer before tangling (by default it saves the buffer), org-babel-tangle-body-hook runs on each expanded body, org-babel-post-tangle-hook runs in each tangled file (useful for byte-compiling or formatting), and org-babel-tangle-finished-hook runs at the end in the Org buffer.

Noweb references: composing code from pieces

Tangling block after block in document order works when the order of explanation matches the order the compiler needs. Often it does not: you want to explain the main loop first and the helper functions later, or show a long script in small annotated steps. Noweb references, named after an early literate programming tool, solve this. A block can contain a reference of the form <<name>>, and Org replaces it with the body of the block called name.

Noweb expansion is off by default, because <<...>> can be valid code in many languages. The :noweb header argument turns it on and chooses when it applies:

ValueEvaluateTangleExport
no (default)nonono
yesexpandexpandexpand
tanglenoexpandno
no-exportexpandexpandno
strip-exportexpandexpandreferences removed
strip-tangleexpandreferences removedexpand
evalexpandnono

Here is a complete literate shell script. The top block shows the overall structure; the details come later, under their own headings:

#+TITLE: A literate backup script
#+PROPERTY: header-args:shell :noweb yes

* The script
The script is assembled from the pieces below.

#+BEGIN_SRC shell :tangle bin/backup.sh :mkdirp yes :shebang "#!/bin/sh"
set -eu
<<settings>>
<<archive>>
#+END_SRC

* Settings
#+NAME: settings
#+BEGIN_SRC shell
SRC="$HOME/notes"
DEST="/tmp/backup"
#+END_SRC

* Steps
:PROPERTIES:
:header-args:shell+: :noweb-ref archive
:END:

** Make sure the destination exists
#+BEGIN_SRC shell
mkdir -p "$DEST"
#+END_SRC

** Write the archive
#+BEGIN_SRC shell
tar -czf "$DEST/notes-$(date +%F).tar.gz" -C "$SRC" .
#+END_SRC

Tangling creates bin/backup.sh with mode rwxr-xr-x (because of :shebang) and this content:

#!/bin/sh
set -eu
SRC="$HOME/notes"
DEST="/tmp/backup"
mkdir -p "$DEST"
tar -czf "$DEST/notes-$(date +%F).tar.gz" -C "$SRC" .

Two kinds of reference appear in this example:

  • <<settings>> refers to the block named settings.
  • <<archive>> refers to every block whose :noweb-ref header argument is archive. Here the property drawer of the “Steps” heading gives that argument to both blocks below it, and Org concatenates their bodies in document order, separated by newlines (change the separator with :noweb-sep). This is how you split one logical piece of code across several explained steps.

Only the top block has a :tangle argument, so the pieces are tangled only through the references.

Inserting results instead of code

Parentheses after the name, as in <<name()>> or <<name(arg=value)>>, insert the result of evaluating the named block rather than its body. Noweb also respects a prefix: when a reference has text before it on the line, every line of the inserted text gets the same prefix. That is how a multi-line block can be turned into a comment, or indented to the right level:

#+NAME: today
#+BEGIN_SRC emacs-lisp
"2026-11-19"
#+END_SRC

#+NAME: header-comment
#+BEGIN_SRC text
Generated from notes.org.
Do not edit by hand.
#+END_SRC

#+NAME: config
#+BEGIN_SRC shell :noweb yes
# <<header-comment>>
BUILD_DATE=<<today()>>
#+END_SRC

C-c C-v v (org-babel-expand-src-block) shows how a block will look after expansion, without running it. For config it shows:

# Generated from notes.org.
# Do not edit by hand.
BUILD_DATE=2026-11-19

Set :noweb-prefix no when you want a multi-line expansion inserted as it is, for example inside a string literal. Note that noweb expansion copies code only; the :var arguments of the referenced block are not carried along.

The Library of Babel

Named blocks are reusable within a file, and file.org:name makes them reusable across files. The Library of Babel goes one step further: it is a global collection of named blocks that any Org file can call by name alone. You add the named blocks of a file to it with org-babel-lob-ingest (C-c C-v i):

* Reusable blocks
#+NAME: word-count
#+BEGIN_SRC emacs-lisp :var text=""
(length (split-string text))
#+END_SRC

After ingesting this file, any Org buffer can call the block:

#+CALL: word-count(text="Org mode keeps code and prose together")

#+RESULTS:
: 7

To have the library available in every session, ingest your library files from your init file:

(with-eval-after-load 'org
  (org-babel-lob-ingest "~/org/library.org"))

Key bindings

Babel commands live under the prefix C-c C-v; each key also works with Control held (C-c C-v C-t equals C-c C-v t). C-c C-v h lists them all.

KeyCommandPurpose
C-c C-c, C-c C-v eorg-babel-execute-src-block / org-babel-execute-maybeEvaluate the block at point.
C-c 'org-edit-specialEdit the block in its language’s mode.
C-c C-v borg-babel-execute-bufferEvaluate all blocks in the buffer.
C-c C-v sorg-babel-execute-subtreeEvaluate all blocks in the subtree.
C-c C-v korg-babel-remove-result-one-or-manyRemove the result (all results with a prefix).
C-c C-v n, C-c C-v porg-babel-next-src-block / org-babel-previous-src-blockMove between blocks.
C-c C-v gorg-babel-goto-named-src-blockJump to a named block.
C-c C-v oorg-babel-open-src-block-resultOpen the result in a separate buffer.
C-c C-v vorg-babel-expand-src-blockPreview the expanded body.
C-c C-v Iorg-babel-view-src-block-infoShow the merged header arguments.
C-c C-v dorg-babel-demarcate-blockSplit the block at point, or wrap the region in a new block.
C-c C-v torg-babel-tangleTangle the buffer.
C-c C-v forg-babel-tangle-fileTangle a file.
C-c C-v iorg-babel-lob-ingestAdd a file’s blocks to the Library of Babel.
C-c C-v zorg-babel-switch-to-session-with-codeShow the session buffer.

Running Babel from the command line

Babel works without an interactive Emacs, which makes it suitable for build scripts and continuous integration. Start Emacs with --batch, load Org, and call the same functions the keys call. This script tangles every file given on the command line:

#!/bin/sh
# tangle.sh FILE...
emacs -Q --batch --eval "
  (progn
    (require 'ob-tangle)
    (dolist (file command-line-args-left)
      (with-current-buffer (find-file-noselect file)
        (org-babel-tangle))))
" "$@"

Tangling does not run code, so it needs no confirmation settings. Evaluation does, and in batch mode there is no one to answer the prompt. For a script that evaluates a document you trust, set the confirmation variable inside the batch run only:

;; run-notebook.el: emacs -Q --batch -l run-notebook.el notebook.org
(require 'org)
(org-babel-do-load-languages
 'org-babel-load-languages '((emacs-lisp . t) (shell . t) (python . t)))
(let ((org-confirm-babel-evaluate nil))
  (with-current-buffer (find-file-noselect (car command-line-args-left))
    (org-babel-execute-buffer)
    (save-buffer)))

The let binding limits the change to this one run; your normal Emacs keeps asking. The examples in this chapter were produced with a script of this kind.

Code evaluation and security

A code block is a program. Evaluating a block from an Org file you downloaded is as risky as running a script from the same source: it can delete files, read secrets or send data over the network. Export is a second path to the same risk, because exporting a document evaluates every block whose results are exported. Org therefore treats evaluation as something you must allow, block by block.

The central setting is org-confirm-babel-evaluate:

  • t (the default): Org asks before evaluating each block, with a question such as “Evaluate this python code block (total) on your system?”.
  • nil: Org evaluates without asking.
  • a function: Org calls it with the language and the expanded body, and asks only if the function returns non-nil.

The function form gives a middle ground. This configuration skips the prompt for two diagram languages whose blocks only draw pictures, and keeps it for everything else:

(defun my-babel-confirm (lang _body)
  "Ask before evaluating any block except diagram blocks."
  (not (member lang '("dot" "ditaa"))))

(setq org-confirm-babel-evaluate #'my-babel-confirm)

Org protects this variable from the files it opens. Its safe-local-variable property accepts only the value t, so a file cannot switch confirmation off through file-local variables. A malicious file can still put :eval yes on its blocks, but yes only means “evaluate, subject to org-confirm-babel-evaluate”, so the prompt still appears.

Some practical rules follow from this:

  • Keep the default t globally. If the prompts become tiresome, use a function that exempts specific languages, or bind the variable to nil with let in scripts that process your own files, as in the batch example above.
  • Read a document before you evaluate or export it, when it comes from someone else. Header arguments count as code too: a :var value that starts with ( is Emacs Lisp, evaluated when the block runs.
  • Mark blocks that must never run with :eval never, and blocks that must not run during export with :eval never-export.
  • To export untrusted documents, set org-export-use-babel to nil. Org then evaluates nothing during export and ignores all header arguments.
  • If you want C-c C-c never to run code by accident, set org-babel-no-eval-on-ctrl-c-ctrl-c to t and use C-c C-v e deliberately.

Code blocks are not the only executable content in Org. shell: and elisp: links run code when you follow them, and their prompts are controlled by org-link-shell-confirm-function and org-link-elisp-confirm-function (both yes-or-no-p by default). Table formulas also run Calc or Emacs Lisp code. The Org Beyond the Basics chapter discusses these together.

Further reading

Exporting

An Org file is a good place to think, but sooner or later other people need to read what you wrote, and they rarely use Emacs. Exporting turns one Org document into HTML, Markdown, plain text, LaTeX and PDF, OpenDocument, Texinfo, iCalendar and more, while keeping the structure (headlines, lists, tables) and the markup (emphasis, links, code) intact.

This chapter starts with the everyday path (one key sequence, one output file), then shows how to control what is exported and how, and ends with the machinery you can extend: hooks, filters and derived backends. Publishing whole sets of files is the subject of the next chapter, Publishing and Citations; evaluation of code blocks during export is covered in Working with Source Code.

All examples below were run with Org 9.8.13 in emacs -Q --batch, and the outputs are pasted from those runs. Where an output was long, it is trimmed and the cut is mentioned in the text.

The idea: one source, many backends

Org does not convert text with a set of regular expressions. It parses the buffer into a tree of elements and objects (the same tree that the element API exposes, see Hacking and Extending Org), and then hands that tree to a backend. A backend is a library that knows how to turn each kind of node (a headline, a table cell, a bold word) into the target format. Each of these per-node functions is called a transcoder.

Because every backend reads the same tree, a single source file can feed several outputs without any change. The library names follow the pattern ox-NAME:

BackendLibraryOutputLoaded by default
asciiox-asciiPlain text in ASCII, Latin-1 or UTF-8yes
htmlox-htmlHTML (XHTML or HTML5)yes
icalendarox-icalendar.ics calendar filesyes
latexox-latexLaTeX, and PDF through a LaTeX engineyes
odtox-odtOpenDocument Text (.odt)yes
beamerox-beamerLaTeX Beamer slidesno
mdox-mdMarkdown (original syntax)no
orgox-orgA normalized Org fileno
texinfoox-texinfoTexinfo and Info manualsno
manox-manMan pagesno
koma-letterox-koma-letterLetters with the KOMA-Script classno

The “loaded by default” column reflects the default value of org-export-backends, which is (ascii html icalendar latex odt). You can add more in two ways. Either set the variable (with setq it must happen before Org loads; through the Customize interface it also works later), or simply require the library:

;; Option 1: before Org is loaded
(setq org-export-backends '(ascii html icalendar latex odt md org))

;; Option 2: at any time
(with-eval-after-load 'org
  (require 'ox-md)
  (require 'ox-beamer))

Third-party packages follow the same naming scheme, so a search for ox- in the package archives finds further backends.

The export dispatcher

Exporting interactively

Every export starts from one command: C-c C-e (org-export-dispatch). It opens a menu with one letter per backend and, under each letter, one letter per action. For example, C-c C-e h h writes file.html next to file.org, and C-c C-e h o writes it and opens it in a browser. Capital letters usually mean “export to a temporary buffer” rather than to a file, which is useful for a quick look:

KeysFunctionResult
C-c C-e h horg-html-export-to-htmlfile.html
C-c C-e h Horg-html-export-as-htmlbuffer *Org HTML Export*
C-c C-e t a / t uorg-ascii-export-to-asciifile.txt (ASCII / UTF-8)
C-c C-e m morg-md-export-to-markdownfile.md (after loading ox-md)
C-c C-e l l / l porg-latex-export-to-latex / org-latex-export-to-pdffile.tex / file.pdf
C-c C-e l b / l Porg-beamer-export-to-latex / org-beamer-export-to-pdfBeamer .tex / .pdf
C-c C-e o oorg-odt-export-to-odtfile.odt
C-c C-e O oorg-org-export-to-orgfile.org.org
C-c C-e i t / i iorg-texinfo-export-to-texinfo / org-texinfo-export-to-info.texi / .info
C-c C-e c forg-icalendar-export-to-icsfile.ics
C-c C-e P ...org-publish and friendssee Publishing and Citations

Output files are overwritten without a question, so do not keep hand edits in them.

Scope and toggles

By default the whole buffer is exported. If a region is active, only the region is exported. Inside the dispatcher, a few C- keys change the scope or the shape of the output before you choose a backend:

  • C-s exports only the subtree at point. The subtree’s headline becomes the document title. This is how one Org file can hold many small documents (a handout, a status report, a letter), each exported on its own.
  • C-v exports only the visible text, so you can fold or narrow the buffer (for example with a sparse tree) and export what you see.
  • C-b produces the body only, without the surrounding document structure (no <html> and <head> in HTML, no preamble in LaTeX). Use it when the output will be pasted into a template or a CMS.
  • C-a runs the export asynchronously in a separate Emacs process. The results go to the export stack, which C-u C-u C-c C-e (or & inside the dispatcher) displays.
  • C-f forces publishing of unchanged files; it matters only for the P commands.

A plain C-u before C-c C-e repeats the last export with the same options, which is the fastest way to re-export while editing.

Each toggle has a variable for its default: org-export-initial-scope (buffer or subtree), org-export-visible-only, org-export-body-only, org-export-in-background and org-export-force-publishing. For asynchronous export, org-export-async-init-file names the init file that the child Emacs loads. Without it the child loads your full user-init-file, so a small file that only sets up Org and your export settings makes background exports start faster. If you prefer a minibuffer prompt to the full-screen menu, set org-export-dispatch-use-expert-ui to t (? brings back the menu).

Exporting from the command line and from Lisp

Every export command can also run without a user. This is how you integrate Org into a Makefile or a CI job:

emacs --batch report.org --eval '(require (quote ox-md))' -f org-md-export-to-markdown

Emacs visits report.org, loads the Markdown backend and writes report.md. In Lisp, three functions cover most needs:

  • org-export-to-file writes the result of a backend to a file.
  • org-export-as returns the result of the current buffer as a string. Its arguments are the backend, then subtreep, visible-only, body-only and an ext-plist of extra options.
  • org-export-string-as converts a string of Org text without a buffer of your own.
(require 'ox-md)
(org-export-string-as
 "Ship *v2* soon, see [[https://orgmode.org][Org]]."
 'md t '(:with-toc nil))

The result:

Ship **v2** soon, see [Org](https://orgmode.org).

The last argument is an export option plist. Every option you can set with a keyword also has a property name such as :with-toc; the next section explains how these layers relate.

Export settings

Where settings come from

An export option can be set at four levels, and the more specific level wins:

flowchart LR
  A["Global variables<br/>org-export-with-toc ..."] -->|overridden by| B["External plist<br/>ext-plist, publishing project"]
  B -->|overridden by| C["In-buffer keywords<br/>#+TITLE, #+OPTIONS, #+SETUPFILE"]
  C -->|overridden by| D["Subtree properties<br/>EXPORT_TITLE, EXPORT_OPTIONS"]
  D --> E[Export options used]

Figure 15.1: Export options are merged from the general to the specific, so a subtree property beats a file keyword, which beats a global variable.

The order is visible in the source of org-export-get-environment, which combines the global options, the external plist, the in-buffer settings and, for a subtree export, the subtree properties, in that order. Subtree properties are read only when you export a subtree (C-s in the dispatcher).

The practical consequence: put your personal defaults in variables, put document decisions in keywords at the top of the file, and use EXPORT_ properties for documents that live inside a larger file. If several files share the same keywords, move them into one file and pull it in with #+SETUPFILE: path/to/common.org.

Keywords

In-buffer settings are keywords of the form #+KEYWORD: value, usually at the top of the file. The ones every backend understands are:

KeywordMeaningGlobal default
TITLEDocument title (several lines are joined)buffer name
AUTHORAuthoruser-full-name
EMAILEmail addressuser-mail-address
DATEDate or timestampnone
LANGUAGELanguage for generated strings such as “Table of Contents”org-export-default-language
CREATORName of the producing softwareorg-export-creator-string
SELECT_TAGSTags that select subtreesorg-export-select-tags, ("export")
EXCLUDE_TAGSTags that remove subtreesorg-export-exclude-tags, ("noexport")
EXPORT_FILE_NAMEOutput file name without extensionderived from the buffer

Backends add their own keywords, for example HTML_HEAD and HTML_DOCTYPE for HTML or LATEX_CLASS and LATEX_HEADER for LaTeX. To avoid typos, type #+ and complete with M-TAB, or press # inside the dispatcher to insert a template with all keywords of a backend.

The OPTIONS line

#+OPTIONS: packs many switches into one line as name:value pairs. You can repeat the keyword to spread them over several lines. The most useful items are:

ItemEffectVariable
toc:nil, toc:2No table of contents, or limit its depthorg-export-with-toc
num:nil, num:2No section numbers, or number only to a levelorg-export-with-section-numbers
H:3Deepest level exported as a heading; deeper ones become list itemsorg-export-headline-levels
todo:nil, tags:nil, pri:tShow or hide TODO keywords, tags, priority cookiesorg-export-with-todo-keywords, org-export-with-tags, org-export-with-priority
tasks:nil, tasks:todoDrop all task headlines, or only the done onesorg-export-with-tasks
p:t, c:t, d:t, prop:tInclude planning lines, clock lines, drawers, property drawersorg-export-with-planning …
author:nil, date:nil, title:nil, email:tShow or hide document metadataorg-export-with-author …
^:{}Treat a_b literally but a_{b} as a subscriptorg-export-with-sub-superscripts
\n:tKeep line breaks as they areorg-export-preserve-breaks
broken-links:markMark broken internal links instead of abortingorg-export-with-broken-links
timestamp:nilDo not stamp the creation time into the outputorg-export-timestamp-file

The full list has more than 30 items; see the manual’s Export Settings node.

Subtree settings

When you export a subtree, keywords become properties with an EXPORT_ prefix: EXPORT_TITLE, EXPORT_AUTHOR, EXPORT_OPTIONS, EXPORT_FILE_NAME and so on. Every keyword in the table above has such a twin, except SETUPFILE. The next example combines this with selection by tags.

Choosing what gets exported

A notebook mixes material for readers with material for yourself. Org offers several tools to keep the private part out of the output, and they work at different granularities.

ToolGranularityCode blocks inside are evaluated?
# comment lineone linenot applicable
#+BEGIN_COMMENT … #+END_COMMENTa blocknot applicable
COMMENT keyword in a headline (C-c ;, org-toggle-comment)a subtreeno, and not tangled either
:noexport: tag (or any tag in EXCLUDE_TAGS)a subtreeyes
:export: tag (or any tag in SELECT_TAGS)keeps only tagged subtreesyes
tasks: item in OPTIONStask headlinesyes

The difference in the last column matters when a subtree contains code with side effects: a COMMENT subtree is removed before Babel runs, while a noexport subtree is removed only after the code has run. The pipeline in Figure 15.2 below shows why.

Consider this file:

#+TITLE: Team Notebook
#+OPTIONS: toc:nil author:nil date:nil

Preamble text before the first headline.

* Meeting 2026-11-02
Agreed to ship on Friday.
* Handout                                                           :export:
:PROPERTIES:
:EXPORT_TITLE: Onboarding Handout
:EXPORT_OPTIONS: num:nil
:EXPORT_FILE_NAME: handout
:END:
Welcome to the team.
** DONE Get a laptop
** TODO Read the style guide
** Secrets                                                        :noexport:
The Wi-Fi password.

Exporting the whole buffer to ASCII gives:

                            _______________

                             TEAM NOTEBOOK
                            _______________


1 Handout                                                       :export:
=========

  Welcome to the team.


1.1 DONE Get a laptop
~~~~~~~~~~~~~~~~~~~~~


1.2 TODO Read the style guide
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Three things happened. Because one subtree carries the export tag, only that subtree was selected, and the meeting notes disappeared. The preamble text vanished too: when select tags are in use, text before the first headline is never exported. Finally, Secrets was removed by its noexport tag. The tag itself still shows in the heading; add tags:nil to OPTIONS if you do not want that.

Now place point on Handout, export the subtree (C-c C-e C-s t a), and set org-export-with-tasks to todo:

                          ____________________

                           ONBOARDING HANDOUT
                          ____________________


Welcome to the team.


TODO Read the style guide
=========================

The title now comes from EXPORT_TITLE, section numbers are off because of EXPORT_OPTIONS, and the finished task was dropped. Since the subtree also sets EXPORT_FILE_NAME, the file version is written to handout.txt instead of notes.txt.

Tables of contents

By default, Org puts a table of contents (TOC) at the start of the document, with all headline levels. #+OPTIONS: toc:2 limits the depth and toc:nil removes it. To place a TOC elsewhere, turn off the default and insert a #+TOC: keyword where you want it:

#+TITLE: Guide
#+OPTIONS: toc:nil author:nil date:nil title:nil

Intro paragraph.
#+TOC: headlines 2

* Install
** On Linux
** On macOS
* Configure
:PROPERTIES:
:ALT_TITLE: Config
:END:
#+TOC: headlines 1 local
** Basic
** Advanced
* Changelog
:PROPERTIES:
:UNNUMBERED: notoc
:END:

UTF-8 export (C-c C-e t u) produces:

Intro paragraph.
Table of Contents
─────────────────

1. Install
.. 1. On Linux
.. 2. On macOS
2. Config
.. 1. Basic
.. 2. Advanced


1 Install
═════════

1.1 On Linux
────────────


1.2 On macOS
────────────


2 Configure
═══════════

  .. 1. Basic
  .. 2. Advanced


2.1 Basic
─────────


2.2 Advanced
────────────


Changelog
═════════

The example shows four controls:

  • #+TOC: headlines 2 inserts a TOC of two levels at that position.
  • #+TOC: headlines 1 local inside a section lists only that section’s children, which is useful for long chapters.
  • The ALT_TITLE property gives a headline a shorter entry in the TOC (“Config” instead of “Configure”).
  • UNNUMBERED: notoc removes the number from “Changelog” and keeps it, with its children, out of every TOC. A plain UNNUMBERED: t removes only the number.

#+TOC: tables and #+TOC: listings produce lists of captioned tables and code listings. #+TOC: headlines 1 :target #some-id builds a TOC of another section, identified by its CUSTOM_ID; it works in HTML, Markdown, ODT and ASCII.

Including other files

Large documents become easier to manage when you split them. The #+INCLUDE: keyword copies another file (or part of it) into the document at export time. The source file stays untouched; the inclusion happens on a temporary copy of the buffer.

The keyword takes a file name, then an optional block type and language:

  • #+INCLUDE: "chapter2.org" inserts Org text. Its headlines become children of the current section.
  • #+INCLUDE: "lib.el" src emacs-lisp wraps the file in a source block, so code examples always match the real file.
  • #+INCLUDE: "page.html" export html wraps it in an export block.

Several parameters narrow the selection:

  • :lines "5-10" includes lines 5 to 9 (the upper bound is excluded); "-10" and "10-" leave one end open.
  • A search option after :: picks one element, as in a file link: "paper.org::*Conclusion" for a headline, "paper.org::#theory" for a CUSTOM_ID.
  • :only-contents t drops the headline, its planning line and its property drawer, and keeps the body.
  • :minlevel 2 shifts the included headlines so that the highest one is at level 2.

Here is a book file that pulls in code and text from two other files:

#+TITLE: Include Demo
#+OPTIONS: toc:nil num:nil author:nil date:nil title:nil

* Code
The greeting function:
#+INCLUDE: "lib.el" src emacs-lisp :lines "1-4"

* From the chapter
#+INCLUDE: "chapter.org::#usage" :only-contents t
#+INCLUDE: "chapter.org::*Setup" :minlevel 2

with chapter.org:

* Setup
Install the package first.
* Usage
:PROPERTIES:
:CUSTOM_ID: usage
:END:
Call =greet= with a name.
** Options
There are none yet.

The quickest way to see what an inclusion produces is to export to Org itself (C-c C-e O O after loading ox-org), because the Org backend prints the expanded document:

#+options: toc:nil num:nil author:nil date:nil title:nil
* Code
The greeting function:
#+begin_src emacs-lisp
  (defun greet (name)
    "Return a greeting for NAME."
    (format "Hello, %s!" name))
#+end_src
* From the chapter
Call =greet= with a name.
** Options
There are none yet.
** Setup
Install the package first.

Notice that :only-contents kept the Options child of Usage, and that :minlevel 2 turned the level-1 Setup into a level-2 heading. With point on an INCLUDE line, C-c ' (org-edit-special) opens the included file.

Macros

A macro is a named piece of text that Org substitutes during export. Macros are handy for values that appear many times (a product name, a version) and for small computed strings. Define them with #+MACRO:, or globally in org-export-global-macros, and call them with three braces:

#+TITLE: Macro Demo
#+MACRO: product Orgle
#+MACRO: ver version $1 (build $2)
#+MACRO: upper (eval (upcase $1))
#+OPTIONS: toc:nil num:nil author:nil date:nil title:nil

{{{product}}} {{{ver(2.0, 417)}}} ships today. Shout it: {{{upper(done)}}}.

Step {{{n}}}: install. Step {{{n}}}: configure. Step {{{n}}}: run.

This file is {{{input-file}}}, titled "{{{title}}}".

ASCII export gives:

Orgle version 2.0 (build 417) ships today. Shout it: DONE.

Step 1: install. Step 2: configure. Step 3: run.

This file is macros.org, titled "Macro Demo".

Arguments are referenced as $1, $2 and so on, and are separated by commas (escape a literal comma as \,). A replacement that starts with (eval is evaluated as Emacs Lisp, with the arguments bound as strings. Org also predefines several macros:

MacroExpands to
{{{title}}}, {{{author}}}, {{{email}}}The corresponding keyword
{{{keyword(NAME)}}}All values of any keyword NAME
{{{date}}}, {{{date(FORMAT)}}}The DATE keyword, optionally reformatted
{{{time(FORMAT)}}}The export time
{{{modification-time(FORMAT, VC)}}}The file’s modification time, from version control if VC is non-nil
{{{input-file}}}The name of the exported file
{{{property(NAME)}}}A property of the current entry, or of a remote entry given as a search option
{{{n}}}, {{{n(NAME)}}}, {{{n(NAME, ACTION)}}}An auto-incrementing counter; - holds the value, a number sets it, any other string resets it

Macros work in paragraphs, headlines, lists, table cells, verse blocks and in keywords such as TITLE, AUTHOR, DATE and CAPTION. Avoid redefining results, because inline code blocks use it. If the braces clutter your buffer, org-hide-macro-markers hides them, and org-export-replace-macros set to nil disables expansion entirely.

Speaking directly to one backend

Sometimes you need a construct that Org has no syntax for: a <kbd> tag in HTML, a \newpage in LaTeX. Org lets you pass raw text to one backend while every other backend ignores it.

  • An export snippet @@html:...@@ works inline.
  • The keyword #+HTML: ... (or #+LATEX:, #+ASCII: …) works for one line.
  • An export block #+BEGIN_EXPORT html … #+END_EXPORT works for many lines.
  • An attribute line such as #+ATTR_HTML: adds attributes to the element that follows it.
#+TITLE: Snippets
#+OPTIONS: toc:nil num:nil author:nil date:nil

Press @@html:<kbd>@@C-c C-e@@html:</kbd>@@ to export.@@ascii: (Keyboard shortcut.)@@

#+ATTR_HTML: :class wide :alt Architecture diagram
[[file:arch.png]]

#+BEGIN_EXPORT html
<aside class="note">Only HTML readers see this.</aside>
#+END_EXPORT

The HTML body (C-b in the dispatcher) is:

<p>
Press <kbd>C-c C-e</kbd> to export.
</p>


<div id="orgd50719d" class="figure">
<p><img src="arch.png" alt="Architecture diagram" class="wide" />
</p>
</div>

<aside class="note">Only HTML readers see this.</aside>

and the ASCII body is:

Press C-c C-e to export. (Keyboard shortcut.)

<file:arch.png>

Each backend kept its own snippets and dropped the others. Snippets also travel through derived backends: Markdown is derived from HTML, so @@html:...@@ snippets appear in Markdown output as well.

The built-in backends at a glance

The same small file serves as input for the comparisons below:

#+TITLE: Release Notes
#+AUTHOR: Ada Example
#+DATE: 2026-11-19
#+OPTIONS: toc:nil num:t

Version 2.0 brings *faster* search and a /new/ plugin API.

* Highlights
- Search is about 3x faster.
- Plugins can register commands.

* TODO Write migration guide
* Internal notes                                                   :noexport:
Do not ship the debug build.
* Benchmarks
| Query | v1 (ms) | v2 (ms) |
|-------+---------+---------|
| short |     120 |      40 |
| long  |     900 |     310 |

HTML

The HTML backend is the most complete one. Body-only output of the file above (trimmed after the second section) looks like this:

<p>
Version 2.0 brings <b>faster</b> search and a <i>new</i> plugin API.
</p>
<div id="outline-container-org9f54f56" class="outline-2">
<h2 id="org9f54f56"><span class="section-number-2">1.</span> Highlights</h2>
<div class="outline-text-2" id="text-1">
<ul class="org-ul">
<li>Search is about 3x faster.</li>
<li>Plugins can register commands.</li>
</ul>
</div>
</div>
<div id="outline-container-org4c5f174" class="outline-2">
<h2 id="org4c5f174"><span class="section-number-2">2.</span> <span class="todo TODO">TODO</span> Write migration guide</h2>
</div>

Every structural part gets a CSS class (outline-2, section-number-2, todo, timestamp, tag and so on), so a stylesheet can target them. The id values such as org9f54f56 are generated and change between exports; give a headline a CUSTOM_ID property when you need a stable anchor.

A full document adds a <head>, a default style sheet, some JavaScript and a postamble (a footer with author, date and a validation link). For a modern, clean page, ask for HTML5 and switch the extras off. The html-style and html-scripts items of OPTIONS control the built-in CSS and scripts:

#+TITLE: Tiny Page
#+AUTHOR: Ada Example
#+DATE: 2026-11-19
#+HTML_DOCTYPE: html5
#+HTML_HEAD: <link rel="stylesheet" href="style.css" />
#+OPTIONS: toc:nil num:nil html-style:nil html-scripts:nil

Hello from Org.

With org-export-timestamp-file set to nil, the complete output is:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Tiny Page</title>
<meta name="author" content="Ada Example" />
<meta name="generator" content="Org Mode" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="content" class="content">
<h1 class="title">Tiny Page</h1>
<p>
Hello from Org.
</p>
</div>
<div id="postamble" class="status">
<p class="date">Date: 2026-11-19</p>
<p class="author">Author: Ada Example</p>
<p class="validation"><a href="https://validator.w3.org/check?uri=referer">Validate</a></p>
</div>
</body>
</html>

The postamble is built automatically because org-html-postamble defaults to auto. Set it to nil, to a format string, or to a function returning a string. org-html-preamble works the same way for a header above the content. A configuration for bare HTML pages, with every variable taken from the manual’s Bare HTML node, is:

(setq org-html-doctype "html5"
      org-html-head ""
      org-html-head-extra ""
      org-html-head-include-default-style nil
      org-html-head-include-scripts nil
      org-html-preamble nil
      org-html-postamble nil
      org-html-use-infojs nil)

Links to other .org files become links to .html files (controlled by org-html-link-org-files-as-html), which is what makes multi-page sites work; see Publishing and Citations. Math is rendered with MathJax by default (org-html-mathjax-options, keyword HTML_MATHJAX).

Markdown

The Markdown backend follows the original Markdown syntax. It is derived from the HTML backend, so anything Markdown cannot express falls back to HTML. Tables are the most visible case. C-c C-e m m on the release notes produces report.md (trimmed inside the table):

Version 2.0 brings **faster** search and a *new* plugin API.


# Highlights

-   Search is about 3x faster.
-   Plugins can register commands.


# TODO Write migration guide


# Benchmarks

<table border="2" cellspacing="0" cellpadding="6" rules="groups" frame="hsides">
...
<tr>
<td class="org-left">short</td>
<td class="org-right">120</td>
<td class="org-right">40</td>
</tr>
...
</table>

Two details stand out. The #+TITLE does not appear, because the Markdown template returns only the body; put the title in a top-level headline or in front matter of your own if your target needs it. And the noexport subtree is gone, as in every backend. org-md-headline-style chooses between atx (# headings, the default), setext (underlined, two levels only) and mixed; org-md-toplevel-hlevel sets the Markdown level of top-level headlines. If you need pipe tables or fenced code blocks, a derived backend can add them in a few lines; the last section of this chapter builds one.

ASCII, Latin-1 and UTF-8

The text backend fills paragraphs to org-ascii-text-width (72 columns by default) and underlines headings. The three variants differ only in org-ascii-charset (ascii, latin1 or utf-8), which the dispatcher keys t a, t l and t u set for you. Plain text output is the best way to check what a document actually contains, which is why this chapter uses it so often:

                            _______________

                             RELEASE NOTES

                              Ada Example
                            _______________


                               2026-11-19


Version 2.0 brings *faster* search and a /new/ plugin API.


1 Highlights
============

  - Search is about 3x faster.
  - Plugins can register commands.


2 TODO Write migration guide
============================


3 Benchmarks
============

   Query  v1 (ms)  v2 (ms) 
  -------------------------
   short      120       40 
   long       900      310 

Links become footnote-like references collected before the next heading (org-ascii-links-to-notes). Two special blocks, #+BEGIN_JUSTIFYLEFT and #+BEGIN_JUSTIFYRIGHT, align text, and #+ATTR_ASCII: :width 10 sets the width of a horizontal rule.

LaTeX and PDF

The LaTeX backend targets print-quality documents. C-c C-e l p writes the .tex file and runs the commands in org-latex-pdf-process to build a PDF; the engine (pdflatex, xelatex or lualatex) comes from org-latex-compiler or the LATEX_COMPILER keyword. The body of the release notes is:

Version 2.0 brings \textbf{faster} search and a \emph{new} plugin API.
\section{Highlights}
\label{sec:orge3b3863}
\begin{itemize}
\item Search is about 3x faster.
\item Plugins can register commands.
\end{itemize}
\section{{\bfseries\sffamily TODO} Write migration guide}
\label{sec:orgd67671a}
\section{Benchmarks}
\label{sec:orgec6e440}
\begin{center}
\begin{tabular}{lrr}
Query & v1 (ms) & v2 (ms)\\
\hline
short & 120 & 40\\
long & 900 & 310\\
\end{tabular}
\end{center}

Document classes come from org-latex-classes and the LATEX_CLASS keyword; extra preamble lines go into #+LATEX_HEADER:. Packages loaded by default are listed in org-latex-default-packages-alist, and your own additions belong in org-latex-packages-alist. Because LaTeX itself treats blank lines as paragraph breaks, blank lines in the Org source matter more here than in other backends.

Beamer

Beamer turns an outline into slides. Headlines at the frame level (set with H: in OPTIONS or with org-beamer-frame-level) become frames, and headlines above it become sections:

#+TITLE: Why Plain Text
#+OPTIONS: H:2 toc:nil num:nil
* Motivation
** One source, many outputs
- Notes become slides
- Slides become handouts
\section*{Motivation}
\label{sec:org54a4030}
\begin{frame}[label={sec:org9aa0fd8}]{One source, many outputs}
\begin{itemize}
\item Notes become slides
\item Slides become handouts
\end{itemize}
\end{frame}

Load ox-beamer, then use C-c C-e l b for the .tex file or C-c C-e l P for the PDF.

ODT, Org, Texinfo and man

  • ODT (C-c C-e o o) writes an OpenDocument Text file that LibreOffice and Word can open. It needs the zip program. org-odt-preferred-output-format can convert the result further, for example to doc or pdf, through an external converter.
  • Org (C-c C-e O o, after loading ox-org) writes a normalized copy with includes and macros expanded, Babel results computed, and content for other backends removed. It is the debugging tool for everything in this chapter.
  • Texinfo (C-c C-e i t, C-c C-e i i) produces GNU-style manuals; the Org manual itself is written in Org and exported this way.
  • man (ox-man, keys under C-c C-e M) writes man pages.

iCalendar

The iCalendar backend exports headlines that carry active timestamps as calendar events, so your Org schedule can appear in any calendar application. Tags become categories, and the ID property, if present, provides a stable UID:

#+TITLE: Calendar
* Team sync                                                         :work:
:PROPERTIES:
:ID:       7d1c0f3e-2a7b-4e5c-9a51-0b6f1f2c9e10
:LOCATION: Room 4
:END:
<2026-11-23 Mon 10:00-10:30>
Weekly status round.
* TODO Submit report
DEADLINE: <2026-11-27 Fri>

With org-icalendar-include-todo set to t, C-c C-e c f writes cal.ics (header lines trimmed):

BEGIN:VCALENDAR
VERSION:2.0
X-WR-CALNAME:cal
PRODID:-////Emacs with Org mode//EN
CALSCALE:GREGORIAN
BEGIN:VEVENT
DTSTAMP:20261119T092619Z
UID:TS1-7d1c0f3e-2a7b-4e5c-9a51-0b6f1f2c9e10
DTSTART:20261123T100000
DTEND:20261123T103000
SUMMARY:Team sync
LOCATION:Room 4
DESCRIPTION:<2026-11-23 Mon 10:00-10:30> Weekly status round.
CATEGORIES:work,cal
END:VEVENT
BEGIN:VTODO
UID:TODO-3f2a835a-82b2-4649-9dc0-55779302c29b
DTSTAMP:20261119T092620Z
DUE;VALUE=DATE:20261127
SUMMARY:Submit report
CATEGORIES:cal
SEQUENCE:1
PRIORITY:5
STATUS:NEEDS-ACTION
END:VTODO
END:VCALENDAR

The UID prefix (TS1-, TODO-) records which part of the entry produced the event, so one entry can yield several calendar items. Set org-icalendar-store-UID to write generated IDs back into the Org file, so that UIDs stay stable across exports. C-c C-e c a exports each file in org-agenda-files separately, and C-c C-e c c combines them into org-icalendar-combined-agenda-file. Timestamps without an end time get the length in org-agenda-default-appointment-duration (two hours if that is unset); org-icalendar-use-deadline and org-icalendar-use-scheduled decide which planning lines become events or task dates. The properties SUMMARY, DESCRIPTION, LOCATION, TIMEZONE and CLASS are copied when present. See Dates and Times for the timestamps themselves.

How an export runs

Everything so far has been configuration. To change the export process itself, you need a picture of its stages. Org never touches your buffer: it works on a temporary copy and goes through four phases.

flowchart TD
  A[Org buffer] -->|copy| B["Temporary buffer"]
  B --> C["before-processing hook"]
  C --> D["Expand #+INCLUDE, drop COMMENT trees, expand macros"]
  D --> E["Run Babel, apply :exports"]
  E --> F["before-parsing hook"]
  F -->|parse| G["Parse tree, pruned by tags and OPTIONS"]
  G -->|"parse-tree filters"| H["Backend transcoders, node by node"]
  H -->|"element and object filters"| I["Template: TOC, preamble, metadata"]
  I -->|"body and final-output filters"| J[Output string or file]

Figure 15.2: An export copies the buffer, rewrites the text, parses it into a tree, transcodes each node through the backend, and passes every stage through hooks or filters that you can extend.

The figure explains several behaviors seen earlier:

  • Includes and macros are expanded before parsing. That is why an included file may contain headlines and macros, and why a hook that inserts {{{input-file}}} still gets it expanded (see the example below).
  • COMMENT subtrees are removed before Babel runs, while noexport subtrees are removed only after parsing; their code has already been evaluated.
  • Once the tree exists, the buffer no longer matters. Changes must be made by hooks before parsing, or by filters and transcoders after it.

Hooks run on text, filters run on strings that transcoders produced, and derived backends replace transcoders. The rest of the chapter takes them in that order.

Hooks

Two abnormal hooks run in the temporary buffer. org-export-before-processing-functions runs first, before includes, macros and Babel. org-export-before-parsing-functions runs after them, just before parsing. Each function receives the backend name as a symbol and may edit the buffer freely.

The following hook inserts a line at the top of every exported document. Since it runs before macro expansion, it can use a macro:

(defun my-insert-source-note (_backend)
  "Insert a note at the top of the buffer before macros expand."
  (goto-char (point-min))
  (while (looking-at-p "^#\\+") (forward-line))
  (insert "Generated from {{{input-file}}}.\n\n"))

(add-hook 'org-export-before-processing-functions #'my-insert-source-note)

Use hooks for structural edits that are easier to express on text than on a tree: removing or reordering headlines, inserting boilerplate, or rewriting custom syntax into standard Org.

Filters

A filter is a function that receives the string a transcoder produced and may return a changed string. Filters are stored in variables named org-export-filter-TYPE-functions, where TYPE is an element or object type (headline, link, table, src-block, plain-text …) or one of the special stages parse-tree, options, body and final-output. Each filter receives three arguments: the text, the backend name, and the communication channel info, a plist with all export options and state. Returning nil leaves the text unchanged.

Here are two filters. The first replaces an internal code name in all plain text, for every backend. The second adds target="_blank" to external links, but only in HTML:

(defun my-filter-codename (text _backend _info)
  "Replace the internal codename in every piece of plain text."
  (replace-regexp-in-string "Bluebird" "Orgle" text t t))

(defun my-html-external-links (text backend _info)
  "Open external links in a new tab in HTML output."
  (when (and (org-export-derived-backend-p backend 'html)
             (string-match-p "href=\"https?:" text))
    (replace-regexp-in-string "<a href=" "<a target=\"_blank\" href=" text t t)))

(add-to-list 'org-export-filter-plain-text-functions #'my-filter-codename)
(add-to-list 'org-export-filter-link-functions #'my-html-external-links)

Together with the hook from the previous section, this input:

#+TITLE: Filters
#+OPTIONS: toc:nil num:nil author:nil date:nil title:nil

Bluebird is our new search engine. See [[https://orgmode.org][the Org site]] or [[#faq][the FAQ]].

* FAQ
:PROPERTIES:
:CUSTOM_ID: faq
:END:
Bluebird is fast.

exports to this HTML body:

<p>
Generated from filters.org.
</p>


<p>
Orgle is our new search engine. See <a target="_blank" href="https://orgmode.org">the Org site</a> or <a href="#faq">the FAQ</a>.
</p>
<div id="outline-container-faq" class="outline-2">
<h2 id="faq">FAQ</h2>
<div class="outline-text-2" id="text-faq">
<p>
Orgle is fast.
</p>
</div>
</div>

and to this Markdown:

Generated from filters.org.

Orgle is our new search engine. See [the Org site](https://orgmode.org) or [the FAQ](#faq).


<a id="faq"></a>

# FAQ

Orgle is fast.

The internal link kept its plain href, because the filter checks for http. Note also why the HTML filter tests the text as well as the backend: org-export-derived-backend-p is true for md, since Markdown is derived from HTML. Without the href= test, the filter would run on Markdown links too. Always think about derived backends when you write a backend test.

Filters for a single file

Filters are global variables, but sometimes one document needs its own. The #+BIND: keyword makes a variable buffer-local during export, and it can bind a filter list. Because a file could use it to set any variable, BIND is ignored unless org-export-allow-bind-keywords is non-nil.

#+TITLE: Per-file filter
#+OPTIONS: toc:nil num:nil author:nil date:nil title:nil
#+BIND: org-export-filter-strike-through-functions (my-drop-strike)

#+BEGIN_SRC emacs-lisp :exports results :results none
(defun my-drop-strike (_text _backend _info) "")
#+END_SRC

The meeting is on +Monday+ Tuesday.

The code block defines the filter during export: it runs in the Babel phase, before the BIND values are read. By default Org asks for confirmation before it evaluates the block; the runs below set org-confirm-babel-evaluate to nil. ASCII export with default settings, then with org-export-allow-bind-keywords set to t:

--- default ---
The meeting is on +Monday+ Tuesday.

--- with org-export-allow-bind-keywords ---
The meeting is on Tuesday.

The struck-out word disappears only in the second run. Since this technique evaluates code from the document, apply it only to files you trust; Working with Source Code discusses org-confirm-babel-evaluate.

Derived backends

Filters edit strings after the fact. When you want to change how a whole kind of node is rendered, it is cleaner to replace its transcoder. org-export-define-derived-backend creates a new backend that inherits everything from a parent and overrides only the transcoders you list in :translate-alist.

flowchart LR
  N["Node, e.g. src-block"] --> Q{"In my-md<br/>translate-alist?"}
  Q -->|yes| M["my-md-src-block"]
  Q -->|no| P{"In md?"}
  P -->|yes| MD["md transcoder"]
  P -->|no| H["html transcoder"]
  M --> O[Output text]
  MD --> O
  H --> O

Figure 15.3: A derived backend looks up each node type in its own table first and falls back to its parent’s chain, so you write only the transcoders you want to change.

The Markdown backend writes code as indented blocks and tables as HTML. Many sites expect fenced code blocks with a language and pipe tables instead. A derived backend fixes both:

(require 'ox-md)

(defun my-md-src-block (src-block _contents info)
  "Transcode SRC-BLOCK into a fenced code block with a language tag."
  (format "```%s\n%s```"
          (or (org-element-property :language src-block) "")
          (org-export-format-code-default src-block info)))

(defun my-md-table-cell (_cell contents _info)
  "Transcode a table cell into one pipe-table cell."
  (concat " " (or contents "") " |"))

(defun my-md-table-row (row contents info)
  "Transcode ROW into a pipe-table line or a separator line."
  (if (eq (org-element-property :type row) 'rule)
      (let ((columns (cdr (org-export-table-dimensions
                           (org-element-lineage row 'table) info))))
        (concat "|" (apply #'concat (make-list columns "---|"))))
    (concat "|" contents)))

(defun my-md-table (_table contents _info)
  "Return the rows of a table unchanged."
  contents)

(org-export-define-derived-backend 'my-md 'md
  :translate-alist '((src-block . my-md-src-block)
                     (table . my-md-table)
                     (table-row . my-md-table-row)
                     (table-cell . my-md-table-cell))
  :menu-entry
  '(?m 1 ((?f "To fenced Markdown buffer"
              (lambda (a s v b)
                (org-export-to-buffer 'my-md "*Org my-md Export*"
                  a s v b nil (lambda () (text-mode))))))))

A transcoder takes three arguments: the node, its already transcoded contents (or nil for leaf nodes such as source blocks), and the info channel. Helper functions from ox.el do the hard work: org-export-format-code-default returns the code with any line numbers applied, and org-export-table-dimensions returns the number of rows and columns. A transcoder can also delegate to the parent for cases it does not handle, with (org-export-with-backend 'md node contents info).

The :menu-entry adds f under the existing m (Markdown) menu, so C-c C-e m f now exports with the new backend. Because the second element is a number (1) instead of a description, the dispatcher adds the item to the submenu that already exists under m instead of creating a new top-level letter.

For this input:

#+TITLE: Fenced
#+OPTIONS: toc:nil num:nil author:nil date:nil title:nil

* Example
Run this:
#+BEGIN_SRC python
print("hello")
#+END_SRC

| a | b |
|---+---|
| 1 | 2 |

the stock md backend writes (table trimmed):

# Example

Run this:

    print("hello")

<table border="2" cellspacing="0" cellpadding="6" rules="groups" frame="hsides">
...
</table>

while my-md writes:

# Example

Run this:

```python
print("hello")
```

| a | b |
|---|---|
| 1 | 2 |

The derived backend reused the parent for headlines, paragraphs and everything else. You can also add options with :options-alist, run filters specific to the backend with :filters-alist, or build a completely new backend with org-export-define-backend; Hacking and Extending Org covers that case.

Choosing the right tool

You want to …Use
Rewrite Org text before export (add, remove, reorder)org-export-before-processing-functions or org-export-before-parsing-functions
Adjust a string in the output of an existing backenda filter, org-export-filter-TYPE-functions
Do the same for one document only#+BIND: with org-export-allow-bind-keywords
Change how a whole kind of node is rendereda derived backend
Support a new output formatorg-export-define-backend

Converting a region in place

Some backends can also convert a region in place, replacing Org text in any buffer with the target format. This is useful when you edit an HTML or LaTeX file and want to write a table or list in Org syntax. Select the Org text and run one of these commands:

CommandAlias
org-ascii-convert-region-to-asciiorg-export-region-to-ascii
org-ascii-convert-region-to-utf8org-export-region-to-utf8
org-html-convert-region-to-htmlorg-export-region-to-html
org-latex-convert-region-to-latexorg-export-region-to-latex
org-md-convert-region-to-mdorg-export-region-to-md
org-texinfo-convert-region-to-texinfoorg-export-region-to-texinfo

For example, selecting

| tea | 3 |
| coffee | 4 |

and running M-x org-html-convert-region-to-html replaces it with (blank lines trimmed):

<table border="2" cellspacing="0" cellpadding="6" rules="groups" frame="hsides">
<colgroup>
<col  class="org-left" />
<col  class="org-right" />
</colgroup>
<tbody>
<tr>
<td class="org-left">tea</td>
<td class="org-right">3</td>
</tr>
<tr>
<td class="org-left">coffee</td>
<td class="org-right">4</td>
</tr>
</tbody>
</table>

For tables that must stay editable inside another major mode, Orgtbl mode with its send-and-receive mechanism is the better tool; see The Table Editor.

Summary

  • C-c C-e opens the dispatcher; C-s, C-v and C-b restrict scope and shape; C-u C-c C-e repeats the last export.
  • Options come from variables, then an external plist, then keywords, then EXPORT_ properties, with the most specific winning.
  • Tags, COMMENT, comment lines and the tasks option decide what reaches the output; only COMMENT prevents code evaluation.
  • #+TOC, #+INCLUDE and #+MACRO assemble a document; export to Org to see the expanded result.
  • Hooks edit text, filters edit strings, and derived backends replace transcoders.

Further reading

Publishing and Citations

Exporting converts one document at a time. A website, a set of course notes or a project’s documentation consists of many files that link to each other, share a style and sit next to images and stylesheets. Exporting each file by hand quickly becomes tedious and error-prone. Org’s publishing system describes such a collection once, as a project, and then rebuilds all of it, or only the parts that changed, with one command.

The second half of this chapter covers citations: references to entries in a bibliography, written with their own Org syntax and formatted by citation processors during export. Citations matter most for papers and theses, but they work in every backend, including HTML, so they fit well beside publishing.

All outputs below come from running Org 9.8.13 in emacs -Q --batch.

The idea: a project describes files, a destination and an action

A publishing project answers three questions:

  1. Which files? A base directory, a file extension (a regular expression) and optional include and exclude rules.
  2. Where to? A publishing directory, which can be local or remote.
  3. How? A publishing function that turns one source file into its output: export to HTML, export to PDF, or simply copy.

Every project is one entry in the variable org-publish-project-alist. An entry is a name followed by a property list:

("notes"
 :base-directory "~/notes/"
 :publishing-directory "~/public_html/"
 :publishing-function org-html-publish-to-html)

A project can also be a list of other projects, given as :components. Publishing such a meta-project publishes each component in turn. This is the usual way to combine Org pages (which need exporting) with static files (which need copying), because the two kinds of files need different publishing functions.

A complete small site

The rest of the first half builds one site and examines what Org produces. The source tree looks like this:

site/
  publish.el
  org/
    index.org
    about.org
    posts/
      first-post.org
      second-post.org
  static/
    css/style.css
    img/logo.svg

The Org pages link to each other with ordinary file: links. index.org:

#+TITLE: Ada's Notebook

Welcome. Read [[file:posts/first-post.org][my first post]] or the [[file:about.org::#contact][contact details]].

[[file:img/logo.svg]]

about.org:

#+TITLE: About
#+DATE: <2026-10-01>
#+INDEX: Contact

* Contact
:PROPERTIES:
:CUSTOM_ID: contact
:END:
Write to ada@example.org.

posts/first-post.org:

#+TITLE: First Post
#+DATE: <2026-11-02>
#+INDEX: Publishing!first steps

Back to the [[file:../index.org][home page]].

posts/second-post.org is similar, with #+DATE: <2026-11-15> and no index entry.

The configuration

publish.el defines three projects: one for pages, one for static files and one that combines them.

;;; publish.el --- publishing setup  -*- lexical-binding: t -*-
(require 'ox-publish)

(defvar my-root (file-name-directory (or load-file-name buffer-file-name)))

(setq org-publish-timestamp-directory (expand-file-name ".timestamps/" my-root))

(setq org-publish-project-alist
      `(("site-pages"
         :base-directory ,(expand-file-name "org/" my-root)
         :base-extension "org"
         :recursive t
         :publishing-directory ,(expand-file-name "public/" my-root)
         :publishing-function org-html-publish-to-html
         :section-numbers nil
         :with-toc nil
         :html-doctype "html5"
         :html-head "<link rel=\"stylesheet\" href=\"/css/style.css\" />"
         :html-head-include-default-style nil
         :html-head-include-scripts nil
         :html-postamble nil
         :auto-sitemap t
         :sitemap-filename "sitemap.org"
         :sitemap-title "All Pages"
         :sitemap-style list
         :sitemap-sort-files anti-chronologically
         :makeindex t)
        ("site-static"
         :base-directory ,(expand-file-name "static/" my-root)
         :base-extension "css\\|svg\\|png"
         :recursive t
         :publishing-directory ,(expand-file-name "public/" my-root)
         :publishing-function org-publish-attachment)
        ("site" :components ("site-pages" "site-static"))))

The backquote and commas build absolute paths from the location of publish.el, so the project works wherever the directory is checked out. Keeping the configuration in the repository, instead of in your personal init file, also lets a CI job or a colleague build the site.

flowchart LR
  S["site<br/>:components"] -->|"1st"| P["site-pages<br/>org-html-publish-to-html"]
  S -->|"2nd"| T["site-static<br/>org-publish-attachment"]
  OD["org/*.org"] -->|export| P
  SD["static/css, static/img"] -->|copy| T
  P -->|".html, sitemap, index"| OUT["public/"]
  T -->|"same relative paths"| OUT

Figure 16.1: The meta-project site publishes two components in order; one exports Org pages, the other copies static files, and both write into the same output tree.

Running it

Publishing is ordinary Emacs Lisp, so it runs in batch mode without any user interaction:

emacs --batch -l publish.el --eval '(org-publish "site" t)'

The second argument of org-publish is force; t publishes every file regardless of whether it changed. The messages of the first run show the order of events:

Generating sitemap for All Pages
Publishing file .../site/org/sitemap.org using 'org-html-publish-to-html'
Publishing file .../site/org/about.org using 'org-html-publish-to-html'
Publishing file .../site/org/posts/second-post.org using 'org-html-publish-to-html'
Publishing file .../site/org/posts/first-post.org using 'org-html-publish-to-html'
Publishing file .../site/org/index.org using 'org-html-publish-to-html'
Publishing file .../site/org/theindex.org using 'org-html-publish-to-html'
Resetting org-publish-cache
Publishing file .../site/static/img/logo.svg using 'org-publish-attachment'
Publishing file .../site/static/css/style.css using 'org-publish-attachment'

The resulting tree:

org/sitemap.org          (generated)
org/theindex.inc         (generated)
org/theindex.org         (generated)
public/about.html
public/css/style.css
public/img/logo.svg
public/index.html
public/posts/first-post.html
public/posts/second-post.html
public/sitemap.html
public/theindex.html

Note that Org writes the generated sitemap and index files into the source directory and then publishes them like any other page. Add them to your version control ignore list if you do not want to commit them.

When the HTML backend exports a link to another .org file, it rewrites the extension to .html and keeps the path relative. This is what makes a set of Org files work as a website. The body of public/index.html:

<h1 class="title">Ada's Notebook</h1>
<p>
Welcome. Read <a href="posts/first-post.html">my first post</a> or the <a href="about.html#contact">contact details</a>.
</p>


<div id="org36f252d" class="figure">
<p><img src="img/logo.svg" alt="logo.svg" class="org-svg">
</p>
</div>

and from public/posts/first-post.html:

Back to the <a href="../index.html">home page</a>.

Three kinds of links worked here:

  • Plain file links to other pages (file:posts/first-post.org) became .html links.
  • A link with a search option (file:about.org::#contact) became an anchor in the target page. Search options for headlines (::*heading) and targets (::target) are resolved in the same way.
  • The image link file:img/logo.svg was copied as it is. In the source tree it is broken, because org/img/logo.svg does not exist. In the published tree it works, because site-static copies static/img/ to public/img/, next to the HTML files.

The last point is the general rule for assets: design the output tree first, then write links that are correct relative to the published file. Either mirror the output layout in your sources (keep img/ beside the Org files), or accept, as here, that a link is resolved only in the published site. If you want a link to the Org source itself, use an http link, because file: links to .org files are always rewritten.

Selecting files

These properties decide which files belong to a project:

PropertyMeaning
:base-directoryWhere the source files live (required)
:base-extensionRegular expression for the extension, without the dot; default "org". The symbol any selects every file
:recursiveNon-nil to descend into subdirectories
:excludeRegular expression for file names to skip
:includeList of extra files, relative to the base directory, published regardless of extension and exclusion

Exclusion is applied first, then the :include list is added. A typical exclusion keeps drafts and private notes out of the site:

:exclude "\\`drafts/\\|private\\.org\\'"

Within a project that publishes Org files, finer control comes from the export settings of Exporting: a :noexport: subtree disappears from the page, a COMMENT subtree is removed before code runs, and a file can use #+SELECT_TAGS: to publish only some sections.

Publishing functions

:publishing-function takes either a function or a list of functions. With a list, every function runs on every file, so one project can produce several formats at once.

FunctionResult
org-html-publish-to-htmlHTML page (the default)
org-latex-publish-to-pdfPDF via LaTeX
org-latex-publish-to-latex.tex file
org-ascii-publish-to-ascii, org-ascii-publish-to-utf8Plain text
org-md-publish-to-mdMarkdown (load ox-md)
org-org-publish-to-orgCleaned-up Org file (load ox-org); with :htmlized-source t, also an htmlized copy of the source
org-publish-attachmentCopy the file unchanged

To offer every page as HTML and PDF:

:publishing-function (org-html-publish-to-html org-latex-publish-to-pdf)

You can write your own function. It receives three arguments: the project’s property list, the absolute name of the source file, and the publishing directory for this file. Most custom functions are thin wrappers around org-publish-org-to, the helper that the built-in functions use:

(defun my-publish-to-utf8-txt (plist filename pub-dir)
  "Publish FILENAME as UTF-8 text with a .txt extension."
  (org-publish-org-to 'ascii filename ".txt"
                      (plist-put plist :ascii-charset 'utf-8)
                      pub-dir))

Export options in a project

A project’s property list can carry any export option under its property name: :with-toc, :section-numbers, :with-author, :html-head, :html-postamble and so on. The site above used several of them to strip the default style and footer from every page. The full list of names is in the manual’s Publishing options node; every #+OPTIONS item and every backend variable has one.

The precedence follows the rule from Figure 15.1 in Exporting: the project plist is passed to the exporter as the external plist, so it overrides global variables, and keywords inside each file override the project. A page that needs a table of contents can therefore say #+OPTIONS: toc:t even though the project sets :with-toc nil.

Sitemaps

A sitemap is a generated page that lists all pages of a project. Turn it on with :auto-sitemap t. Org writes the list as an Org file (by default sitemap.org, or the name in :sitemap-filename) in the base directory and then publishes it like the other pages, so the sitemap gets the same style and can be linked from your home page.

For the site above, with :sitemap-style list and :sitemap-sort-files anti-chronologically, the generated sitemap.org is:

#+TITLE: All Pages

- [[file:index.org][Ada's Notebook]]
- [[file:posts/second-post.org][Second Post]]
- [[file:posts/first-post.org][First Post]]
- [[file:about.org][About]]

The order comes from each file’s date. org-publish-find-date uses the DATE keyword when it contains a timestamp and falls back to the file’s modification time otherwise. index.org has no DATE, so its modification time (today) put it first.

The properties that shape a sitemap are:

PropertyValues
:sitemap-titleTitle of the sitemap page
:sitemap-styletree (mirrors directories, the default) or list (flat)
:sitemap-sort-filesalphabetically (default), chronologically, anti-chronologically, or nil
:sitemap-sort-foldersfirst, last, ignore, or nil to mix; only for the list style
:sitemap-ignore-caseNon-nil for case-insensitive sorting
:sitemap-format-entryFunction that formats one entry
:sitemap-functionFunction that builds the whole page from the entries

The global defaults are org-publish-sitemap-sort-files and org-publish-sitemap-sort-folders. Note that the variable org-publish-sitemap-sort-folders defaults to ignore in the 9.8.13 source, although the manual describes first as the default; set the property explicitly if folder placement matters to you.

Formatting entries

A blog-style list usually shows dates. :sitemap-format-entry takes a function of three arguments (the entry’s file name relative to the base directory, the style, and the project) and returns the text of one item. The helpers org-publish-find-title, org-publish-find-date and org-publish-find-property read metadata from the file, and org-publish-sitemap-default-entry provides the default behavior for directories:

(defun my-sitemap-entry (entry style project)
  "Show the date before each page title in the site map."
  (if (directory-name-p entry)
      (org-publish-sitemap-default-entry entry style project)
    (format "%s [[file:%s][%s]]"
            (format-time-string "%Y-%m-%d" (org-publish-find-date entry project))
            entry
            (org-publish-find-title entry project))))

With this function and :sitemap-style tree, the sitemap becomes:

#+TITLE: All Pages

- 2026-11-19 [[file:theindex.org][Index]]
- 2026-11-19 [[file:index.org][Ada's Notebook]]
- 2026-10-01 [[file:about.org][About]]
- posts
  - 2026-11-15 [[file:posts/second-post.org][Second Post]]
  - 2026-11-02 [[file:posts/first-post.org][First Post]]

The posts directory became a nested list, and theindex.org, which existed by the time of this second run, now appears as an ordinary page. Exclude it with :exclude "theindex\\.org" if you do not want it listed. For full control over the page (a heading per year, an introduction paragraph), replace the whole generator with :sitemap-function; it receives the title and the entries as a nested list that org-list-to-org can turn into Org text.

An index across pages

With :makeindex t, Org collects every #+INDEX: keyword in the project into a single index page. An exclamation mark creates a sub-entry, so #+INDEX: Publishing!first steps appears under “Publishing”. Org writes the entries to theindex.inc and creates theindex.org (only if it does not exist yet), which merely includes it:

#+TITLE: Index

#+INCLUDE: "theindex.inc"

The generated theindex.inc for the example site:

* C
  - [[file:about.org][Contact]]
* P
  - Publishing
    - [[file:posts/first-post.org][first steps]]

Since Org never overwrites theindex.org, you can edit it freely, for example to add an introduction or a different title. Org publishes it after all other files, because the include file must be complete first.

Preparation and completion

Two properties attach your own code to the start and end of a project:

  • :preparation-function runs before any file is published. Use it to generate inputs: run make, render diagrams, fetch data.
  • :completion-function runs after the last file. Use it to post-process or deploy: fix permissions, compress, upload.

Both accept a function or a list of functions, each called with the project’s property list. A trivial example:

(defun my-announce (plist)
  (message "Finished %s into %s"
           (file-name-nondirectory (directory-file-name (plist-get plist :base-directory)))
           (plist-get plist :publishing-directory)))

With :completion-function my-announce, the log of a run ends with:

Finished org into .../site/public/

The order inside a project is fixed: preparation, sitemap, all files except the index, the index, completion.

flowchart TD
  A["org-publish project"] --> B[":preparation-function"]
  B --> C{"auto-sitemap?"}
  C -->|yes| D["Write sitemap.org"]
  C -->|no| E
  D --> E{"For each file:<br/>changed since last run?"}
  E -->|"yes, or force"| F[":publishing-function"]
  E -->|no| G["Skip"]
  F --> H{"makeindex?"}
  G --> H
  H -->|yes| I["Write theindex.inc, publish theindex.org"]
  H -->|no| J[":completion-function"]
  I --> J

Figure 16.2: Within one project, Org runs the preparation code, writes the sitemap, publishes only changed files, builds the index and finally runs the completion code.

Timestamps: publishing only what changed

Publishing a large site from scratch can take a while, so Org remembers when it last published each file. The records live in one cache file per project in org-publish-timestamp-directory (default ~/.org-timestamps/; the example moved it next to the project). On the next run, a file is published only if it is newer than its record.

A second run of the example site without changes, then a third run after appending a line to second-post.org, produce:

== run 2 (no change)
Generating sitemap for All Pages
Publishing file .../org/sitemap.org using 'org-html-publish-to-html'
Skipping unmodified file .../org/about.org
Skipping unmodified file .../org/posts/second-post.org
Skipping unmodified file .../org/posts/first-post.org
Skipping unmodified file .../org/index.org
Publishing file .../org/theindex.org using 'org-html-publish-to-html'
...
== run 3 (one edit)
Generating sitemap for All Pages
Publishing file .../org/sitemap.org using 'org-html-publish-to-html'
Skipping unmodified file .../org/about.org
Publishing file .../org/posts/second-post.org using 'org-html-publish-to-html'
Skipping unmodified file .../org/posts/first-post.org
Skipping unmodified file .../org/index.org
Publishing file .../org/theindex.org using 'org-html-publish-to-html'
...

The sitemap and the index are regenerated on every run, so they are always published; the ordinary pages are skipped unless they changed. Set org-publish-list-skipped-files to nil to hide the “Skipping” lines.

The check also looks inside each Org file for #+INCLUDE: keywords and compares the included files’ modification times. It does not follow #+SETUPFILE:. A quick test confirms both: after adding #+INCLUDE: "../parts/hours.txt" and #+SETUPFILE: ../parts/setup.org to about.org,

--- edit included file
Publishing file .../org/about.org using 'org-html-publish-to-html'
--- edit setupfile
Skipping unmodified file .../org/about.org

Other inputs that the cache cannot see include changes to publish.el itself, to global variables, and to files reached through links. Whenever such an input changes, force a full rebuild:

  • with a prefix argument to any publishing command (C-u C-c C-e P p),
  • with C-f inside the export dispatcher, or org-export-force-publishing as its default,
  • with t as the force argument of org-publish in Lisp,
  • or by setting org-publish-use-timestamps-flag to nil, which disables the cache altogether.

org-publish-remove-all-timestamps deletes the cache files, which has the same effect for the next run.

Triggering publication

The publishing commands live under P in the export dispatcher:

KeysCommandPublishes
C-c C-e P xorg-publishA project chosen by name
C-c C-e P porg-publish-current-projectThe project that contains the current file
C-c C-e P forg-publish-current-fileOnly the current file
C-c C-e P aorg-publish-allEvery project in org-publish-project-alist

All four accept a prefix argument to force publishing. C-a in the dispatcher runs them asynchronously, like any export.

For a reproducible build, prefer the batch form. A Makefile rule might look like this:

EMACS ?= emacs

public: publish.el $(wildcard org/*.org org/posts/*.org)
	$(EMACS) --batch -l publish.el --eval '(org-publish "site" t)'

Forcing in batch is usually the right choice: the cache lives outside the build’s inputs, so a clean build from a fresh checkout should not depend on it.

Uploading the result

The publishing directory may be remote. Any file name that Tramp understands works, for example "/ssh:user@host:~/html/", and Org then writes each file over the network. This is convenient for a few files but slow for many, and every small change still opens remote connections.

A local publishing directory plus a synchronization tool is usually faster and more reliable: tools such as rsync compare content and permissions, transfer only differences, and copy assets that are not part of any project. A completion function can run the upload right after publishing:

(defun my-upload (_plist)
  "Copy the published site to the web server."
  (let ((status (call-process "rsync" nil "*rsync*" nil
                              "-az" "--delete"
                              (expand-file-name "public/" my-root)
                              "user@example.org:/var/www/notes/")))
    (unless (eq status 0)
      (error "rsync failed with status %s; see buffer *rsync*" status))))

Attach it to the meta-project’s last component (here site-static), so that it runs once all files are in place. Since --delete removes remote files that no longer exist locally, try the command with --dry-run first.

Citations

A link points to exactly one target and displays whatever description you wrote. Academic writing needs more: a reference that is formatted according to a style (“Knuth (1984)”, “[1]”, a footnote), groups of references in one place, page numbers and prefixes such as “see”, and a bibliography that lists exactly the works cited. Org provides a separate citation syntax for this, and leaves the formatting to exchangeable citation processors.

The syntax

A citation is written in brackets, starts with cite, and contains one or more keys, each prefixed with @:

[cite:@knuth1984]
[cite:@knuth1984;@schulte2012]
[cite:see @schulte2012 p. 3; also @knuth1984]
[cite/t:@knuth1984]
  • Keys are separated by semicolons.
  • Text before a key is its prefix, text after it is its suffix (“see”, “p. 3”).
  • A slash after cite selects a style, such as t (text, for use inside a sentence) or author. Styles can have variants, as in cite/author/caps. Which styles exist depends on the export processor.
  • A citation without a style uses the default style named in #+CITE_EXPORT:, or the processor’s own default.

The bibliography itself is one or more files in BibTeX, BibLaTeX or CSL-JSON format. Declare them per document with #+BIBLIOGRAPHY: (repeat the keyword for several files), or for all documents with org-cite-global-bibliography. Mark where the reference list belongs with #+PRINT_BIBLIOGRAPHY:.

C-c C-x @ (org-cite-insert) inserts a citation with completion over the keys of all bibliographies; on an existing citation it edits it. C-c C-o on a citation follows it to the bibliography entry.

Processors and capabilities

Citation handling is split into four capabilities, and each one can use a different processor:

flowchart LR
  C["[cite:@key]"] --> A["activate<br/>org-cite-activate-processor"]
  C --> F["follow<br/>org-cite-follow-processor"]
  C --> I["insert<br/>org-cite-insert-processor"]
  C --> E["export<br/>org-cite-export-processors"]
  A -->|"faces, checks"| BUF[Org buffer]
  F -->|"C-c C-o"| BIB["Bibliography entry"]
  I -->|"C-c C-x @"| BUF
  E -->|"formatted text"| OUT["HTML, LaTeX, text ..."]

Figure 16.3: One citation is served by up to four processors: one for display, one for following, one for insertion, and one per backend for export.

The first three variables default to basic, the built-in processor that reads both BibTeX and CSL-JSON. Export processors are chosen per backend through org-cite-export-processors, whose default ((t basic)) uses basic everywhere. The built-in export processors are:

ProcessorTargetsNotes
basicAll backendsSimple author-year or numeric formatting, no external dependencies
cslHTML, LaTeX, ODT, plain textFormats with Citation Style Language files; requires the external citeproc package
bibtexLaTeX onlyUses BibTeX and \cite
natbibLaTeX onlyUses the natbib package for more citation commands
biblatexLaTeX onlyUses BibLaTeX and its citation commands

A common setup uses BibLaTeX for LaTeX and PDF output and a portable processor for everything else:

(require 'oc-biblatex)
(setq org-cite-global-bibliography '("~/bib/references.bib")
      org-cite-export-processors '((latex biblatex)
                                   (t basic)))

The lookup respects backend inheritance: Beamer is derived from LaTeX, so it would also use biblatex here.

Inside a document, #+CITE_EXPORT: overrides the variable. It takes up to three words: the processor, the bibliography style and the default citation style.

#+CITE_EXPORT: basic numeric numeric
#+CITE_EXPORT: csl ieee.csl
#+CITE_EXPORT: biblatex authoryear

A worked example

refs.bib holds two entries, knuth1984 (a book) and schulte2012 (a journal article). The document:

#+TITLE: Notes on Literate Programming
#+OPTIONS: toc:nil num:nil author:nil date:nil title:nil
#+BIBLIOGRAPHY: refs.bib

The idea goes back to [cite/t:@knuth1984]. Org Babel applies it to
many languages [cite:see @schulte2012 p. 3; also @knuth1984].

#+PRINT_BIBLIOGRAPHY:

With the default basic processor, ASCII export gives:

The idea goes back to Knuth, Donald E. (1984). Org Babel applies it to
many languages (see Schulte, Eric and Davison, Dan and Dye, Thomas and
Dominik, Carsten, 2012 p. 3, also Knuth, Donald E., 1984).

Knuth, Donald E. (1984). /Literate Programming/, Oxford University
Press.

Schulte, Eric and Davison, Dan and Dye, Thomas and Dominik, Carsten
(2012). /A Multi-Language Computing Environment for Literate Programming
and Reproducible Research/, Journal of Statistical Software.

The t style put the author into the sentence, the plain citation became a parenthetical group with prefixes and suffix, and #+PRINT_BIBLIOGRAPHY: listed exactly the two cited works.

Adding #+CITE_EXPORT: basic numeric numeric switches both the citations and the bibliography to numbers:

The idea goes back to Knuth, Donald E. (1984). Org Babel applies it to
many languages (1, 2).

[1] Knuth, Donald E., /Literate Programming/, Oxford University Press,
1984.

[2] Schulte, Eric and Davison, Dan and Dye, Thomas and Dominik, Carsten,
/A Multi-Language Computing Environment for Literate Programming and
Reproducible Research/, Journal of Statistical Software, 2012.

The explicit t style still wins over the default numeric style for the first citation, while the second one became “(1, 2)”. The basic processor’s numeric style dropped the prefixes and the page number, so check the output when you rely on them. HTML export of the same file produces the same text, with <i> for titles.

With org-cite-export-processors set to ((latex biblatex) (t basic)), the LaTeX body becomes:

The idea goes back to \textcite{knuth1984}. Org Babel applies it to
many languages \autocites[see][p. 3]{schulte2012}[also][]{knuth1984}.

\printbibliography

Now the formatting is left to BibLaTeX; prefixes and suffixes survive as the optional arguments of \autocites. The same Org source thus produces a quick text or HTML version and a typeset PDF, each with references handled by the tool best suited to the format.

Bibliography options

#+PRINT_BIBLIOGRAPHY: may appear several times, and with the csl and biblatex processors it accepts options to print only part of the bibliography:

#+PRINT_BIBLIOGRAPHY: :type book
#+PRINT_BIBLIOGRAPHY: :keyword "literate programming" :nottype article

The biblatex processor passes the options to \printbibliography. The csl processor understands :keyword, :notkeyword, :type, :nottype, :csltype, :notcsltype and :filter (an Emacs Lisp predicate). The LaTeX-based processors print a section heading above the list, while basic and csl print only the entries.

Citations in a published site

Citations work in published projects without extra configuration, because publishing calls the same exporters. Two points need attention. First, relative paths in #+BIBLIOGRAPHY: are resolved against the directory of each source file. Either use one global bibliography, or put the keyword in a shared #+SETUPFILE:; Org adjusts relative bibliography paths that come from a setup file in another directory. Second, the timestamp cache does not watch .bib files; force a rebuild after you change the bibliography.

Summary

  • A project in org-publish-project-alist names source files, a destination and a publishing function; :components combines projects.
  • Design the output tree first: published links are relative, and .org links become .html links.
  • Sitemaps (:auto-sitemap) and indexes (:makeindex) are generated Org files that are published like any page.
  • Org republishes only changed files, including directly included files; force a full rebuild when other inputs change.
  • Citations ([cite:@key]) are formatted by processors chosen per backend, with basic working everywhere and the LaTeX processors handing the work to LaTeX tools.

Further reading

Hacking and Extending Org

Org is written in Emacs Lisp, and almost every part of it is open to your own code. When a setting does not do what you need, you can add a function to a hook, query and change entries through a small API, read the document as a syntax tree, teach Org new kinds of links and dynamic blocks, or derive a new exporter from an existing one. This chapter shows each of these extension points with a working example.

The chapter assumes that you can read and write simple Emacs Lisp: defun, let, add-hook, setq. Every example was run with Org 9.8.13 in Emacs 31 in batch mode, and the output shown is the real output.

Choosing the right level

Before writing code, check whether a less invasive level solves the problem. Org offers its extension points at increasing levels of effort:

  1. Options. Org defines more than 1,000 user options. M-x customize-group RET org RET browses them, and C-h v describes one.
  2. Hooks. A hook is a variable holding a list of functions that Org calls at a defined moment, such as after a TODO state change. Hooks let you add behavior without changing Org’s code.
  3. Entry APIs. The property API and the mapping API read and change headings, tags and properties, which is enough for most automation.
  4. The element API. The parser turns a buffer into a tree of syntax nodes. Any code that needs to understand the document’s structure should start from this tree.
  5. New syntax handlers. Custom link types, dynamic block writers and export backends extend what Org syntax can mean.
flowchart LR
  U["user command"] -->|"runs"| H["hooks"]
  B["Org buffer"] -->|"org-element-parse-buffer"| T["parse tree"]
  T -->|"org-element-map"| Y["your analysis code"]
  B -->|"org-map-entries, org-entry-get"| Y
  T -->|"transcoders and filters"| X["export backend"]
  L["link at point"] -->|"org-link-parameters"| F[":follow / :export / :store"]
  D["#+BEGIN: name"] -->|"C-c C-x C-u"| W["org-dblock-write:name"]

Figure 17.1: Your code can attach to Org at several points: around commands (hooks), on the buffer and its tree (APIs), and in the handlers for links, dynamic blocks and export.

Finding documentation from the buffer

Two commands help you find the right variable or function. C-c C-x I (org-info-find-node) opens the section of the Org manual that matches the syntax at point: on a headline it shows “Document Structure”, on a table “Tables”, and in a code block “Working with Source Code”. Inside Emacs, C-h f and C-h v show the docstrings, which are often more detailed than the manual, and the link to the source file lets you read the implementation.

When you write Org files programmatically, M-x org-lint checks a buffer for common syntax mistakes and lists them with a trust level, since some reports may be false positives.

Hooks

Hooks are the lightest way to change behavior. You write a function and add it with add-hook; Org calls it at the right moment. Most hooks run with point on the relevant entry, so the function can use the property API described below.

Some of the hooks you are most likely to use:

HookRuns when
org-mode-hookA buffer enters Org mode.
org-after-todo-state-change-hookA TODO state has changed; the new state is in org-state.
org-blocker-hookBefore a state change; any function returning nil blocks it.
org-trigger-hookAfter a state change, with a property list describing it.
org-after-tags-change-hookTags of an entry have changed.
org-property-changed-functionsA property was set; called with the property name and value.
org-insert-heading-hookA new heading has been inserted.
org-cycle-hookAfter a visibility change by TAB.
org-capture-before-finalize-hookA capture is about to be filed.
org-clock-in-hook, org-clock-out-hookThe clock starts or stops.
org-agenda-finalize-hookAn agenda buffer has been built.
org-babel-after-execute-hookA code block has been evaluated.
org-export-before-processing-functionsExport starts, before macros, includes and Babel run.
org-export-before-parsing-functionsExport has expanded the buffer copy and is about to parse it.

The two export hooks are abnormal hooks: Org calls their functions with an argument (the backend symbol). Variables whose names end in -functions follow this convention throughout Emacs.

Reacting to a state change

Suppose you want to record when a task started waiting for someone, so that you can follow up after a week. A function on org-after-todo-state-change-hook can read the new state from the variable org-state and set a property:

(setq org-todo-keywords '((sequence "TODO" "WAITING" "|" "DONE")))

(defun my-note-waiting-start ()
  "Record when an entry enters the WAITING state."
  (when (equal org-state "WAITING")
    (org-entry-put nil "WAITING_SINCE"
                   (format-time-string (org-time-stamp-format t t)))))

(add-hook 'org-after-todo-state-change-hook #'my-note-waiting-start)

Changing * TODO Ask the client for feedback to WAITING produces:

* WAITING Ask the client for feedback
:PROPERTIES:
:WAITING_SINCE: [2026-11-19 Thu 04:27]
:END:

org-time-stamp-format with two t arguments returns the format of an inactive timestamp with a time, so the value looks like any other Org timestamp and can be searched in the agenda. The built-in logging features described in TODO Items cover many similar needs; a hook is the right tool when you need data in a property rather than a note.

Preventing a state change

org-blocker-hook receives a property list with :type, :position, :from and :to. If any function returns nil, the change does not happen. Org uses this hook itself to implement org-enforce-todo-dependencies. This function insists that a task records its outcome before it can be closed:

(defun my-require-outcome (change)
  "Block the change to DONE unless the entry has an OUTCOME property."
  (or (not (equal (plist-get change :to) "DONE"))
      (org-entry-get (plist-get change :position) "OUTCOME")))

(add-hook 'org-blocker-hook #'my-require-outcome)

With this hook active, org-todo on * TODO Review the pull request leaves the entry unchanged and reports TODO state change from TODO to DONE blocked. After the property is set, the change goes through:

* DONE Review the pull request
:PROPERTIES:
:OUTCOME:  approved
:END:

Blocker functions must not modify the buffer. When you call org-todo from Lisp, a blocked change fails silently with a message; when you press C-c C-t, it signals an error.

Small hooks worth knowing

Two one-line additions are common enough to show here. The first updates all dynamic blocks (see below) whenever an Org file is saved. The second refreshes image previews after a code block runs, so that a newly generated plot appears immediately:

(add-hook 'org-mode-hook
          (lambda ()
            (add-hook 'before-save-hook #'org-update-all-dblocks nil t)))

(add-hook 'org-babel-after-execute-hook #'org-link-preview-refresh)

The fourth argument t to the inner add-hook makes the hook buffer-local, so it runs only when saving Org buffers.

Working with entries: the property and mapping APIs

Many automation tasks are about entries: find the tasks that match a condition, read a property, set a tag. Org exposes two small APIs for this, and both work at the level of headings rather than raw text.

The examples in this section use this file:

#+TODO: TODO WAITING | DONE

* Project Alpha
:PROPERTIES:
:OWNER:    kim
:END:
** TODO Draft the proposal                                         :writing:
:PROPERTIES:
:EFFORT:   2:00
:END:
** WAITING Feedback from the client                                  :email:
** DONE Kick-off meeting
* Project Beta
** TODO Collect requirements                                     :writing:

Reading and writing properties

org-entry-get returns the value of a property for the entry at a position (nil means point). By default it looks only at the entry itself; with a non-nil third argument it also searches the ancestors. It also returns special properties, which Org computes from the entry: TODO, ALLTAGS, PRIORITY, SCHEDULED and others listed in Tags, Properties and Column View.

With point on “Draft the proposal”:

(list (org-entry-get nil "OWNER")
      (org-entry-get nil "OWNER" t)
      (org-entry-get nil "EFFORT")
      (org-entry-get nil "TODO")
      (org-entry-get nil "ALLTAGS"))

returns:

(nil "kim" "2:00" "TODO" ":writing:")

The first call returns nil because the entry has no OWNER of its own; the second finds it on the parent. Passing the symbol selective instead of t makes inheritance follow your org-use-property-inheritance setting.

org-entry-put sets a property, creating the drawer when necessary, and org-entry-delete removes one. For properties that hold several space-separated values there are org-entry-get-multivalued-property, org-entry-add-to-multivalued-property and related functions.

Mapping over entries

org-map-entries calls a function on every heading that matches a match string, the same syntax used by tag searches in the agenda. The function runs with point at the start of the heading, and the results are collected in a list:

(org-map-entries (lambda () (org-get-heading t t t t))
                 "+writing/TODO" 'file)
("Draft the proposal" "Collect requirements")

The match string +writing/TODO selects entries tagged writing whose TODO state is TODO. Passing t as the function makes each call return t, which turns org-map-entries into a counter:

(length (org-map-entries t "/+WAITING" 'file))   ; => 1

The third argument is the scope: nil for the current buffer (respecting narrowing), tree for the current subtree, region, file for the whole buffer, file-with-archives, agenda for all agenda files, agenda-with-archives, or an explicit list of files. Note that file uses the buffer’s file, so in a buffer that is not visiting a file it finds nothing; use nil there. Further arguments archive and comment skip archived and commented trees.

The mapped function can change the entry. This call tags every writing entry with review, and the earlier org-entry-put call adds a reviewer:

(org-entry-put nil "REVIEWER" "lee")   ; point on "Draft the proposal"
(org-map-entries (lambda () (org-toggle-tag "review" 'on)) "+writing" 'file)
** TODO Draft the proposal                                   :writing:review:
:PROPERTIES:
:EFFORT:   2:00
:REVIEWER: lee
:END:
** WAITING Feedback from the client                                  :email:
** DONE Kick-off meeting
* Project Beta
** TODO Collect requirements                                 :writing:review:

Org realigned the tags automatically. If your function deletes or moves the current subtree (for example by archiving it), set org-map-continue-from to the position where the search should resume, or Org may skip the next entry.

The element API: the document as a tree

The property and mapping APIs see a document as a list of headings. For anything finer (code blocks, links, timestamps inside paragraphs, list items) you need the parser. org-element.el turns the buffer into a tree of syntax nodes, and the exporter, the fontification and many editing commands all rely on that tree.

Org’s syntax has three kinds of node:

  • An element is a block-level construct that starts at the beginning of a line: a paragraph, a source block, a keyword, a table.
  • A greater element is an element that contains other elements: a headline, a section, a plain list, an item, a drawer.
  • An object is an inline construct inside an element: bold text, a link, a timestamp, an entity. Plain text between objects is represented as a string.

The Markup for Rich Contents chapter shows which constructs belong to which kind.

Parsing a buffer

Take this small file:

#+TITLE: Notes

* TODO Write report :work:
Draft the *summary* first.
- check [[https://orgmode.org][the site]]

org-element-parse-buffer returns the tree. Printed with indentation and a few properties per node, it looks like this:

org-data
  section
    keyword :key "TITLE" :value "Notes"
  headline :raw-value "Write report" :todo-keyword "TODO" :tags ("work") :level 1
    section
      paragraph
        plain-text "Draft the "
        bold
          plain-text "summary"
        plain-text "first.
"
      plain-list
        item
          paragraph
            plain-text "check "
            link :type "https" :path "//orgmode.org"
              plain-text "the site"
            plain-text "
"
flowchart TB
  D["org-data"] --> S1["section"]
  S1 --> K["keyword TITLE"]
  D --> H["headline: TODO Write report"]
  H --> S2["section"]
  S2 --> P1["paragraph"]
  P1 --> B["bold: summary"]
  S2 --> PL["plain-list"]
  PL --> I["item"]
  I --> P2["paragraph"]
  P2 --> L["link: https://orgmode.org"]

Figure 17.2: The parse tree of a 5-line file: greater elements (headline, section, plain-list, item) contain elements, and elements such as paragraphs contain objects.

Several details of the tree are worth noticing:

  • The text before the first heading lives in a top-level section.
  • The headline’s title, TODO keyword and tags are properties of the headline node, not children of it. The body lives in its section.
  • The space after *summary* does not appear in the next string, because it belongs to the bold object as its :post-blank (trailing whitespace) property.
  • The link’s description, “the site”, is the link’s content.

Each node is a list of the form (TYPE PROPERTIES . CONTENTS). Printing the raw headline node, with Lisp printing limited to 3 levels, shows this:

(headline (:standard-properties [17 17 44 113 113 0 ... nil nil nil nil 46 ...] :pre-blank 0 :raw-value "Write report" :title (#("Write report" 0 12 ...)) :level 1 :priority nil ...) (section (:standard-properties [44 44 44 113 113 0 nil section nil nil nil 44 ...]) (paragraph ... #("Draft the " 0 10 ...) ... #("first.
" 0 7 ...)) (plain-list ... ...)))

Common properties such as the start and end positions are packed into the :standard-properties vector, and some values are computed only on request. Do not read the property list directly; use the accessor functions:

FunctionReturns
org-element-typeThe node type, such as headline or link.
org-element-propertyOne property, for example (org-element-property :level node).
org-element-contentsThe list of child nodes.
org-element-begin, org-element-endBuffer positions of the node.
org-element-lineageThe ancestors of a node, optionally only those of given types.

The optional first argument of org-element-parse-buffer controls the depth of parsing, which matters for large files. headline parses only the outline, greater-element stops at top-level elements, element parses all elements but no objects, and object (the default) parses everything.

Searching the tree with org-element-map

org-element-map walks a tree and calls a function on every node of the given types, collecting the non-nil return values. Given this file:

* Setup
#+BEGIN_SRC shell
make install
#+END_SRC
See [[https://orgmode.org][Org]] and [[file:notes.org][my notes]].
* Analysis
#+BEGIN_SRC python
print("hi")
#+END_SRC
#+BEGIN_SRC python
print("again")
#+END_SRC

these calls answer three typical questions:

(let ((tree (org-element-parse-buffer)))
  ;; Which links does the file contain?
  (org-element-map tree 'link
    (lambda (l)
      (cons (org-element-property :type l)
            (org-element-property :path l))))
  ;; => (("https" . "//orgmode.org") ("file" . "notes.org"))

  ;; Under which heading is each code block?
  (org-element-map tree 'src-block
    (lambda (b)
      (org-element-property :raw-value
                            (org-element-lineage b 'headline))))
  ;; => ("Setup" "Analysis" "Analysis")
  )

and with a parse limited to headlines, which is much faster on a large file:

(org-element-map (org-element-parse-buffer 'headline) 'headline
  (lambda (h)
    (list (org-element-property :raw-value h)
          (org-element-begin h)
          (org-element-end h))))
;; => (("Setup" 1 117) ("Analysis" 117 213))

org-element-map accepts a list of types, or t for all types. A non-nil fifth argument (first-match) stops at the first non-nil result and returns it, which turns the function into a search.

The node at point

Interactive commands usually need only the node under the cursor, and parsing the whole buffer for that would be wasteful. Two functions answer the question locally, using a cache that Org keeps up to date as you edit:

  • org-element-at-point returns the element at point.
  • org-element-context returns the innermost object at point, or the element when there is no object.

With point on the URL in the example file:

(org-element-type (org-element-at-point))   ; => paragraph
(org-element-type (org-element-context))    ; => link
(mapcar #'org-element-type
        (org-element-lineage (org-element-context)))
;; => (paragraph item plain-list section headline org-data)

A command that should do something special on links, and something else on timestamps, typically starts with (org-element-context) and dispatches on org-element-type.

From tree back to text

org-element-interpret-data turns nodes back into Org text, and org-element-create builds new nodes. Together they let you generate Org syntax without assembling strings by hand:

(org-element-interpret-data
 (org-element-create 'headline
     '(:level 2 :title "Generated task" :todo-keyword "TODO" :tags ("auto"))
   (org-element-create 'section nil
     (org-element-create 'paragraph nil "Created from Lisp.\n"))))
** TODO Generated task                                                 :auto:
Created from Lisp.

The tree is a read model. Changing nodes in a parsed tree does not change the buffer; to modify the document, use editing commands or the property API, or replace a region with the interpreted text.

Org’s link syntax, [[type:path][description]], is extensible. A new link type is a name plus a set of functions registered with org-link-set-parameters. The Hyperlinks chapter introduces this from the user’s side; here we look at the parts you write.

Suppose your team refers to tracker issues as issue:1234. You want those links to open the tracker in a browser, and to export to a real URL. This is the whole implementation:

(require 'ol)

(defvar my-issue-url "https://tracker.example.com/issues/%s"
  "URL template for issue: links.")

(defun my-issue-follow (path _arg)
  (browse-url (format my-issue-url path)))

(defun my-issue-export (path desc backend _info)
  (let ((url (format my-issue-url path))
        (text (or desc (concat "#" path))))
    (cond
     ((org-export-derived-backend-p backend 'md)
      (format "[%s](%s)" text url))
     ((org-export-derived-backend-p backend 'html)
      (format "<a class=\"issue\" href=\"%s\">%s</a>" url text))
     (t (format "%s (%s)" text url)))))

(org-link-set-parameters "issue"
                         :follow #'my-issue-follow
                         :export #'my-issue-export
                         :face 'warning
                         :help-echo "Open the issue in the tracker")

Exported to HTML, the line See [[issue:1234]] and [[issue:99][the parser bug]]. becomes:

<p>
See <a class="issue" href="https://tracker.example.com/issues/1234">#1234</a> and <a class="issue" href="https://tracker.example.com/issues/99">the parser bug</a>.
</p>

and exported to Markdown:

See [#1234](https://tracker.example.com/issues/1234) and [the parser bug](https://tracker.example.com/issues/99).

The order of the tests in my-issue-export matters. The Markdown backend is derived from the HTML backend, so org-export-derived-backend-p returns true for html when exporting to Markdown. Test the more specific backend first.

flowchart LR
  L["[[issue:1234]]"] -->|"C-c C-o"| FO[":follow (path, prefix)"]
  L -->|"export"| EX[":export (path, desc, backend, info)"]
  L -->|"font lock"| FA[":face, :help-echo"]
  S["any buffer"] -->|"org-store-link"| ST[":store"]
  ST -->|"org-link-store-props"| C["stored link, inserted with C-c C-l"]

Figure 17.3: Each link parameter handles one moment in a link’s life: following, exporting, display, and storing.

The parameters you will use most:

ParameterPurpose
:followCalled by C-c C-o with the path and the prefix argument.
:exportCalled with path, description, backend and the export information; returns the backend’s text. When absent, the backend handles the link itself.
:storeCalled by org-store-link; returns non-nil after calling org-link-store-props when it can link to the current buffer.
:completeCalled by C-c C-l to build a link of this type with completion.
:faceFace for the link in the buffer, or a function of the path returning one.
:help-echoTooltip text, or a function producing it.
:previewA function that displays an inline preview (Org 9.8).

The full list, with the arguments each function receives, is in the docstring of org-link-parameters. The manual’s example of a link type for man pages, with a complete :store function, is also shipped as lisp/ol-man.el.

Dynamic blocks

A dynamic block is a region of the document whose content is generated by a function and replaced every time it is updated. Org itself uses them for clock tables and column views (Clocking, Effort and Timers). The block starts with #+BEGIN: followed by the block’s name and parameters, and ends with #+END::

#+BEGIN: task-count :match "TODO=\"TODO\""
#+END:

To make a block of a new type, define a function named org-dblock-write: followed by the block name. It receives the parameters as a property list and inserts the new content at point:

(defun org-dblock-write:task-count (params)
  (let* ((match (or (plist-get params :match) ""))
         (n (length (org-map-entries t match 'file))))
    (insert (format "Matching entries: %d" n))))
sequenceDiagram
  participant U as User
  participant O as org-dblock-update
  participant W as org-dblock-write:task-count
  U->>O: C-c C-x C-u on the BEGIN line
  O->>O: read parameters, erase old content
  O->>W: parameters as a plist, old text under content
  W->>O: inserts new content at point
  O->>U: block shows fresh result

Figure 17.4: Updating a dynamic block erases its content and calls the writer function named after the block.

C-c C-x C-u (org-dblock-update) updates the block at point; with a prefix argument, or through org-update-all-dblocks, it updates every block in the buffer. Given this file:

* TODO Draft
* TODO Review
* DONE Plan
* Summary
#+BEGIN: task-count :match "TODO=\"TODO\""
#+END:

an update produces:

#+BEGIN: task-count :match "TODO=\"TODO\""
Matching entries: 2
#+END:

The previous content is passed to the writer under :content, so a writer can also transform what is already there rather than replace it.

To offer your block in the insertion menu of C-c C-x x (org-dynamic-block-insert-dblock), register an insertion function with org-dynamic-block-define. org-create-dblock inserts the delimiters with the parameters you give, and org-update-dblock fills the new block:

(defun my-insert-task-count-dblock ()
  "Insert a task-count dynamic block and fill it."
  (interactive)
  (org-create-dblock (list :name "task-count" :match "TODO=\"TODO\""))
  (org-update-dblock))

(org-dynamic-block-define "task-count" #'my-insert-task-count-dblock)

Dynamic blocks and Babel code blocks overlap. A code block with :results drawer can also generate Org text. Prefer a dynamic block when the content summarizes the document itself and should be refreshed without a security prompt; prefer a code block when the computation belongs to the document’s content and should be visible, versioned with the text, and exportable as code.

Defining an export backend

The export engine in ox.el separates parsing from output. It turns the buffer into a parse tree (the same tree the element API produces), then calls one transcoder function per node type to produce text, then passes the result through filters. A backend is a named table of transcoders plus options and menu entries. The Exporting chapter describes the pipeline from the user’s side.

Writing a backend from scratch with org-export-define-backend means writing a transcoder for every node type, which is a large task; ox-latex.el and ox-html.el are full examples. Most customizations need much less: a derived backend, created with org-export-define-derived-backend, inherits all transcoders from a parent and replaces only the ones you list.

As an example, the Markdown backend exports source blocks as indented code, without a language. A derived backend can emit fenced blocks instead, and a filter can remove lines marked as drafts:

(require 'ox-md)

(defun my-fenced-src-block (src-block _contents info)
  "Transcode SRC-BLOCK into a fenced Markdown code block."
  (format "```%s\n%s```"
          (or (org-element-property :language src-block) "")
          (org-export-format-code-default src-block info)))

(defun my-fenced-drop-drafts (text _backend _info)
  "Remove lines that end with [DRAFT] from the final output."
  (replace-regexp-in-string "^.*\\[DRAFT\\]\n" "" text))

(org-export-define-derived-backend 'fenced-md 'md
  :translate-alist '((src-block . my-fenced-src-block))
  :filters-alist '((:filter-final-output . my-fenced-drop-drafts))
  :menu-entry
  '(?m 1
    ((?f "To fenced Markdown buffer"
         (lambda (a s v b)
           (org-export-to-buffer 'fenced-md "*Fenced MD*" a s v b))))))

For this input:

#+OPTIONS: toc:nil
* Example
Run this:

#+BEGIN_SRC shell
echo "hello"
#+END_SRC

Internal draft note. [DRAFT]

the parent backend md produces:

# Example

Run this:

    echo "hello"

Internal draft note. [DRAFT]

and the derived backend fenced-md produces:

# Example

Run this:

```shell
echo "hello"
```

The pieces of the definition:

  • A transcoder receives the node, its already transcoded contents (nil for nodes without contents, such as source blocks) and info, the communication channel: a property list with the export options and the parse tree. It returns a string. Helper functions such as org-export-format-code-default handle common work like line numbers and code references.
  • A filter receives the text produced for a node type (or, for :filter-final-output, the whole document), the backend and info, and returns the modified text. Filters can be attached to one backend with :filters-alist, or to every export through variables such as org-export-filter-headline-functions and org-export-filter-final-output-functions.
  • :menu-entry adds the backend to the dispatcher (C-c C-e). A number in the second position, as here, adds the entries as a submenu of an existing key (m for Markdown) rather than creating a new top-level entry.
  • :options-alist (not used here) declares new export keywords and options.

From Lisp, org-export-as, org-export-to-buffer, org-export-to-file and org-export-string-as run any backend, including your own.

Packaging your extensions

Once a hook function or link type works, give it a permanent home. A small personal extension can live in your init file; anything larger is easier to maintain as a separate file on your load-path that ends with (provide 'my-org-extras), loaded with require after Org:

(with-eval-after-load 'org
  (require 'my-org-extras))

Name your functions and variables with a personal prefix, as the examples in this chapter do with my-, so that they cannot collide with Org’s own names. Test them the way this chapter’s examples were produced: an emacs -Q --batch run that loads Org, loads your file, opens a sample Org file and prints the result. Such a test catches errors that your personal configuration might hide.

Before writing a new extension, check what already exists. Many add-on packages are listed on Worg, and some packages that were once part of Org now live in the separate org-contrib repository.

Further reading

Org Beyond the Basics

The earlier chapters treat Org as a closed world: you open a file, edit it, and run commands inside Emacs. Real work rarely stays that tidy. You read web pages in a browser and want to file them as tasks, you keep passwords next to project notes, you check your list on a phone, you paste screenshots, and you run Org inside a terminal or alongside packages that claim the same keys.

This chapter covers the points where Org meets the rest of your environment. It begins with the question that matters most once Org files can run code (what can execute, and how to control it), then moves through encryption, external access, mobile synchronization, files and images, other Emacs packages, and terminal use. The examples were run with Org 9.8.13, in batch Emacs or through a test Emacs server, and the outputs shown are the real ones. Where a step needs a browser or a clipboard, the text says what was run instead.

Code evaluation and trust

An Org file looks like a document, but several of its parts are programs. A source block is code in some language; a table formula is Calc or Emacs Lisp; certain link types run a shell command or a Lisp form when you follow them. Opening a file from someone else is therefore closer to running a script than to reading a text file, and Org asks for confirmation by default for exactly this reason.

The table below lists the places where an Org file can make Emacs do something on your behalf, together with the control that governs each one.

What runsWhenControl
Source blocksC-c C-c on the block, or during exportorg-confirm-babel-evaluate, the :eval header argument, org-export-use-babel
shell: linkswhen you follow the linkorg-link-shell-confirm-function, org-link-shell-skip-confirm-regexp
elisp: linkswhen you follow the linkorg-link-elisp-confirm-function, org-link-elisp-skip-confirm-regexp
Table formulason recalculationnone specific: treat formulas as code you have read
Remote #+SETUPFILE and #+INCLUDEon export or setuporg-resource-download-policy, org-safe-remote-resources

Source blocks

org-confirm-babel-evaluate decides whether Org asks before it runs a block. Its default is t, so every evaluation prompts. Setting it to nil removes all prompts, which is convenient but means that any file you open can run arbitrary code the moment you press C-c C-c or export it.

A better middle ground is a function. Org calls it with 2 arguments, the language and the body of the block, and asks for confirmation only when the function returns non-nil. The function runs in the Org buffer, so it can also look at buffer-file-name. The following configuration trusts Emacs Lisp blocks only in files under one directory that you control:

(defvar my-trusted-org-directory (expand-file-name "~/org/"))

(defun my-org-confirm-babel-evaluate (lang _body)
  "Ask for confirmation unless an Emacs Lisp block lives in my trusted directory."
  (not (and (member lang '("emacs-lisp" "elisp"))
            buffer-file-name
            (file-in-directory-p buffer-file-name my-trusted-org-directory))))

(setq org-confirm-babel-evaluate #'my-org-confirm-babel-evaluate)

To test it, the same block was placed in trusted/note.org and untrusted/note.org, with the trusted directory pointing at the first. Org evaluated the first block silently and inserted the result:

#+begin_src emacs-lisp
(+ 1 2)
#+end_src

#+RESULTS:
: 3

For the second file it asked Evaluate this emacs-lisp code block on your system? (yes or no) and, since the batch session could not answer, nothing ran.

Org protects this variable against file-local overrides. Its safe-local-variable predicate accepts only t, so a file cannot quietly switch confirmation off for itself through a -*- ... -*- line or a local-variables section.

The picture has 3 further controls:

  • The :eval header argument sets the policy per block or per subtree. never (or no) forbids evaluation, query always asks, never-export (or no-export) allows interactive runs but not export-time runs, and query-export asks only during export. Without :eval, Org falls back to org-confirm-babel-evaluate. Working with Source Code explains header arguments in full.
  • org-babel-no-eval-on-ctrl-c-ctrl-c, when non-nil, removes block evaluation from C-c C-c altogether. You can still evaluate blocks with C-c C-v e.
  • org-export-use-babel, when nil, stops export from evaluating code and from obeying header arguments. Use it with care, because it also affects how blocks appear in the output.

Org has 2 link types whose target is code: shell: runs a shell command and elisp: evaluates a Lisp form. The description of such a link can say anything, so the visible text tells you nothing about what will run. Both org-link-shell-confirm-function and org-link-elisp-confirm-function default to yes-or-no-p, which makes you type a full yes. You can switch them to y-or-n-p for a lighter prompt, or exempt specific commands through the two skip-confirm regexps. Setting the functions to nil removes the protection completely.

Remote resources

The #+SETUPFILE and #+INCLUDE keywords can point at a URL. org-resource-download-policy controls whether Org downloads such resources: prompt (the default) asks before fetching anything that is not considered safe, safe fetches only safe resources, t fetches everything, and nil fetches nothing. A resource is safe when it matches one of the regexps in org-safe-remote-resources, which is empty by default.

Encrypting entries with Org Crypt

Some notes belong next to the project they describe but must not sit on disk in plain text: an API token, the admin password of a router, the details of a contract. Encrypting the whole file would make it unsearchable and awkward to edit. Org Crypt takes a finer approach: it encrypts the body of individual entries and leaves the headline, tags and properties readable, so the outline, the agenda and searches still work.

Org Crypt relies on EasyPG, the GnuPG interface built into Emacs, so it needs a working GnuPG installation. It selects entries with a tag, crypt by default (org-crypt-tag-matcher holds the match string, so you can use any tag or a more complex match).

Setting it up

The following configuration enables automatic encryption on save:

(require 'org-crypt)
(org-crypt-use-before-save-magic)
(setq org-tags-exclude-from-inheritance '("crypt"))
(setq org-crypt-key "you@example.com")

Each line has a specific purpose:

  • org-crypt-use-before-save-magic adds org-encrypt-entries to before-save-hook in every Org buffer. Each save then encrypts every entry that matches the tag.
  • Excluding crypt from tag inheritance matters because a child of an encrypted entry would otherwise match too, and Org would try to encrypt text that is already part of an encrypted body. If you already set org-tags-exclude-from-inheritance, add "crypt" to your existing list instead of replacing it.
  • org-crypt-key chooses the recipient. Its 3 kinds of value behave differently, as described below.

The key selection in org-crypt-key-for-heading works like this:

org-crypt-keyResult
a string such as "you@example.com"public-key encryption to the matching keys in your keyring
"" (the default)matches no key, so Org looks at epa-file-encrypt-to and otherwise falls back to symmetric (passphrase) encryption
nilalways symmetric encryption, and the CRYPTKEY property is ignored

A heading can override the key with a CRYPTKEY property, which is useful when one entry is meant for a colleague who has a different key. As the table states, this override works only while org-crypt-key is non-nil.

What the file looks like

Here is a small file before saving:

#+title: Accounts

* Router admin                                                       :crypt:
User: admin
Password: correct-horse-battery-staple

* Shopping list
- milk

After a save with the configuration above (using a throwaway GnuPG key), the file on disk and the buffer both contain this:

#+title: Accounts

* Router admin                                                       :crypt:
-----BEGIN PGP MESSAGE-----

hF4DQ46f6qdLzD4SAQdAZDnhRV4lni1JE56onURsFrCpjQClXKjmwkU6G2ps0SYw
jQQtVtIZ8U/oCtu23vCxsBMxSCF/p2+aYB4/G+LH5MfeqeRNX1m2ggVsDY00bDF0
0nABjKSPZ5J2FGmm6RKzqcmVipuNBD8c0/yOatfkOd/YAkiNPnnXMAP9vroYagld
MwcR3IXHckuaYn9RvitN1/6Xh0K7dLYgrR18gtdxIEdFEvtQA1oT1DC6ZSDYocC5
2HBjAcLt2TJDVhOPcspUw8vj
=XgAA
-----END PGP MESSAGE-----

* Shopping list
- milk

The headline and its tag remain visible, and the untagged entry is untouched. Running M-x org-decrypt-entry with point on the heading restored the original 2 lines in the buffer.

Daily use

The commands below have no default key:

  • org-decrypt-entry decrypts the entry at point. Org Crypt also adds it to org-fold-reveal-start-hook, so revealing a folded entry with C-c C-r tries to decrypt it.
  • org-decrypt-entries decrypts every matching entry in the buffer.
  • org-encrypt-entry and org-encrypt-entries do the reverse by hand. With the save hook installed you rarely need them.

The commentary in org-crypt.el suggests binding decryption to a key of your choice:

(with-eval-after-load 'org
  (define-key org-mode-map (kbd "C-c C-/") #'org-decrypt-entry))

Auto-save is the weak point. While an entry is decrypted in the buffer, an auto-save file could write the plain text to disk. org-crypt-disable-auto-save controls what happens when you decrypt: ask (the default) asks whether to turn off auto-save-mode for the buffer, t turns it off without asking, encrypt keeps auto-save but re-encrypts tagged entries before each auto-save, and nil does nothing and accepts the risk.

stateDiagram-v2
    [*] --> Plain: tag the entry with crypt
    Plain --> Encrypted: save runs before-save-hook
    Encrypted --> Plain: org-decrypt-entry or C-c C-r
    Plain --> Plain: edit (auto-save per org-crypt-disable-auto-save)

Figure 18.1: A tagged entry is plain text only while you work on it in the buffer; every save returns it to its encrypted form.

Calling Org from outside: org-protocol

Many useful moments happen outside Emacs. You find an article in a browser and want it in your reading list, or you are reading a published page and want to fix a typo in its source. org-protocol lets any program that can open a URL trigger an Org action. It defines a URL scheme, org-protocol://, and a set of handlers that Emacs runs when it receives such a URL.

The mechanism uses the Emacs server. A browser bookmark, a script or a desktop shortcut runs emacsclient with an org-protocol:// URL as its argument. org-protocol advises server-visit-files, the function the server uses to open files sent by emacsclient, so the server inspects each “file name” before it opens anything. When the name starts with org-protocol:/ followed by a known sub-protocol, the matching handler receives the decoded parameters instead.

sequenceDiagram
    participant B as Browser bookmark
    participant O as OS URL handler
    participant C as emacsclient
    participant S as Emacs server
    participant P as org-protocol
    participant K as org-capture
    B->>O: org-protocol capture URL
    O->>C: URL as a file argument
    C->>S: file name list
    S->>P: server-visit-files advice checks each name
    P->>K: template key, link, title, selected text
    K->>S: entry filed, client released

Figure 18.2: An org-protocol URL travels as a file name through emacsclient, and the advice on the server diverts it to a handler before any file is opened.

Setting it up

You need 3 things in place:

  1. Load the library and start the server in your Emacs configuration:

    (require 'org-protocol)
    (require 'server)
    (unless (server-running-p) (server-start))
    
  2. Register org-protocol:// with your operating system so that it calls emacsclient with the URL. How you do this depends on the desktop environment and the browser, and Org does not do it for you.

  3. Test from a shell before you involve a browser:

    emacsclient "org-protocol://store-link?url=https%3A%2F%2Forgmode.org%2F&title=Org%20Mode"
    

Parameters use the familiar key=value&key=value form, and values must be URL-encoded. Org decodes + as a space, so the browser function URLSearchParams produces suitable query strings. Older guides build the string with encodeURIComponent, which also works.

The store-link handler adds a link to org-stored-links, the list that org-insert-link offers, and pushes the URL onto the kill ring. Sending

org-protocol://store-link?url=https%3A%2F%2Forgmode.org%2Fmanual%2FProtocols.html&title=Protocols%20(The%20Org%20Manual)

produced the message ‘M-x org-insert-link’ to insert new Org link, ‘C-y’ to insert "https://orgmode.org/manual/Protocols.html" and left these values behind:

stored: ("https://orgmode.org/manual/Protocols.html" "Protocols (The Org Manual)")
kill-ring: "https://orgmode.org/manual/Protocols.html"

In an Org buffer, C-c C-l then offers the stored link with the page title as its description. A bookmark that sends the current page looks like this:

javascript:location.href='org-protocol://store-link?' + new URLSearchParams({url: location.href, title: document.title}); void(0);

capture: file a page as a note

The capture handler starts org-capture with data from the URL. Its parameters are template (a capture template key), url, title and body; if you omit template, Org uses org-protocol-default-template-key. Inside the template, the handler makes these escapes available:

EscapeValue
%:linkthe URL
%:descriptionthe page title
%:annotationa complete Org link built from the two
%ithe body parameter, usually the selected text

Here is a template for web clippings. :immediate-finish files the entry without showing the capture buffer, which suits a one-click bookmark:

(setq org-capture-templates
      '(("w" "Web page" entry (file+headline "~/org/inbox.org" "Inbox")
         "* %:description\n:PROPERTIES:\n:SOURCE: %:link\n:END:\n%i\n"
         :immediate-finish t)))

The URL org-protocol://capture?template=w&url=https%3A%2F%2Forgmode.org%2Fmanual%2FOrg-Crypt.html&title=Org+Crypt&body=Org+Crypt+encrypts+the+text+of+an+entry. turned an inbox containing only * Inbox into this:

* Inbox
** Org Crypt
:PROPERTIES:
:SOURCE: https://orgmode.org/manual/Org-Crypt.html
:END:
Org Crypt encrypts the text of an entry.

The matching bookmark sends the selection as the body:

javascript:location.href='org-protocol://capture?' + new URLSearchParams({template: 'w', url: location.href, title: document.title, body: window.getSelection()}); void(0);

Capture templates themselves are the subject of Capture, Refile, Archive and Attachments.

open-source: from a published page back to its source

If you publish Org files as a website (see Publishing and Citations), the open-source handler takes you from a page in the browser to the Org file that produced it. org-protocol-project-alist describes each site: Org removes :base-url from the URL, replaces :online-suffix with :working-suffix, and prepends :working-directory.

(setq org-protocol-project-alist
      '(("Notes site"
         :base-url "https://notes.example.com/"
         :working-directory "/home/user/site/"
         :online-suffix ".html"
         :working-suffix ".org")))

With a working directory in the test folder, the URL org-protocol://open-source?url=https%3A%2F%2Fnotes.example.com%2Fworg%2Findex.html resolved to .../site/worg/index.org, which the server then opened like any file sent by emacsclient. When a site rewrites URLs on the server so that the mapping fails, add a :rewrites list of (REGEXP . RELATIVE-PATH) pairs; Org consults it only when no existing file matches. The commands org-protocol-create and org-protocol-create-for-org build an entry interactively, the second from a project in org-publish-project-alist.

Writing your own handler

org-protocol-protocol-alist registers additional sub-protocols. Each entry names the protocol and a function that receives the parameters as a property list. If the function returns nil, the server opens nothing; a string return value is treated as a file name to visit.

(defun my-org-protocol-echo (info)
  (message "echo handler got: %S" info)
  nil)

(setq org-protocol-protocol-alist
      '(("echo" :protocol "echo" :function my-org-protocol-echo)))

org-protocol://echo?a=1&b=two+words printed echo handler got: (:a "1" :b "two words"). A handler can also set :kill-client t, which releases emacsclient at once; the built-in capture handler does this so that a cancelled capture does not leave a waiting client behind.

Org on a phone: Org Mobile

Org Mobile is a protocol for exchanging Org files with another application, typically a phone app, through a shared directory. The computer remains the home of your system: the phone receives copies of your files and agenda views to read offline, records captures and simple edits, and the computer merges these changes on its next synchronization. Org implements the computer side in org-mobile.el; the phone side is a separate application that speaks the same protocol.

flowchart LR
    A["Org files in org-directory"] -->|"org-mobile-push: copies, agendas.org, index.org"| S["staging area (org-mobile-directory)"]
    S -->|"download changed files"| M["mobile app"]
    M -->|"captures and edits in mobileorg.org"| S
    S -->|"org-mobile-pull: move entries"| I["org-mobile-inbox-for-pull"]
    I -->|"apply edits, tag FLAGGED"| A

Figure 18.3: Org Mobile is a round trip through one staging directory: push publishes copies, pull collects what the phone wrote and merges it.

Configuration

The staging area is a directory that both sides can reach. If you can mount it locally, point org-mobile-directory at the mount; through TRAMP it can also be a remote path such as a WebDAV location.

(setq org-directory "~/org/")
(setq org-mobile-directory "~/orgmobile/")
(setq org-mobile-inbox-for-pull "~/org/from-mobile.org")

org-mobile-files lists what to push. Its default, (org-agenda-files), takes all agenda files; you can add more files or directories. Files are stored with paths relative to org-directory, so they should all live under it. Because the app understands only the TODO keyword sets and the tags that it learns from your global settings, define them in org-todo-keywords, org-tag-alist and org-tag-persistent-alist, even if individual files also use in-buffer settings.

Pushing

M-x org-mobile-push copies the files, writes an agenda file, writes an index, and records checksums so that the app downloads only what changed. For a test directory with one agenda file, the staging area afterwards contained:

agendas.org
checksums.dat
index.org
mobileorg.org
tasks.org

The index carries the global settings the app needs:

#+READONLY
#+TODO: TODO NEXT | DONE
#+TAGS: work home
#+ALLPRIORITIES: A B C
* [[file:agendas.org][Agenda Views]]
* [[file:tasks.org][tasks.org]]

The push also changed the source file. Because org-mobile-force-id-on-agenda-items is t by default, every agenda item received an ID property, which later lets Org find the entry that an edit on the phone refers to:

* TODO Renew passport
SCHEDULED: <2026-11-20 Fri>
:PROPERTIES:
:ID:       b65d3eb1-7181-444f-8c1f-0f4724b7e2e5
:END:

Which agenda views go into agendas.org depends on org-mobile-agendas: all (the default) includes the standard and your custom views, default only the weekly agenda and the global TODO list, custom only your own, and a list of strings selects views by their dispatcher keys. The views themselves are covered in Agenda Views.

Pulling

The app writes everything it records into mobileorg.org in the staging area. M-x org-mobile-pull moves those entries into the file named by org-mobile-inbox-for-pull (which should be outside the staging area), empties mobileorg.org, and then applies edits to your files. To simulate a phone capture, one entry was written into mobileorg.org before pulling; afterwards the inbox contained

* Call the dentist about Tuesday
[2026-11-19 Thu 09:12]

and mobileorg.org was empty. Simple changes such as a new TODO state, new tags, or edited headline and body text are applied directly. Entries that need your attention receive the FLAGGED tag, and conflicts are marked with an error message in the inbox. org-mobile-force-mobile-change decides whether the phone’s version wins when both sides changed the same entry.

To work through flagged entries, press ? in the agenda dispatcher. In the resulting view, ? on an item shows the full flagged note and copies it to the kill ring; pressing ? twice removes the FLAGGED tag and the note, which marks the entry as handled.

Encryption

If the staging area is on a server you do not fully trust, set org-mobile-use-encryption to t and put the shared password in org-mobile-encryption-password (or leave it empty, and Org asks once per session). The same password must be entered in the app. Org encrypts the files with AES-256 through the openssl program, so OpenSSL must be installed. File names stay visible on every machine, and the password can briefly appear in the process list while Org runs the encryption command.

Files and images: drag and drop and yank-media

Attaching a screenshot to a note should not require saving it somewhere, typing a path and writing a link. Org handles files dropped on a buffer and, from Emacs 29, the yank-media command, which pastes rich clipboard content such as images.

When you drop a file onto an Org buffer, org-yank-dnd-method decides what happens: attach makes it an attachment of the current entry, file-link inserts a file: link, open visits the file, and ask (the default) lets you choose each time. For attachments, Org first uses the drag metadata (copy or move) and otherwise falls back to org-yank-dnd-default-attach-method; when that is nil, org-attach-method decides.

M-x yank-media covers 3 kinds of clipboard content:

  • Images: Org writes the image to disk and inserts a link. org-yank-image-save-method chooses where: attach (the default) stores it as an attachment of the current heading, a directory name stores it there, and a function returns the directory to use. org-yank-image-file-name-function names the file; the default produces names like clipboard-20261119T091200.123456, and org-yank-image-read-filename asks for a name instead.
  • Files copied in a file manager, which follow org-yank-dnd-method.
  • Tables copied from LibreOffice Calc, which arrive as Org tables.

The clipboard cannot be reached from batch Emacs, so the following results come from calling Org’s image handler directly with a fake PNG and a fixed file name. With org-yank-image-save-method set to "images/", Org wrote images/whiteboard.png and inserted:

* Whiteboard photo
[[file:images/whiteboard.png]]

With the default attach, Org created an ID for the heading, moved the image into the attachment directory data/d6/5b9b7d-da0f-4752-8af8-472f42b91a31/, and inserted an attachment: link:

* Whiteboard photo                                                   :ATTACH:
:PROPERTIES:
:ID:       d65b9b7d-da0f-4752-8af8-472f42b91a31
:END:
[[attachment:whiteboard.png][whiteboard.png]]

Attachments are explained in Capture, Refile, Archive and Attachments, and how inline images are displayed is part of Markup for Rich Contents.

Living with other packages

Org binds many keys and changes how editing commands behave, so it inevitably meets other packages that want the same keys or the same text. The manual records which packages Org works with and which ones clash with it. The cases below are those you are most likely to meet.

Packages Org builds on

  • Calc performs the arithmetic behind table formulas (see The Spreadsheet and Plotting).

  • constants.el, an external package, lets formulas use named physical constants and unit prefixes. Org uses it when the function constants-get is available.

  • CDLaTeX, also external, speeds up typing LaTeX fragments (Markup for Rich Contents).

  • Imenu builds a menu of headlines. Enable it with a hook; org-imenu-depth (default 2) limits the levels included:

    (add-hook 'org-mode-hook (lambda () (imenu-add-to-menubar "Imenu")))
    
  • Speedbar can browse into Org files, and < in the Speedbar frame restricts agenda commands to the selected file or subtree.

  • table.el tables, which support cells spanning several rows or columns, are recognized and exported. You cannot edit them directly in the Org buffer: C-c ' (org-edit-special) opens one in a separate buffer, and C-c ~ (org-table-create-with-table.el) inserts a new one or converts an existing table between the two formats.

Shift-selection, CUA mode and windmove

Emacs uses shifted cursor keys to select text, while Org uses S-<left>, S-<right>, S-<up> and S-<down> to change TODO states, priorities, timestamps and list bullets. org-support-shift-select resolves the conflict in three steps:

ValueBehavior
nil (default)shifted cursor keys run Org commands in special contexts and signal an error elsewhere
toutside special contexts they select text; in a list item, bullet cycling works only with point on the bullet
alwaysthey select text in headlines, property lines, list items and tables as well; use C-c C-t, C-c , and similar commands instead

CUA mode and windmove also want the shifted cursor keys. If you prefer to give them the keys, set org-replace-disputed-keys to t before Org is loaded. Org then moves its own bindings according to org-disputed-keys:

Default keyReplacement
S-<up>M-p
S-<down>M-n
S-<left>M--
S-<right>M-+
C-S-<left>M-S--
C-S-<right>M-S-+

If you would rather keep Org’s keys and use windmove only where Org has nothing to do, attach windmove to the “final” hooks. Org runs these hooks when a shifted cursor key is pressed outside any special context:

(add-hook 'org-shiftup-final-hook #'windmove-up)
(add-hook 'org-shiftleft-final-hook #'windmove-left)
(add-hook 'org-shiftdown-final-hook #'windmove-down)
(add-hook 'org-shiftright-final-hook #'windmove-right)

Other known conflicts

  • YASnippet: Org binds TAB as [tab] rather than "\t", which takes precedence over YASnippet’s trigger. The manual gives 2 workarounds: setting YASnippet’s trigger key to [tab] locally in Org buffers, or adding a non-intrusive expansion function to org-tab-first-hook. Both depend on YASnippet internals, so check them against the version you use; they were not evaluated for this book.
  • Viper uses C-c /, which hides org-sparse-tree. Bind the command to another key, or override the key in viper-vi-global-user-map.
  • filladapt.el interferes with Org’s own filling of paragraphs and list items; turn it off in Org buffers with turn-off-filladapt-mode on org-mode-hook.
  • Ecomplete stops completing addresses in message headers when Orgtbl mode is active. Turn on Orgtbl mode by hand once the headers are written, instead of from a hook (see The Table Editor for Orgtbl mode).

Using Org on a terminal

In a text terminal, many key combinations that Org relies on never reach Emacs: the terminal may send nothing for M-<up> or S-<return>, or send something Emacs cannot tell apart from a plain key. Org therefore defines additional bindings that use only ordinary keys. They are installed when Org is loaded in a session where display-graphic-p returns nil, or whenever org-use-extra-keys is non-nil (set it before Org loads, for instance if you start a graphical Emacs but also use emacsclient -t).

The table below was checked by asking Org 9.8.13 in a non-graphical batch session which command each key runs (C-u TAB, a prefix argument, was read from the manual). Speed keys (single letters at the start of a headline, see Getting Started) are listed where org-speed-commands defines one for the same command.

Graphical keyTerminal alternativeSpeed keyCommand
S-TABC-u TABCorg-shifttab (C-u TAB is org-cycle with a prefix argument)
M-<left>C-c C-x l, ESC <left>lorg-metaleft
M-<right>C-c C-x r, ESC <right>rorg-metaright
M-<up>C-c C-x u, ESC <up>Uorg-metaup
M-<down>ESC <down>Dorg-metadown
M-S-<left>C-c C-x LLorg-shiftmetaleft
M-S-<right>C-c C-x RRorg-shiftmetaright
M-S-<up>C-c C-x Uorg-shiftmetaup
M-S-<down>C-c C-x Dorg-shiftmetadown
M-RETC-c C-x m, ESC RETorg-meta-return
M-S-RETC-c C-x Morg-insert-todo-heading
S-<left>C-c <left>org-shiftleft
S-<right>C-c <right>org-shiftright
S-<up>C-c <up>org-shiftup
S-<down>C-c <down>org-shiftdown
C-S-<left>C-c C-x <left>org-shiftcontrolleft
C-S-<right>C-c C-x <right>org-shiftcontrolright
C-c C-,C-c C-x sorg-insert-structure-template

In 2 rows, this table differs from the one in the manual. The manual lists C-c C-x d for M-<down> and C-c C-x c for S-RET, but org-keys.el later binds these keys again: C-c C-x d runs org-insert-drawer and C-c C-x c runs org-clone-subtree-with-time-shift, and the later bindings win. On a terminal, use ESC <down> for M-<down>. S-RET (org-table-copy-down) has no working alternative, so bind one yourself if you copy table cells down often. The manual also lists the speed keys U and D against M-S-<up> and M-S-<down>, but org-speed-commands maps them to org-metaup and org-metadown, which is how the table above shows them.

The ESC alternatives are explicit bindings in org-keys.el (for example, ESC <left> runs org-metaleft and ESC RET runs org-meta-return), so they do not depend on the terminal sending Meta combinations. Some contexts also offer a prompt-based alternative: on a timestamp, C-c . lets you type a new date instead of nudging it with shifted cursor keys.

Repeating navigation commands

The Emacs minor mode repeat-mode lets you repeat a command by pressing only its last key. Org defines repeat maps for its motion commands, so with repeat-mode on, C-c C-n n n p u moves down 3 visible headings, back up 1, and then to the parent. Any key outside the map ends the repetition and runs normally.

(repeat-mode 1)
Repeat mapCommandKeyRepeat key
org-navigation-repeat-maporg-next-visible-headingC-c C-nn
org-previous-visible-headingC-c C-pp
org-forward-heading-same-levelC-c C-ff
org-backward-heading-same-levelC-c C-bb
org-up-headingC-c C-uu
org-block-navigation-repeat-maporg-next-blockC-c M-ff
org-previous-blockC-c M-bb
org-link-navigation-repeat-maporg-next-linkC-c C-x C-nn
org-previous-linkC-c C-x C-pp

Choosing what to adopt

None of these integrations is required, and each one adds a dependency: Org Crypt needs GnuPG and careful handling of auto-save, org-protocol needs a running server and an OS-level URL handler, and Org Mobile needs a shared directory and a compatible app. A reasonable order is to settle your evaluation policy first, because it protects you from the moment you open someone else’s file, then add org-protocol capture if much of your input comes from a browser, and only then consider encryption and mobile access for the specific notes that need them. Putting It Together shows how capture from the browser fits into a complete task system.

Further reading

Putting It Together

The previous chapters describe Org one feature at a time. Real use rarely looks like that: a working system combines capture with refiling, refiling with the agenda, code blocks with export, and export with publishing. This chapter assembles 4 such systems from the features you already know:

  1. a task system built on capture, refile, the agenda and a weekly review;
  2. a literate Emacs configuration, written in Org and tangled into an init file;
  3. a research notebook that keeps data, code, results and prose in one file;
  4. a small website published from a directory of Org files.

These systems are this book’s suggestions, not part of Org. The Org manual documents the building blocks (capture templates, refile targets, custom agenda commands, tangling, publishing projects) but does not prescribe how to combine them, and many Org users work quite differently. Every option used below is documented in the manual or in the docstrings of Org 9.8.13; each section links to the chapter that explains the feature in detail. Treat the configurations as starting points and change them as soon as your own habits disagree with them.

The table below shows which chapters each system draws on.

SystemMain featuresChapters
Task systemTODO keywords, logging, capture, refile, archive, custom agenda commands, stuck projectsTODO Items, Tags, Properties and Column View, Dates and Times, Capture, Refile, Archive and Attachments, Agenda Views
Literate configurationCode blocks, header arguments, tanglingWorking with Source Code (Babel)
Research notebookNamed tables, code blocks with variables, results, exportThe Table Editor, Working with Source Code (Babel), Exporting
Publishing sitePublishing projects, components, sitemapExporting, Publishing and Citations

Every result shown in this chapter (the captured entries, the agenda, the tangled file, the evaluated notebook and the list of published files) was produced by Org 9.8.13 in Emacs batch mode. The task system uses the sample files from Agenda Views and assumes that “today” is Friday, 13 March 2026, the day of the weekly review.

A task system

The idea

A task system has to answer 3 questions reliably: where does a new commitment go, what should I do now, and is anything slipping? The design below answers them with 3 kinds of files and 2 regular habits.

  • An inbox file receives everything new. Capturing must be fast enough that you never postpone it, so the inbox has no structure at all.
  • Project files hold the real structure. A project is a level-1 headline tagged project; its tasks are the children. Tasks that you can start right now carry the keyword NEXT; the others are TODO, or WAITING when someone else must act first.
  • Dates are reserved for real commitments. A deadline means “this has consequences if late”; a scheduled date means “I plan to start on this day”. Tasks without a real date have no date.
  • A daily view shows today’s fixed items, the NEXT tasks and the WAITING list.
  • A weekly review empties the inbox, looks back over the week and forward at the next one, and finds projects without a next action.

Files and keywords

The system uses the 2 files from Agenda Views, work.org and home.org, plus an inbox.org that starts with only a title. All 3 live in one directory, and the directory itself is the agenda file list, so a new file in it joins the agenda automatically:

(setq org-directory "~/org/")
(setq org-default-notes-file (expand-file-name "inbox.org" org-directory))
(setq org-agenda-files (list org-directory))

The TODO keywords add logging to the workflow, which TODO Items explains in detail. WAITING(w@/!) asks for a note when a task starts waiting (so you record what you are waiting for) and records a timestamp when it stops waiting; DONE(d!) records when a task was finished; CANCELED(c@) asks why. org-log-into-drawer keeps these records in a LOGBOOK drawer, out of the way of the entry text:

(setq org-todo-keywords
      '((sequence "TODO(t)" "NEXT(n)" "WAITING(w@/!)"
                  "|" "DONE(d!)" "CANCELED(c@)")))
(setq org-log-into-drawer t)

Capturing into the inbox

Capture, described in Capture, Refile, Archive and Attachments, opens a small buffer from a template, lets you type, and files the result when you press C-c C-c. For an inbox, the templates should be as short as possible. The target (file "") means org-default-notes-file, so both templates below write to inbox.org:

(setq org-capture-templates
      '(("t" "Task" entry (file "")
         "* TODO %?%i\n:PROPERTIES:\n:CREATED: %U\n:END:\n")
        ("n" "Note" entry (file "")
         "* %?%i :note:\n%U\n%a\n")))
(global-set-key (kbd "C-c c") #'org-capture)

In the templates, %? marks where point is placed, %i inserts the active region if there is one, %U inserts an inactive timestamp with the time, and %a inserts a link to the place where you started the capture. The CREATED property records when the task arrived; it costs nothing at capture time and helps you notice, during the review, tasks that have stayed in the system for months.

After 2 captures with C-c c t, one on Thursday morning and one on Friday, the inbox contains:

#+TITLE: Inbox
* TODO Ask Maria about the hosting budget
:PROPERTIES:
:CREATED: [2026-03-12 Thu 10:42]
:END:
* TODO Book a room for the offsite
:PROPERTIES:
:CREATED: [2026-03-13 Fri 09:15]
:END:

Do not decide anything while capturing. Whether the room booking belongs to a project, whether it needs a date, whether it is a NEXT action: these are questions for the review, when you have time to think.

Refiling into projects

Refiling moves an entry under another headline, in the same file or a different one. With the settings below, C-c C-w offers every headline up to level 2 in every agenda file as a target, and shows targets as paths that start with the file name, such as work.org/Website redesign:

(setq org-refile-targets '((org-agenda-files :maxlevel . 2)))
(setq org-refile-use-outline-path 'file)
(setq org-outline-path-complete-in-steps nil)

Setting org-outline-path-complete-in-steps to nil lets you complete the whole path at once, which works well with completion frameworks that match substrings. You can refile from the inbox file itself, or directly from an agenda line with the same key C-c C-w.

The daily view

For the day, a block agenda gives one screen with today’s calendar, the next actions and the waiting list. It is the command d from Agenda Views, here as the first entry of the custom commands:

(setq org-agenda-custom-commands
      '(("d" "Daily overview"
         ((agenda "" ((org-agenda-span 'day)))
          (todo "NEXT"
                ((org-agenda-overriding-header "Next actions")))
          (todo "WAITING"
                ((org-agenda-overriding-header "Waiting for others")))))))

During the day, you work from this view with the remote editing keys: t to change states, S-RIGHT to postpone, I and O to clock in and out if you track time (see Clocking, Effort and Timers), and g to refresh.

The weekly review

The daily view only shows what is already organized. Once a week, the review brings everything else back under control. Figure 19.1 shows how it connects to the rest of the system.

flowchart TD
  C["Capture: C-c c"] -->|"new entries"| I["inbox.org"]
  I -->|"1. clarify, C-c C-w"| P["Project files"]
  P -->|"2. dates and closed items"| W["Week agenda with log"]
  P -->|"3. no NEXT task"| S["Stuck projects"]
  S -->|"define a NEXT action"| P
  P -->|"4. WAITING entries"| F["Follow up or wait"]
  P -->|"NEXT and today's dates"| D["Daily view: C-c a d"]
  D -->|"ideas during work"| C

Figure 19.1: The weekly review drains the inbox into projects and repairs projects that have stopped moving, so the daily view can be trusted for the rest of the week.

The review is one custom agenda command with 4 blocks, one per step. Each block has an overriding header that says what to do with it:

(setq org-stuck-projects
      '("+project+LEVEL=1/-DONE" ("NEXT") nil ""))

(add-to-list 'org-agenda-custom-commands
             '("r" "Weekly review"
               ((tags "LEVEL=1"
                      ((org-agenda-files (list org-default-notes-file))
                       (org-agenda-overriding-header "1. Inbox: clarify and refile")))
                (agenda ""
                        ((org-agenda-span 'week)
                         (org-agenda-overriding-header "2. This week: done and planned")))
                (stuck ""
                       ((org-agenda-overriding-header "3. Projects without a next action")))
                (todo "WAITING"
                      ((org-agenda-overriding-header "4. Waiting for others"))))
               ((org-agenda-start-with-log-mode t))))

Some choices in this command need a word of explanation.

  • The first block is a match view for LEVEL=1 with org-agenda-files bound to the inbox alone, so it lists every top-level entry of the inbox, whatever its keyword.
  • The stuck-project definition only accepts NEXT as a next action. A project with many TODO tasks but no NEXT is still stuck, because none of its tasks has been judged ready to start. The LEVEL=1 part prevents the tasks inside a project from being treated as projects themselves (see the stuck projects section of Agenda Views).
  • org-agenda-start-with-log-mode sits in the settings shared by all blocks. In Org 9.8.13, log mode is set up when the agenda buffer is created, so the option has no effect inside a single block.

On Friday afternoon, the review over the sample files looks like this:

1. Inbox: clarify and refile
  inbox:      TODO Ask Maria about the hosting budget
  inbox:      TODO Book a room for the offsite

===============================================================================
2. This week: done and planned
Monday      9 March 2026 W11
  work:        9:30-9:45  Team standup
  work:       Scheduled:  TODO [#A] Write the summary                :project::
Tuesday    10 March 2026
  work:       16:10...... Closed:     DONE Submit the abstract       :project::
  home:       Scheduled:  TODO Call the plumber                          :call:
  work:       Deadline:   TODO Collect sales figures                 :project::
Wednesday  11 March 2026
  home:       15:00-16:00 Dentist appointment
  work:       Scheduled:  NEXT Draft the new navigation          :project::web:
Thursday   12 March 2026
  work:       14:00...... 1:1 with Maria
  home:       Alex turns 36
Friday     13 March 2026
  work:       Sched. 4x:  TODO [#A] Write the summary                :project::
  home:       Sched. 3x:  TODO Call the plumber                          :call:
  work:       Sched. 2x:  NEXT Draft the new navigation          :project::web:
  work:        3 d. ago:  TODO Collect sales figures                 :project::
  work:       Deadline:   TODO Review the color palette with design  :project::
  home:       In   7 d.:  TODO Renew passport                          :errand:
Saturday   14 March 2026
Sunday     15 March 2026

===============================================================================
3. Projects without a next action
  work:       Quarterly report                                        :project:
  work:       Conference talk                                         :project:

===============================================================================
4. Waiting for others
  work:       WAITING Final copy from marketing                      :project::

Work through the blocks from top to bottom, using the agenda’s remote editing keys so that you never leave the review buffer for long:

  1. Inbox. For each entry, decide what it is. Refile tasks into their project with C-c C-w, or turn them into NEXT actions with t. Delete what no longer matters with C-k. The inbox should be empty at the end.
  2. This week. Log mode shows what you finished (the closed abstract on Tuesday) next to what you planned. The Friday page is the honest part: Sched. 4x: means the summary has been postponed silently for 4 days. Either do it, give it a realistic new date with C-c C-s, or remove the date if it was never a real commitment. Then open the plain weekly agenda with C-c a a and press f to check the deadlines of the next week. (In this block agenda, Org 9.8.13 rejects f with the error Not allowed in `tags'-type agenda buffer or component.)
  3. Stuck projects. Quarterly report has tasks but none marked NEXT; decide which one you will start and change its keyword. Conference talk has nothing left to do, so either add the next step (preparing the slides) or mark the project itself as done.
  4. Waiting. For each WAITING entry, decide whether to send a reminder. The note that the keyword asked for when you set it tells you what exactly you are waiting for.

Finish with g to rebuild the review: the inbox block should be empty and the stuck-project block should list only projects you have consciously put on hold.

Archiving finished work

Finished projects should leave the project files, both to keep the files readable and to keep the agenda fast. C-c C-x C-s (org-archive-subtree) moves the subtree at point to the archive location; in the agenda, $ does the same for the entry on the current line. By default the archive location is a file next to the original, named after it with _archive appended, so work.org is archived into work.org_archive. The variable org-archive-location changes this, as described in Capture, Refile, Archive and Attachments.

A good moment to archive is the end of the weekly review: a project whose last task is done, such as the conference talk once the talk has been given, can go.

A literate Emacs configuration

The idea

An Emacs configuration grows over years, and after a while it is hard to remember why a line is there. Literate programming reverses the usual relation between code and comments: you write a document that explains your choices, and the code lives in blocks inside it. Org’s tangling, described in Working with Source Code (Babel), extracts the code blocks into a plain Emacs Lisp file that Emacs loads at startup. Figure 19.2 shows the 2 outputs of the same source file.

flowchart LR
  O["config.org"] -->|"C-c C-v t: tangle"| E["init.el"]
  E -->|"loaded at startup"| M["Emacs"]
  O -->|"C-c C-e: export"| H["HTML or PDF documentation"]

Figure 19.2: One Org file is both the source of the configuration and its documentation, because tangling and export read the same blocks.

The source file

The file below is a complete, if small, literate configuration. The #+PROPERTY line sets a default header argument for every Emacs Lisp block in the file, so each block is written to init.el without repeating :tangle on every block:

#+TITLE: My Emacs configuration
#+PROPERTY: header-args:emacs-lisp :tangle init.el

* Header
The first line turns on lexical binding for the generated file.

#+begin_src emacs-lisp
;;; init.el --- generated from config.org  -*- lexical-binding: t -*-
#+end_src

* Appearance
#+begin_src emacs-lisp
(setq inhibit-startup-screen t)
(column-number-mode 1)
#+end_src

* Org
** Agenda
#+begin_src emacs-lisp
(setq org-agenda-files '("~/org/"))
(global-set-key (kbd "C-c a") #'org-agenda)
#+end_src

** Experiments
This block is kept for reference but not written to init.el.

#+begin_src emacs-lisp :tangle no
(setq org-agenda-span 'day)
#+end_src

The headlines do the work that comments do in a plain init file, but better: you can fold them, move them with the structure editing commands, tag them, and link to them. The last block shows how a header argument on a single block overrides the file-wide default: :tangle no keeps it out of the generated file.

Tangling

C-c C-v t (org-babel-tangle) writes every block with a :tangle target to its file. Tangling this file reports Tangled 3 code blocks from config.org and produces:

;;; init.el --- generated from config.org  -*- lexical-binding: t -*-

(setq inhibit-startup-screen t)
(column-number-mode 1)

(setq org-agenda-files '("~/org/"))
(global-set-key (kbd "C-c a") #'org-agenda)

Blocks are separated by a blank line, in the order in which they appear in the document. The experiment block is missing, as intended.

Making it practical

A few habits make a literate configuration pleasant to maintain:

  • Treat init.el as a build product. Edit only config.org, and tangle after every change. If you keep the configuration in version control, decide once whether to commit init.el; committing it means that a new machine can start Emacs before Org has ever tangled anything.
  • Test a block before tangling it. C-c C-c in an Emacs Lisp block evaluates it in the running Emacs, so you can try a setting immediately.
  • Use org-babel-load-file if you prefer one step. It tangles the Emacs Lisp blocks of an Org file and loads the result; its docstring explains the details.
  • Keep secrets out. The document is meant to be read, exported and perhaps published; tokens and passwords belong in a separate file that the configuration loads.

For noweb references, which let one block include another by name, and for the full list of tangling header arguments, see Working with Source Code (Babel).

A research notebook

The idea

A notebook keeps an investigation in one place: the question, the data, the code that analyzes it, the results, and your interpretation. In Org, the data can be a table, the code a source block that reads the table through a variable, and the results are inserted below the block when you evaluate it. Export turns the notebook into a report that shows code and results together.

A notebook file

The notebook below compares response times before and after a change. The table has a name, so a code block can refer to it, and the #+PROPERTY line makes every block export both its code and its results:

#+TITLE: Response times after the cache change
#+PROPERTY: header-args :exports both
#+OPTIONS: toc:nil author:nil

* Data
Response times in milliseconds, measured before and after the change.

#+NAME: timings
| run | before | after |
|-----+--------+-------|
|   1 |    212 |   148 |
|   2 |    198 |   151 |
|   3 |    225 |   139 |

* Analysis
#+NAME: mean-improvement
#+begin_src emacs-lisp :var rows=timings
(let* ((before (mapcar (lambda (r) (nth 1 r)) rows))
       (after (mapcar (lambda (r) (nth 2 r)) rows))
       (mean (lambda (xs) (/ (apply #'+ xs) (float (length xs))))))
  (format "%.1f ms faster on average"
          (- (funcall mean before) (funcall mean after))))
#+end_src

* Environment
#+begin_src shell :results output
uname -s
#+end_src

The header argument :var rows=timings passes the table to the block as a list of rows. Because the table has a header row separated by a horizontal rule, Org removes the header before passing the data, so rows contains only the 3 numeric rows.

Evaluating

Only Emacs Lisp is enabled by default (org-babel-load-languages is ((emacs-lisp . t))), so the shell block needs one more language:

(org-babel-do-load-languages 'org-babel-load-languages
                             '((emacs-lisp . t) (shell . t)))

C-c C-c evaluates the block at point; C-c C-v b (org-babel-execute-buffer) evaluates all blocks in the buffer. After evaluation, the Analysis and Environment sections contain the results:

#+RESULTS: mean-improvement
: 65.7 ms faster on average
#+RESULTS:
: Linux

Evaluating code is the one Org feature that can damage your system if a file comes from someone else. By default, Org asks before each evaluation. The variable org-confirm-babel-evaluate controls this; besides t and nil it accepts a function of the language and the code, so you can decide case by case instead of turning the question off globally. Working with Source Code (Babel) discusses this in more detail.

Exporting the report

Export, described in Exporting, evaluates the blocks again (unless org-export-use-babel is nil) and renders the notebook in the chosen format. The plain text exporter (C-c C-e t a) gives a compact report:

                _______________________________________

                 RESPONSE TIMES AFTER THE CACHE CHANGE
                _______________________________________


1 Data
======

  Response times in milliseconds, measured before and after the change.

   run  before  after
  --------------------
     1     212    148
     2     198    151
     3     225    139


2 Analysis
==========

  ,----
  | (let* ((before (mapcar (lambda (r) (nth 1 r)) rows))
  |        (after (mapcar (lambda (r) (nth 2 r)) rows))
  |        (mean (lambda (xs) (/ (apply #'+ xs) (float (length xs))))))
  |   (format "%.1f ms faster on average"
  |           (- (funcall mean before) (funcall mean after))))
  `----

  ,----
  | 65.7 ms faster on average
  `----


3 Environment
=============

  ,----
  | uname -s
  `----

  ,----
  | Linux
  `----

For a report addressed to readers who do not care about code, change the file-wide default to :exports results. For one that teaches the method, keep both. :exports none leaves a block out of the report completely, which suits blocks that only prepare data for later ones.

Growing the notebook

As a notebook grows, a few features of earlier chapters become useful:

  • Table formulas (The Spreadsheet and Plotting) can compute simple derived columns directly in the data table, without any code block.
  • A :session header argument keeps an interpreter running between blocks, so expensive data loading happens once.
  • Results can be tables (:results table) or files (:results file), so a block can produce a chart image that the export includes.
  • An inactive timestamp under each heading, inserted with C-c !, turns the notebook into a dated lab journal.

A small publishing site

The idea

Publishing, described in Publishing and Citations, exports a whole directory tree of Org files to another directory, copies the other files the pages need, and only rebuilds what has changed. A personal site or a team handbook fits this model well: you write pages in Org, and a single command produces a directory of HTML files that any web server can serve.

The project definition

The site uses this layout:

src/
  index.org
  posts/agenda-tips.org
  img/week.png
public/          (created by publishing)

A publishing project is an entry in org-publish-project-alist. Different kinds of files usually need different treatment, so the site is split into 2 components: one exports Org files to HTML, the other copies images and stylesheets unchanged. A third entry groups them, so that one command publishes both. Figure 19.3 shows the structure.

flowchart LR
  S["src/*.org"] -->|"org-html-publish-to-html"| A["site-pages"]
  M["src/img/*.png"] -->|"org-publish-attachment"| B["site-static"]
  A -->|"HTML and sitemap"| P["public/"]
  B -->|"copied files"| P
  G["site"] -->|"components"| A
  G -->|"components"| B
  P -->|"rsync or similar tool"| W["Web server"]

Figure 19.3: A project groups components that each handle one kind of file, and all of them write into the same publishing directory.

The definition:

(require 'ox-publish)
(setq org-publish-project-alist
      '(("site-pages"
         :base-directory "~/site/src/"
         :base-extension "org"
         :recursive t
         :publishing-directory "~/site/public/"
         :publishing-function org-html-publish-to-html
         :auto-sitemap t
         :sitemap-title "All pages"
         :sitemap-sort-files anti-chronologically
         :with-toc nil
         :section-numbers nil)
        ("site-static"
         :base-directory "~/site/src/"
         :base-extension "png\\|jpg\\|css"
         :recursive t
         :publishing-directory "~/site/public/"
         :publishing-function org-publish-attachment)
        ("site" :components ("site-pages" "site-static"))))

Most properties are self-explanatory. :recursive t includes subdirectories, so posts/ is published too. :auto-sitemap t generates a page that lists all pages; :sitemap-sort-files anti-chronologically puts the newest pages first. Options such as :with-toc and :section-numbers are ordinary export settings, applied to every page in the component.

Publishing

C-c C-e P x (org-publish) asks for a project and publishes it; C-c C-e P p publishes the project of the current file, C-c C-e P f only the current file, and C-c C-e P a all projects. Publishing site reports each file as it is processed and produces this directory:

public/img/week.png
public/index.html
public/posts/agenda-tips.html
public/sitemap.html

The generated sitemap.org in the source directory, from which sitemap.html is exported, reflects the directory structure:

#+TITLE: All pages

- [[file:index.org][Notes]]
- posts
  - [[file:posts/agenda-tips.org][Three agenda tips]]

Links between Org files, such as [[file:sitemap.org][list of all pages]] in index.org, become links between the HTML files.

Org remembers when each file was last published and skips files that have not changed. When a change affects pages whose own files did not change, for example an edit to a file that the pages include with #+SETUPFILE or #+INCLUDE, force a full rebuild with a prefix argument (C-u C-c C-e P x) or through org-publish-use-timestamps-flag.

Getting the files to a server

The publishing directory can be remote, through Tramp, but the manual itself suggests a simpler approach for most cases: publish to a local directory and then synchronize it with a dedicated tool such as rsync or Unison. Local publishing is faster, and synchronization tools check contents and file attributes as well as timestamps. With this approach, the site-static component is optional, because the synchronization tool can copy images directly from the source tree.

Designing your own system

The 4 systems above share a pattern that is worth making explicit, because it applies to any system you build with Org:

  • Keep one source of truth. The agenda shows entries but stores nothing; init.el is generated from config.org; the HTML pages are generated from Org files. Edit the source, regenerate the rest.
  • Let structure arrive late. Capture into an unstructured inbox and organize during a review. Write a notebook first and extract a library later. Structure imposed too early slows down the moment of writing.
  • Make the regular check a single command. A weekly review that requires 5 different views will be skipped; one block agenda will not. The same is true for tangling and publishing.
  • Add one feature at a time. Every option in this chapter solves a specific problem. Add clocking when you need to know where time goes, effort estimates when you need to plan capacity, and tags when match views would answer a real question.

When something in your files looks wrong, M-x org-lint checks a buffer for common syntax mistakes, as described in Getting Started.

Further reading

Key Bindings and Glossary

This chapter is for looking things up. The first part collects the keys you use most often, grouped by the task you are performing rather than by key prefix. The second part defines the Org terms used throughout the book and points to the chapter that explains each one.

How the tables were checked

Every binding below was checked against Org 9.8.13 by asking a batch Emacs session which command the key runs in an Org buffer (or in the agenda, capture, source edit, column view or date prompt keymap, as noted). Dispatcher letters, which are menu choices rather than keymap bindings, were checked in the source of org-agenda.el and ox.el, and speed keys in org-speed-commands. Graphical key names are used throughout; on a text terminal, see the alternatives in Org Beyond the Basics.

Many Org keys are context-sensitive: one key runs a single “dispatcher” command that does different things on a headline, in a list or in a table. In those rows, the command column shows the dispatcher, and the description states what happens in each context.

You can always ask Emacs directly: C-h k followed by a key describes the command it runs, and C-h m lists the bindings of the current major mode.

Global commands you bind yourself

Org does not bind its 3 entry points globally. The manual suggests these keys, which the rest of this book assumes:

(global-set-key (kbd "C-c l") #'org-store-link)
(global-set-key (kbd "C-c a") #'org-agenda)
(global-set-key (kbd "C-c c") #'org-capture)
Key (suggested)What it doesCommand
C-c lStore a link to the current locationorg-store-link
C-c aOpen the agenda dispatcherorg-agenda
C-c cStart capturing a noteorg-capture

Visibility and navigation

KeyWhat it doesCommand
TABCycle the subtree at point: folded, children, subtreeorg-cycle
S-TABCycle the whole buffer: overview, contents, show allorg-shifttab
C-u C-u TABReturn to the startup visibilityorg-cycle
C-c C-kShow all headings (branches) below the current oneorg-kill-note-or-show-branches
C-c C-rReveal the context around pointorg-fold-reveal
C-c C-n / C-c C-pNext / previous visible headingorg-next-visible-heading, org-previous-visible-heading
C-c C-f / C-c C-bNext / previous heading at the same levelorg-forward-heading-same-level, org-backward-heading-same-level
C-c C-uUp to the parent headingorg-up-heading
C-c C-jJump to a heading through an outline interfaceorg-goto
C-c M-f / C-c M-bNext / previous blockorg-next-block, org-previous-block
C-c /Build a sparse tree (prompts for the kind)org-sparse-tree
C-c C-x bShow the current subtree in an indirect bufferorg-tree-to-indirect-buffer
C-x n sNarrow to the current subtreeorg-narrow-to-subtree
C-x n wWidenwiden

Editing structure

KeyWhat it doesCommand
M-RETNew heading or list item; in a table, wrap the regionorg-meta-return
C-RETNew heading after the current subtreeorg-insert-heading-respect-content
M-S-RETNew TODO headingorg-insert-todo-heading
C-S-RETNew TODO heading after the current subtreeorg-insert-todo-heading-respect-content
M-<left> / M-<right>Promote / demote a heading or list item; move a table columnorg-metaleft, org-metaright
M-S-<left> / M-S-<right>Promote / demote a whole subtree or item tree; delete / insert a table columnorg-shiftmetaleft, org-shiftmetaright
M-<up> / M-<down>Move a subtree, list item or table row up / downorg-metaup, org-metadown
C-c C-x C-wCut the subtree (or a table region)org-cut-special
C-c C-x M-wCopy the subtree (or a table region)org-copy-special
C-c C-x C-yPaste a subtree, adjusting its level (or a table region)org-paste-special
C-c C-x cClone the subtree, optionally shifting its datesorg-clone-subtree-with-time-shift
C-c @Mark the subtreeorg-mark-subtree
C-c ^Sort headings, list items or table rowsorg-sort
C-c *Turn a line into a heading or back; in a table, recalculateorg-ctrl-c-star
C-c ;Toggle the COMMENT keyword on a headingorg-toggle-comment
C-c C-x dInsert a drawerorg-insert-drawer
C-c C-,Insert a block from a structure templateorg-insert-structure-template
C-c 'Edit the element at point (source block, table formulas, and others) in a dedicated bufferorg-edit-special

Lists and checkboxes

KeyWhat it doesCommand
M-RETNew item at the same levelorg-meta-return
C-c -Cycle the bullet style; turn a line into an item; in a table, insert a ruleorg-ctrl-c-minus
S-<left> / S-<right>Cycle the bullet style (in an item)org-shiftleft, org-shiftright
C-c C-cToggle the checkbox of the itemorg-ctrl-c-ctrl-c
C-c C-x C-bToggle the checkbox; with C-u, add or remove itorg-toggle-checkbox
C-c C-x C-rToggle the item as a radio buttonorg-toggle-radio-button
C-c #Update statistics cookiesorg-update-statistics-cookies
KeyWhat it doesCommand
C-c C-lInsert a link, or edit the link at pointorg-insert-link
C-c C-oOpen the link at pointorg-open-at-point
C-c &Jump back to the position recorded before following a linkorg-mark-ring-goto
C-c %Record the current positionorg-mark-ring-push
C-c C-x C-n / C-c C-x C-pNext / previous linkorg-next-link, org-previous-link
C-c C-x C-vToggle link previews (inline images)org-link-preview
C-c C-x C-M-vRefresh link previewsorg-link-preview-refresh

Markup and rich content

KeyWhat it doesCommand
C-c C-x C-fInsert or change emphasis markersorg-emphasize
C-c C-x fCreate or jump to a footnoteorg-footnote-action
C-c C-x \Toggle display of entities and sub/superscripts as charactersorg-toggle-pretty-entities
C-c C-x C-lPreview LaTeX fragments as imagesorg-latex-preview
M-TABComplete keywords, tags, link types and morecomplete-symbol

Tables

KeyWhat it doesCommand
C-c |Create a table, or convert the region into oneorg-table-create-or-convert-from-region
TAB / S-TABNext / previous field, realigning the tableorg-cycle, org-shifttab
RETNext row (creates one at the end)org-return
C-c C-cRealign the tableorg-ctrl-c-ctrl-c
M-<left> / M-<right>Move the column left / rightorg-metaleft, org-metaright
M-S-<left> / M-S-<right>Delete the column / insert a columnorg-shiftmetaleft, org-shiftmetaright
M-<up> / M-<down>Move the row up / downorg-metaup, org-metadown
M-S-<up> / M-S-<down>Delete the row / insert a roworg-shiftmetaup, org-shiftmetadown
C-c -Insert a horizontal rule below the roworg-ctrl-c-minus
C-c RETInsert a rule and move below itorg-ctrl-c-ret
C-c `Edit the field in a separate windoworg-table-edit-field
S-RETCopy the field above into the current fieldorg-table-copy-down
C-c +Sum the numbers in the column or rectangleorg-table-sum
C-c TABShrink or expand the columnorg-ctrl-c-tab
C-c ~Insert a table.el table, or convert between formatsorg-table-create-with-table.el
C-c =Define a column formula (with C-u, a field formula)org-table-eval-formula
C-c 'Edit all formulas of the tableorg-edit-special
C-c *Recalculate the current row (with C-u, the table)org-ctrl-c-star
C-c ?Show information about the current fieldorg-table-field-info
C-c }Toggle row and column coordinatesorg-table-toggle-coordinate-overlays
C-c {Toggle the formula debuggerorg-table-toggle-formula-debugger
C-c " gPlot the table with Gnuplotorg-plot/gnuplot

See The Table Editor and The Spreadsheet and Plotting.

TODO items and priorities

KeyWhat it doesCommand
C-c C-tChange the TODO stateorg-todo
S-<left> / S-<right>Previous / next TODO state (on a heading)org-shiftleft, org-shiftright
C-S-<left> / C-S-<right>Switch to the previous / next TODO keyword setorg-shiftcontrolleft, org-shiftcontrolright
C-c ,Set the priorityorg-priority
S-<up> / S-<down>Raise / lower the priority (on a heading)org-shiftup, org-shiftdown
C-c C-x oToggle the ORDERED property (child dependencies)org-toggle-ordered-property
C-c C-zAdd a note to the entryorg-add-note
C-c / tSparse tree of TODO entriesorg-show-todo-tree

Tags, properties and column view

KeyWhat it doesCommand
C-c C-qSet tags of the current headingorg-set-tags-command
C-c C-cOn a heading: set tagsorg-ctrl-c-ctrl-c
C-c \Sparse tree from a tags/property matchorg-match-sparse-tree
C-c C-x qTurn support for tag groups on or off (org-group-tags)org-toggle-tags-groups
C-c C-x pSet a propertyorg-set-property
C-c C-x PSet a property and its value in one steporg-set-property-and-value
C-c C-x eSet the effort estimateorg-set-effort
C-c C-x C-cTurn on column vieworg-columns
C-c C-x xInsert a dynamic block (column view, clock table, …)org-dynamic-block-insert-dblock
C-c C-x C-uUpdate the dynamic block at pointorg-dblock-update

Inside column view (org-columns-map):

KeyWhat it doesCommand
eEdit the valueorg-columns-edit-value
n / pNext / previous allowed valueorg-columns-next-allowed-value, org-columns-previous-allowed-value
vShow the full valueorg-columns-show-value
aEdit the allowed valuesorg-columns-edit-allowed
sEdit the column’s attributesorg-columns-edit-attributes
< / >Narrow / widen the columnorg-columns-narrow, org-columns-widen
M-<left> / M-<right>Move the columnorg-columns-move-left, org-columns-move-right
M-S-<right> / M-S-<left>Insert / delete a columnorg-columns-new, org-columns-delete
gRecomputeorg-columns-redo
qLeave column vieworg-columns-quit

Dates and times

KeyWhat it doesCommand
C-c .Insert or change an active timestamp (with C-u, include the time)org-timestamp
C-c !Insert an inactive timestamporg-timestamp-inactive
C-c C-sSchedule the entryorg-schedule
C-c C-dSet a deadlineorg-deadline
S-<left> / S-<right>Change the date by one day (on a timestamp)org-shiftleft, org-shiftright
S-<up> / S-<down>Change the part of the timestamp under pointorg-shiftup, org-shiftdown
C-c C-yCompute the length of a time rangeorg-evaluate-time-range
C-c <Insert the date selected in the calendarorg-date-from-calendar
C-c >Show the date at point in the calendarorg-goto-calendar
C-c C-x C-tToggle custom timestamp formatsorg-toggle-timestamp-overlays

In the date prompt (org-read-date-minibuffer-local-map):

KeyWhat it doesCommand
.Go to todayorg-calendar-goto-today-or-insert-dot
S-<left> / S-<right>Previous / next dayorg-calendar-backward-day, org-calendar-forward-day
S-<up> / S-<down>Previous / next weekorg-calendar-backward-week, org-calendar-forward-week
M-S-<left> / M-S-<right>Previous / next monthorg-calendar-backward-month, org-calendar-forward-month
< / >Scroll the calendar by one monthorg-calendar-scroll-month-right, org-calendar-scroll-month-left
C-v / M-vScroll the calendar by three monthsorg-calendar-scroll-three-months-left, org-calendar-scroll-three-months-right

Clocking and timers

KeyWhat it doesCommand
C-c C-x C-iClock inorg-clock-in
C-c C-x C-oClock outorg-clock-out
C-c C-x C-xClock in to the last clocked taskorg-clock-in-last
C-c C-x C-qCancel the running clockorg-clock-cancel
C-c C-x C-jJump to the clocked taskorg-clock-goto
C-c C-x C-dShow clocked times in the bufferorg-clock-display
C-c C-x C-zResolve open or idle clocksorg-resolve-clocks
C-c C-x C-eModify the effort estimate of the clocked task (bound once org-clock is loaded)org-clock-modify-effort-estimate
C-c C-x 0Start a relative timerorg-timer-start
C-c C-x ;Start a countdown timerorg-timer-set-timer
C-c C-x .Insert the timer valueorg-timer
C-c C-x -Insert a list item with the timer valueorg-timer-item
C-c C-x ,Pause or continue the timerorg-timer-pause-or-continue
C-c C-x _Stop the timerorg-timer-stop

A clock table is inserted with C-c C-x x (choose clocktable) and updated with C-c C-c or C-c C-x C-u on its first line.

Capture, refile, archive and attachments

KeyWhereWhat it doesCommand
C-c C-ccapture bufferFinish and file the entryorg-capture-finalize
C-c C-kcapture bufferAbort the captureorg-capture-kill
C-c C-wcapture bufferRefile the entry to another locationorg-capture-refile
C-c C-wOrg bufferRefile the subtree (with C-u, only jump)org-refile
C-c M-wOrg bufferCopy the subtree to a refile targetorg-refile-copy
C-c C-x C-aOrg bufferArchive with the default methodorg-archive-subtree-default
C-c C-x C-s or C-c $Org bufferMove the subtree to the archive fileorg-archive-subtree
C-c C-x aOrg bufferToggle the ARCHIVE tagorg-toggle-archive-tag
C-c C-x AOrg bufferMove the subtree to the archive siblingorg-archive-to-archive-sibling
C-c C-aOrg bufferOpen the attachment dispatcherorg-attach

Agenda

In an Org buffer:

KeyWhat it doesCommand
C-c [Add the current file to the front of the agenda filesorg-agenda-file-to-front
C-c ]Remove the current file from the agenda filesorg-remove-file
C-' or C-,Visit the agenda files one after anotherorg-cycle-agenda-files
C-c C-x <Lock agenda restriction to the current subtree or fileorg-agenda-set-restriction-lock
C-c C-x >Remove the restriction lockorg-agenda-remove-restriction-lock

In the agenda dispatcher (C-c a):

KeyView
aAgenda for the current week or day
t / TAll TODO entries / entries with a chosen TODO keyword
m / MTags and properties match / the same, TODO entries only
s / SKeyword search / the same, TODO entries only
/Multi-occur across agenda files
#Stuck projects (! configures them)
?Entries tagged FLAGGED (Org Mobile)
< / >Restrict to the buffer, subtree or region / remove the restriction
eExport agenda views
*Toggle sticky agenda views
CConfigure custom agenda commands

In the agenda buffer (org-agenda-mode-map):

KeyWhat it doesCommand
n / pNext / previous lineorg-agenda-next-line, org-agenda-previous-line
N / PNext / previous itemorg-agenda-next-item, org-agenda-previous-item
SPCShow the entry in another windoworg-agenda-show-and-scroll-up
TABGo to the entry in another windoworg-agenda-goto
RETGo to the entry in this windoworg-agenda-switch-to
FToggle follow modeorg-agenda-follow-mode
d / w / yDay / week / year vieworg-agenda-day-view, org-agenda-week-view, org-agenda-year-view
vChoose a view or display optionorg-agenda-view-mode-dispatch
f / bForward / back in timeorg-agenda-later, org-agenda-earlier
.Go to todayorg-agenda-goto-today
jGo to a dateorg-agenda-goto-date
lToggle log modeorg-agenda-log-mode
RToggle the clock reportorg-agenda-clockreport-mode
r / gRebuild the view / all viewsorg-agenda-redo, org-agenda-redo-all
tChange the TODO stateorg-agenda-todo
:Set tagsorg-agenda-set-tags
,Set the priorityorg-agenda-priority
+ / -Raise / lower the priorityorg-agenda-priority-up, org-agenda-priority-down
eSet the effort estimateorg-agenda-set-effort
zAdd a noteorg-agenda-add-note
C-c C-s / C-c C-dSchedule / set a deadlineorg-agenda-schedule, org-agenda-deadline
I / O / XClock in / clock out / cancel the clockorg-agenda-clock-in, org-agenda-clock-out, org-agenda-clock-cancel
JJump to the clocked taskorg-agenda-clock-goto
/Filter (tags, categories, effort, regexp)org-agenda-filter
\ / < / ^ / _ / =Filter by tag / category / top headline / effort / regexporg-agenda-filter-by-tag and siblings
|Remove all filtersorg-agenda-filter-remove-all
m / u / UMark / unmark / unmark all for bulk actionorg-agenda-bulk-mark, org-agenda-bulk-unmark, org-agenda-bulk-unmark-all
% / *Mark by regexp / mark allorg-agenda-bulk-mark-regexp, org-agenda-bulk-mark-all
BRun a bulk action on marked itemsorg-agenda-bulk-action
kCapture with the date at pointorg-agenda-capture
C-c C-wRefile the entryorg-agenda-refile
$Archive the subtreeorg-agenda-archive
aArchive with the default method, after confirmationorg-agenda-archive-default-with-confirmation
C-kDelete the item and its entryorg-agenda-kill
C-_Undo a change made from the agendaorg-agenda-undo
EToggle entry text displayorg-agenda-entry-text-mode
DToggle the diaryorg-agenda-toggle-diary
GToggle the time gridorg-agenda-toggle-time-grid
C-c C-x C-cColumn view in the agendaorg-agenda-columns
sSave all Org buffersorg-save-all-org-buffers
C-x C-wWrite the agenda to a fileorg-agenda-write
q / Q / xQuit / quit and kill all agenda buffers / exit and kill Org buffers opened for the agendaorg-agenda-quit, org-agenda-Quit, org-agenda-exit

See Agenda Views.

Source code (Babel)

KeyWhereWhat it doesCommand
C-c C-con a blockEvaluate the blockorg-ctrl-c-ctrl-c
C-c 'on a blockEdit the block in its language’s major modeorg-edit-special
C-c 'edit bufferReturn to the Org bufferorg-edit-src-exit
C-c C-kedit bufferAbort the editorg-edit-src-abort
C-x C-sedit bufferSave the edit back to the Org bufferorg-edit-src-save
C-c C-v eOrg bufferEvaluate the block or call at pointorg-babel-execute-maybe
C-c C-v bOrg bufferEvaluate all blocks in the bufferorg-babel-execute-buffer
C-c C-v sOrg bufferEvaluate all blocks in the subtreeorg-babel-execute-subtree
C-c C-v tOrg bufferTangle the bufferorg-babel-tangle
C-c C-v fOrg bufferTangle a fileorg-babel-tangle-file
C-c C-v n / C-c C-v pOrg bufferNext / previous source blockorg-babel-next-src-block, org-babel-previous-src-block
C-c C-v gOrg bufferGo to a named blockorg-babel-goto-named-src-block
C-c C-v rOrg bufferGo to a named resultorg-babel-goto-named-result
C-c C-v oOrg bufferOpen the block’s resultorg-babel-open-src-block-result
C-c C-v vOrg bufferShow the expanded body (variables, noweb)org-babel-expand-src-block
C-c C-v kOrg bufferRemove resultsorg-babel-remove-result-one-or-many
C-c C-v dOrg bufferSplit the block at point, or wrap the region in a blockorg-babel-demarcate-block
C-c C-v jOrg bufferInsert a header argumentorg-babel-insert-header-arg
C-c C-v iOrg bufferAdd the buffer’s named blocks to the Library of Babelorg-babel-lob-ingest
C-c C-v zOrg bufferSwitch to the session bufferorg-babel-switch-to-session-with-code
C-c C-v IOrg bufferShow information about the blockorg-babel-view-src-block-info
C-c C-v hOrg bufferList all C-c C-v bindingsorg-babel-describe-bindings

Most C-c C-v keys also work with the second key held with Control, for example C-c C-v C-t. See Working with Source Code.

Export and publishing

C-c C-e (org-export-dispatch) opens the export dispatcher. You press a backend letter and then a format letter; options are toggled first.

Keys in the dispatcherAction
C-s / C-v / C-bToggle subtree only / visible only / body only
C-aToggle asynchronous export
C-fToggle forced publishing
h h / h H / h oHTML file / HTML buffer / HTML file and open it
l l / l p / l o / l LLaTeX file / PDF / PDF and open it / LaTeX buffer
t a / t u / t lPlain text file in ASCII / UTF-8 / Latin-1 (capital letters write to a buffer)
o o / o OODT file / ODT file and open it
c f / c a / c ciCalendar for this file / each agenda file / all agenda files combined
P f / P p / P x / P aPublish the current file / current project / a chosen project / all projects
#Insert an export options template
&Show the export stack
qQuit

These backends are loaded by default (org-export-backends). Others add their letters once you load them: Beamer adds l b, l B, l P and l O to the LaTeX menu, and Markdown (m), Org (O) and Texinfo (i) add their own menus. See Exporting and Publishing and Citations.

The context-sensitive keys

A small number of keys do the “obvious” thing wherever point is. They are worth learning first:

KeyCommandTypical effects
C-c C-corg-ctrl-c-ctrl-cToggle a checkbox, realign or recalculate a table, evaluate a source block, update a dynamic block, set tags on a heading, refresh a setting line
C-c 'org-edit-specialEdit a source block, table formulas, a table.el table or an example block in a dedicated buffer
C-c -org-ctrl-c-minusCycle bullets, make list items, insert a table rule
C-c *org-ctrl-c-starMake headings, recalculate a table
M-RETorg-meta-returnNew heading or item; wrap a region in a table
S-<arrow>org-shiftleft and siblingsChange TODO state, priority, timestamp or bullet
M-<arrow>org-metaleft and siblingsPromote, demote and move headings, items, table rows and columns

See Getting Started for how C-c C-c decides what to do.

Speed keys

With org-use-speed-commands turned on, single letters typed with point at the very beginning of a headline run commands. Press ? there to list them all.

KeyCommandKeyCommand
n / pnext / previous visible headingtorg-todo
f / bnext / previous heading at the same level,org-priority
uup to the parent:org-set-tags-command
jorg-gotoe / Eorg-set-effort / org-inc-effort
c / Corg-cycle / org-shifttabI / Oorg-clock-in / org-clock-out
sorg-toggle-narrow-to-subtreeworg-refile
U / Dorg-metaup / org-metadownaarchive with confirmation
l / rorg-metaleft / org-metaright/org-sparse-tree
L / Rorg-shiftmetaleft / org-shiftmetarightvorg-agenda
inew heading after the subtreeoorg-open-at-point
korg-cut-subtree=org-columns
^org-sort#org-toggle-comment
@org-mark-subtree?list all speed keys

Glossary

Each row gives a short definition and the chapter that explains the term.

TermMeaningExplained in
Active timestampA date in angle brackets, such as <2026-11-20 Fri>. Active timestamps place the entry in the agenda on that date.Dates and Times
AgendaA generated buffer that collects scheduled items, deadlines, appointments and TODO entries from all agenda files.Agenda Views
Agenda dispatcherThe menu that org-agenda shows, from which you choose a built-in or custom view.Agenda Views
Agenda filesThe files listed in org-agenda-files, which the agenda reads.Agenda Views
ArchiveA place for finished subtrees that keeps them out of the way: a separate archive file, the ARCHIVE tag, or an archive sibling heading.Capture, Refile, Archive and Attachments
AttachmentA file stored in a directory that belongs to an entry, managed with org-attach and referenced with attachment: links.Capture, Refile, Archive and Attachments
BabelThe part of Org that evaluates, tangles and exports source blocks.Working with Source Code
BackendAn export translator for one output format, such as HTML or LaTeX. A derived backend reuses another backend and overrides parts of it.Exporting
BlockA region between #+BEGIN_NAME and #+END_NAME lines, for example a quote, example or source block.Document Structure
Block agendaA custom agenda command that shows several views one after another in one buffer.Agenda Views
CaptureRecording a note or task quickly, from anywhere in Emacs, without losing your current context.Capture, Refile, Archive and Attachments
Capture templateAn entry in org-capture-templates that defines what a capture creates and where it is filed.Capture, Refile, Archive and Attachments
CategoryThe label shown in front of agenda lines; it defaults to the file name and can be set with the CATEGORY keyword or property.Agenda Views
CheckboxA [ ] marker at the start of a plain list item, which you tick off with C-c C-c.TODO Items
CitationA reference to a bibliography entry, written as [cite:@key] and rendered by a citation processor on export.Publishing and Citations
Clock tableA dynamic block that summarizes clocked time.Clocking, Effort and Timers
ClockingRecording the time spent on an entry with CLOCK: lines, usually inside a LOGBOOK drawer.Clocking, Effort and Timers
Column viewA tabular display of the properties of entries, overlaid on the outline.Tags, Properties and Column View
COMMENTA keyword at the start of a heading that excludes the subtree from export.Exporting
Custom agenda commandA view you define in org-agenda-custom-commands and select from the dispatcher by its key.Agenda Views
CUSTOM_IDA property that gives an entry a stable, human-readable target for links and exported anchors.Hyperlinks
DeadlineA date by which an entry must be done, set with C-c C-d; the agenda warns about it in advance.Dates and Times
Diary sexpA timestamp written as a Lisp expression, such as <%%(diary-float t 4 2)>, for dates that follow a rule.Dates and Times
DrawerA named, foldable region between :NAME: and :END: that holds data such as properties or logs.Document Structure
Dynamic blockA block between #+BEGIN: name and #+END: whose content a function regenerates on request, such as a clock table or a column view.Tags, Properties and Column View and Hacking and Extending Org
EffortAn estimate of the work an entry requires, stored in the Effort property.Clocking, Effort and Timers
Element and objectThe 2 kinds of syntax unit in Org’s parser. Elements are block-level (paragraphs, tables, headlines); objects occur inside them (links, emphasis, timestamps).Markup for Rich Contents and Hacking and Extending Org
EntityA named special character written with a backslash, such as \alpha or \to, rendered correctly in each export format.Markup for Rich Contents
EntryA headline together with the text and drawers that follow it up to the next headline.Document Structure
Export dispatcherThe menu opened by C-c C-e, from which you choose a backend, a format and options.Exporting
Export filterA function that modifies the output of a backend at a specific stage, for one type of element or for the whole result.Exporting
Fast selectionChoosing a TODO keyword or tag with a single key from a popup, configured with key characters in the keyword or tag definitions.TODO Items and Tags, Properties and Column View
FootnoteA note referenced as [fn:name] in the text and defined elsewhere in the file, or inline.Markup for Rich Contents
HabitA repeating TODO entry with the STYLE property set to habit, which the agenda shows with a consistency graph.TODO Items
Header argumentAn option of a source block, such as :var, :results or :tangle, set on the block, in a property or globally.Working with Source Code
HeadlineA line that starts with one or more stars followed by a space. The number of stars is its level.Document Structure
HookA variable holding functions that Org runs at a defined moment, used to customize behavior.Hacking and Extending Org
IDA globally unique identifier stored in the ID property, which lets id: links find an entry in any file.Hyperlinks
In-buffer settingA line of the form #+KEYWORD: value that configures the current file, for example #+STARTUP or #+TODO.Getting Started
Inactive timestampA date in square brackets, such as [2026-11-19 Thu]. It records when something happened but does not put the entry in the agenda.Dates and Times
IncludeThe #+INCLUDE keyword, which inserts another file or part of one at export time.Exporting
InheritanceThe rule by which a subtree receives tags or properties from its ancestors.Tags, Properties and Column View
Library of BabelA collection of named source blocks that you can call from any Org file.Working with Source Code
Link abbreviationA short prefix, defined in org-link-abbrev-alist or a #+LINK line, that expands into a longer URL.Hyperlinks
LOGBOOKThe drawer where Org stores state-change notes and clock lines when logging into a drawer is enabled.TODO Items and Clocking, Effort and Timers
MacroA text replacement written as {{{name(args)}}} and expanded during export.Exporting
Match stringA small query language over tags, properties and TODO states, such as work+urgent-TODO="DONE", used by sparse trees and agenda views.Tags, Properties and Column View
Noweb referenceA reference such as <<block-name>> inside a source block that is replaced by the body or result of another block.Working with Source Code
Org CryptA library that encrypts the body of entries carrying a chosen tag.Org Beyond the Basics
Org MobileA protocol for synchronizing Org files with a mobile application through a staging directory.Org Beyond the Basics
org-protocolA URL scheme that lets external programs trigger Org actions such as capture through emacsclient.Org Beyond the Basics
Orgtbl modeA minor mode that brings the Org table editor to other major modes.The Table Editor
Parse treeThe nested data structure that org-element-parse-buffer builds from a buffer, used by the exporter and by extensions.Hacking and Extending Org
Plain listAn ordered, unordered or description list written with -, +, 1. or similar bullets.Document Structure
PriorityA cookie such as [#A] in a headline that ranks entries.TODO Items
PropertyA key-value pair attached to an entry, stored in its property drawer.Tags, Properties and Column View
Property drawerThe :PROPERTIES: drawer directly below a headline.Tags, Properties and Column View
Publishing projectAn entry in org-publish-project-alist that describes which files to export, how, and where to put the results.Publishing and Citations
Radio targetA target written as <<<text>>>; every occurrence of the text in the file becomes a link to it.Hyperlinks
RefileMoving an entry to another location, usually from an inbox to a project.Capture, Refile, Archive and Attachments
RepeaterA suffix such as +1w, ++1w or .+1w in a timestamp that makes the entry recur.Dates and Times
ResultsThe output of a source block, inserted after a #+RESULTS: line.Working with Source Code
ScheduledThe date on which you plan to start working on an entry, set with C-c C-s.Dates and Times
SessionA persistent interpreter process shared by source blocks that use the same :session header argument.Working with Source Code
SitemapAn index file that the publishing system can generate for a project.Publishing and Citations
Sparse treeA view of the buffer folded so that only matching entries and their context remain visible.Document Structure
Special propertyA property that Org computes or maintains, such as ITEM, TODO, CLOSED or CLOCKSUM, and that you can use in searches and column view.Tags, Properties and Column View
Speed keysSingle-letter commands available with point at the beginning of a headline, enabled with org-use-speed-commands.Getting Started
Statistics cookieA [2/5] or [40%] marker that shows progress on child entries or checkboxes.TODO Items
Structure templateA shortcut for inserting a block, selected with C-c C-,.Getting Started
Stuck projectA project that has no next action, as defined by org-stuck-projects.Agenda Views
SubtreeA headline together with all the headlines nested below it.Document Structure
TagA label written between colons at the end of a headline, such as :work:.Tags, Properties and Column View
Tag groupA tag that stands for a set of other tags in searches.Tags, Properties and Column View
TangleExtracting source blocks into separate source files.Working with Source Code
TargetAn anchor written as <<name>> that internal links can point to.Hyperlinks
TimerA relative or countdown timer whose values can be inserted into notes.Clocking, Effort and Timers
TODO keywordA word at the start of a headline, such as TODO or DONE, that marks the entry’s state. Keywords form sequences, divided into active and done states.TODO Items
TranscoderThe function of a backend that turns one type of element or object into output text.Exporting
Visibility cyclingFolding and unfolding the outline with TAB and S-TAB.Document Structure
Warning periodThe number of days before a deadline when the agenda starts to show it, set globally or with a suffix such as -3d.Dates and Times

Further reading