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:
- Options. Org defines more than 1,000 user options.
M-x customize-group RET org RETbrowses them, andC-h vdescribes one. - 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.
- Entry APIs. The property API and the mapping API read and change headings, tags and properties, which is enough for most automation.
- 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.
- 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:
| Hook | Runs when |
|---|---|
org-mode-hook | A buffer enters Org mode. |
org-after-todo-state-change-hook | A TODO state has changed; the new state is in org-state. |
org-blocker-hook | Before a state change; any function returning nil blocks it. |
org-trigger-hook | After a state change, with a property list describing it. |
org-after-tags-change-hook | Tags of an entry have changed. |
org-property-changed-functions | A property was set; called with the property name and value. |
org-insert-heading-hook | A new heading has been inserted. |
org-cycle-hook | After a visibility change by TAB. |
org-capture-before-finalize-hook | A capture is about to be filed. |
org-clock-in-hook, org-clock-out-hook | The clock starts or stops. |
org-agenda-finalize-hook | An agenda buffer has been built. |
org-babel-after-execute-hook | A code block has been evaluated. |
org-export-before-processing-functions | Export starts, before macros, includes and Babel run. |
org-export-before-parsing-functions | Export 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
headlinenode, not children of it. The body lives in itssection. - The space after
*summary*does not appear in the next string, because it belongs to theboldobject 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:
| Function | Returns |
|---|---|
org-element-type | The node type, such as headline or link. |
org-element-property | One property, for example (org-element-property :level node). |
org-element-contents | The list of child nodes. |
org-element-begin, org-element-end | Buffer positions of the node. |
org-element-lineage | The 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-pointreturns the element at point.org-element-contextreturns 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.
Custom link types
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:
| Parameter | Purpose |
|---|---|
:follow | Called by C-c C-o with the path and the prefix argument. |
:export | Called with path, description, backend and the export information; returns the backend’s text. When absent, the backend handles the link itself. |
:store | Called by org-store-link; returns non-nil after calling org-link-store-props when it can link to the current buffer. |
:complete | Called by C-c C-l to build a link of this type with completion. |
:face | Face for the link in the buffer, or a function of the path returning one. |
:help-echo | Tooltip text, or a function producing it. |
:preview | A 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 (
nilfor nodes without contents, such as source blocks) andinfo, the communication channel: a property list with the export options and the parse tree. It returns a string. Helper functions such asorg-export-format-code-defaulthandle 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 andinfo, and returns the modified text. Filters can be attached to one backend with:filters-alist, or to every export through variables such asorg-export-filter-headline-functionsandorg-export-filter-final-output-functions. :menu-entryadds 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 (mfor 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 manual: Hacking, Hooks
- Org manual: Using the Property API, Using the Mapping API, Org Syntax, Documentation Access
- Org manual: Adding Hyperlink Types, Adding Hyperlink preview, Dynamic Blocks, Adding Export Backends
- Source: lisp/org-element.el (parser), lisp/org-element-ast.el (node accessors), lisp/ol.el (
org-link-parameters), lisp/ox.el (export engine), lisp/ox-md.el (a derived backend), lisp/ol-man.el (a link type) - Worg: Org Syntax, Org Export Reference