An extractor is a function vulpea calls for every note it indexes, with the note’s parsed data in hand and the org-element tree on request. It can write to tables of its own, declared next to it and created for you, or change the note’s core data before it is stored. Every extractor sees the same parse, runs inside the same transaction as the core write, and carries a version, so bumping a number is enough to rebuild its tables.
Write one when the data you want lives in the note text but in no
column vulpea keeps: citations, code blocks, a reading time, a
relation between notes that is not an id: link. Anything you can
express as a query over the existing tables does not need a plugin.
Every extractor receives a parse context with:
:path- absolute path to the org file:hash- content hash for change detection:mtime- modification time:size- file size in bytes:ast- complete org-element AST for the file (only for extractors declaring:requires-ast t; nil for everyone else):file-node- parsed file-level note data:heading-nodes- list of parsed heading-level notes
Access context data using:
(vulpea-parse-ctx-ast ctx) ; Get the AST (requires-ast t only)
(vulpea-parse-ctx-file-node ctx) ; Get file-level note
(vulpea-parse-ctx-heading-nodes ctx) ; Get all headingsThe AST is opt-in. An extractor only receives the AST when its
definition declares :requires-ast t - every other extractor gets a
context whose :ast slot is nil, deterministically. This is because
the full parse the AST comes from is about 2.6x slower than the one
vulpea needs for its own extraction (see bench/README.md), and the AST cannot cross the async worker’s process
boundary; the declaration is how you consciously pay that cost. See
*Extractors and Async Extraction for the full picture.
Each extractor receives and returns note-data, a plist containing:
:id- note ID (UUID):path- absolute path to the containing org file:level- heading level (0 for the file-level note):pos- position in file (0 for the file-level note):title- note title:properties- alist of org properties:tags- list of tags:aliases- list of aliases:meta- metadata alist:links- list of links:todo- TODO state:priority- priority level:scheduled,:deadline,:closed- timestamps:category- resolved org category (seevulpea-note-category):outline-path- path to heading:attach-dir- attachment directory
Extractors can also add custom keys to note-data, but those are
transient: they live only for the duration of the current extraction
run, as a way to pass data to extractors that run later (see
Extractor Dependencies). They are never
written to the database.
Persistence goes strictly by the field list above. After all extractors
have run, any core field an extractor changed is written back to the
note’s row in the notes table, and the normalized tables (tags,
links, meta, properties) are re-synced to match. Any key outside
that list is silently ignored at this point: a custom :word-count key
does not become a word_count column in notes, no matter how it is
spelled. Adding a link to :links, on the other hand, makes it a
first-class link - it shows up in backlink queries exactly like a link
parsed from the file. See Contributing to Core Data.
If your plugin computes per-note data that should survive, put it where
persistent data lives: in your plugin’s own tables (the :schema
field) or in the file itself (a property or a metadata entry). See
Storing Per-Note Data for the common shapes.
Use make-vulpea-extractor to create an extractor:
(make-vulpea-extractor
:name 'my-extractor ; Symbol identifying the extractor
:version 1 ; Schema version for migrations
:priority 50 ; Execution order (lower = earlier)
:requires-ast t ; Declare when extract-fn reads the AST
:reads-dir-locals nil ; Declare when output depends on dir-locals
:schema '(...) ; Database schema definition
:extract-fn #'my-extract-fn) ; Extraction functionDeclare :requires-ast explicitly, one way or the other:
:requires-ast tif your function calls(vulpea-parse-ctx-ast ctx). Without this declaration the AST slot is always nil and your extractor will extract nothing.:requires-ast nilif it works purely fromnote-data(and the non-AST context slots). This keeps extraction fast and files eligible for async extraction.
Leaving it undeclared behaves like nil, but M-x vulpea-doctor will
nag about it.
Declare :reads-dir-locals t when your extract function’s output
depends on directory-local variables of the note’s path - for example
reading a project marker or category from the nearest
.dir-locals.el. The declaration makes autosync force re-index the
affected subtree whenever a .dir-locals.el (or .dir-locals-2.el)
changes, so your stored output cannot go silently stale (see
vulpea-db-sync-reindex-on-dir-locals-change; its default auto
honors this declaration). Same intent-declaration pattern as
:requires-ast: undeclared behaves like nil.
Define custom database tables using the same syntax as vulpea-db--schema:
:schema '((my_table
[(note-id :not-null)
(my-field :not-null)
(my-value)]
(:primary-key [note-id my-field])
(:foreign-key [note-id] :references notes [id]
:on-delete :cascade)))Important: Always use :on-delete :cascade for foreign keys to notes.
This ensures your data is cleaned up when notes are deleted.
Extractor functions have the signature:
(defun my-extractor-fn (ctx note-data)
"Extract custom data from CTX and NOTE-DATA.
CTX is the parse context (vulpea-parse-ctx).
NOTE-DATA is the plist of note data being processed.
Returns NOTE-DATA, possibly with additional keys added."
;; 1. Extract data from the AST
;; (only available when the extractor declares :requires-ast t)
(let* ((ast (vulpea-parse-ctx-ast ctx))
(note-id (plist-get note-data :id))
(my-data (extract-my-data ast)))
;; 2. Insert into custom table
(when my-data
(emacsql (vulpea-db)
[:insert :into my-table :values $v1]
(mapcar (lambda (item)
(vector note-id item))
my-data)))
;; 3. Optionally add to note-data for other extractors
;; (transient: visible to later extractors in this run,
;; never persisted - the table insert above is the storage)
(when my-data
(plist-put note-data :my-custom-key my-data))
;; 4. Return note-data
note-data))Register your extractor during initialization:
(vulpea-db-register-extractor
(make-vulpea-extractor
:name 'my-extractor
:version 1
:priority 50
:requires-ast t ; my-extractor-fn reads the AST
:schema '((my_table [...]))
:extract-fn #'my-extractor-fn))An extractor is not limited to its own tables - it can contribute to the
note’s core data by changing the corresponding note-data field and
returning the plist. Whatever changed after all extractors have run is
persisted to both storage forms: the materialized notes row and the
normalized table behind the field.
For example, an extractor that promotes links found in metadata to first-class links:
(defun my-promote-meta-links (_ctx note-data)
"Turn id: links in metadata into real note links."
(let ((meta-links
(cl-loop for (_key . values) in (plist-get note-data :meta)
append (cl-loop for value in values
when (string-match
"\\[\\[id:\\([^]]+\\)\\]" value)
collect (list :dest (match-string 1 value)
:type "id"
:pos 0
:description nil)))))
(when meta-links
(plist-put note-data :links
(append (plist-get note-data :links) meta-links))))
note-data)
(vulpea-db-register-extractor
(make-vulpea-extractor
:name 'promote-meta-links
:requires-ast nil
:extract-fn #'my-promote-meta-links))The contributed links now appear in vulpea-db-query-links-to, backlink
counts, and vulpea-note-links - indistinguishable from links parsed out
of the file body.
A few rules:
- Mutate =note-data=, not core tables. Do not
INSERTintonotes,tags,links,metaorpropertiesyourself - the materializednotesrow and the normalized tables must stay consistent, and raw inserts update only one side. Change the field innote-dataand let vulpea write both. - Identity is fixed. Changes to
:id,:path,:leveland:posare ignored - plugin tables hold foreign keys against them. - Removal works too. Deleting an entry from a field removes it from both storage forms.
- Return the plist you received. Mutate it in place (or
appendto a field andplist-putthe result) and return it. Do not build a fresh plist with only the fields you touched - a missing field reads as “the extractor removed this” and is wiped from both storage forms. - Returning nil means “use =note-data= as it now stands”. In-place mutations made before the nil return are still persisted; nil only says “nothing further to contribute”.
Core extraction (the notes row and the normalized tables) is not a
registered extractor: it always runs first and produces the
note-data your extractor receives. The core rows of every note in the
file are written before any extractor runs, so a plugin table can hold
a foreign key to any note of the file being indexed. Registered
extractors then run note by note, in priority order, lower numbers
first. The default is 100.
The only reason to pick a number is ordering: when extractor B reads a
transient key that extractor A put into note-data (see
Extractor Dependencies), A needs the lower priority. Otherwise leave
the default.
;; Citations: writes :citations into note-data for others to read
:priority 30
;; Reading time: counts the citations, so it runs after them
:priority 50With vulpea-db-async-extraction enabled, parsing happens in a
worker subprocess - and the org-element AST never crosses the
process boundary. This is why the AST is opt-in for extractors. Two
declarations on make-vulpea-extractor control the interaction:
(vulpea-db-register-extractor
(make-vulpea-extractor
:name 'my-attachments
:requires-ast nil ; works purely from NOTE-DATA
:worker-safe t ; may run inside the worker (full mode)
:worker-lib 'my-lib ; feature/file the worker loads for the fn
:schema '((attachments [(note-id :not-null) (file :not-null)]))
:extract-fn #'my-attachments-fn)):requires-ast tdeclares that your function reads(vulpea-parse-ctx-ast ctx). It is the only way to receive the AST, and it has a price: every file is parsed at the slower'objectgranularity, and async extraction is disabled for every file (the AST cannot cross the process boundary).- Anything else -
:requires-ast nilor no declaration at all (the default) - means your function works from the NOTE-DATA plist \(:id,:attach-dir,:meta, …) and the non-AST context slots. Extraction stays at'elementgranularity and files stay worker-eligible; your extractor runs in the main process when results arrive, against a context whose AST slot is always nil. Prefer the explicit:requires-ast nil- it states intent, andM-x vulpea-doctornudges about undeclared extractors. :worker-safe t(requires a non-AST extractor in practice, and a symbol:extract-fn) additionally lets the extractor run inside the worker in'fullmode, writing its tables through the worker’s connection - preserving the zero-freeze write. The worker loads:worker-libto resolve the function; if it cannot, it transparently falls back to streaming results and your extractor runs in the main process. Nothing is lost either way.
Declare honestly: an AST reader without :requires-ast t finds the
AST nil every single time - it extracts nothing, and you notice on
first test. This is deliberate. The alternative (handing over
whatever tree the core parse happened to build) would sometimes be
the full object tree and sometimes a degraded element-granularity
one that silently lacks inline objects like citations.
Contributions to core note-data fields (see <a href=”*Contributing to Core
Data”>Contributing to Core Data) work identically in every mode:
whichever process runs the extractor also persists its changes, so a
worker-safe extractor adding a link in full mode writes it through
the worker’s own connection.
Each extractor has a version number tracked in the schema-registry table:
(make-vulpea-extractor
:name 'my-extractor
:version 2 ; Incremented from 1
:schema '(...))Bumping the version is the whole migration story. When vulpea sees a
higher version than the stored one, it drops the tables declared in
:schema, recreates them from the current definition, and clears the
file change cache, so every file is re-extracted - the same mechanism
as a vulpea parser upgrade. Plugin tables are recomputable caches
(everything in them comes from extraction), so the drop loses
nothing. Same or lower version is a no-op.
Two things to keep in mind:
- Tables are matched by the current
:schema. If you rename a table across versions, the old table is not dropped; clean it up manually. - Re-extraction rides the regular sync mechanism. Registration
usually happens before
vulpea-db-autosync-modestarts sync, so the forced re-index kicks in right at sync start. If you bump the version mid-session, the tables stay empty until the next sync start or directory scan.
;; Check if table exists. Dashes and underscores are
;; interchangeable: emacsql converts dashes to underscores when it
;; creates a table (my-table is stored as my_table), and the check
;; normalizes its argument the same way, so both spellings work.
(vulpea-db--table-exists-p 'my-table)
;; Check current version (extractor names are stored as strings)
(caar (emacsql (vulpea-db)
[:select [version] :from schema-registry
:where (= name $s1)]
"my-extractor"))This example extracts citations in the format [@citekey] from notes and
stores them in a custom table.
(defun my-extract-citations (ctx note-data)
"Extract citations from org content in format [@citekey]."
(let* ((ast (vulpea-parse-ctx-ast ctx))
(note-id (plist-get note-data :id))
(citations nil))
;; Extract citations from all paragraphs
(org-element-map ast 'paragraph
(lambda (para)
(let ((content (org-element-interpret-data para))
(pos 0))
(while (string-match "\\[@\\([^]]+\\)\\]" content pos)
;; Strip text properties: emacsql stores a propertized
;; string in its printed #("...") form
(push (substring-no-properties (match-string 1 content))
citations)
(setq pos (match-end 0))))))
;; Insert unique citations into custom table
(when citations
(let ((unique-citations (delete-dups (nreverse citations))))
(emacsql (vulpea-db)
[:insert :into citations :values $v1]
(mapcar (lambda (citekey)
(vector note-id citekey))
unique-citations))
;; Add to note-data for other extractors
(plist-put note-data :citations unique-citations)))
note-data))(vulpea-db-register-extractor
(make-vulpea-extractor
:name 'citations
:version 1
:priority 50
:requires-ast t ; my-extract-citations maps the AST
:schema '((citations
[(note-id :not-null)
(citekey :not-null)]
(:primary-key [note-id citekey])
(:foreign-key [note-id] :references notes [id]
:on-delete :cascade)))
:extract-fn #'my-extract-citations))After extraction, you can query the data:
;; Find all notes that cite a specific paper
(emacsql (vulpea-db)
[:select [notes:id notes:title]
:from notes
:inner :join citations
:on (= notes:id citations:note-id)
:where (= citations:citekey $s1)]
"smith2020")
;; => (("paper-1-id" "My Paper") ("paper-2-id" "Another Paper"))
;; Get all citations from a note
(emacsql (vulpea-db)
[:select [citekey] :from citations
:where (= note-id $s1)]
"my-note-id")
;; => (("smith2020") ("jones2019"))
;; Count citations per paper
(emacsql (vulpea-db)
[:select [citekey (funcall count note-id)]
:from citations
:group :by citekey
:order :by [(desc (funcall count note-id))]])
;; => (("smith2020" 5) ("jones2019" 3))See test/vulpea-db-extract-test.el for the complete test:
vulpea-db-extract-plugin-example-citations
Each of these is cheap to do and expensive to skip, and skipping any of them fails without an error.
- Declare
:requires-asteither way. An AST reader that forgets it extracts nothing and never errors. - Give every table a foreign key to
noteswith:on-delete :cascade, and a primary key that makes a duplicate row impossible ((note-id, field)is the usual shape). Deleted notes then clean up after themselves, and re-extraction cannot double rows. - Strip text properties from strings pulled out of the AST
(
substring-no-properties). emacsql stores a propertized string in its printed#("...")form, and the value is then wrong in every query. - Do not catch errors. Extractors run inside the write transaction, so
an error rolls back the whole file, which is the state you want: no
half-extracted note. Use
lwarnfor things worth knowing that should not abort. - Walk the AST once. Each
org-element-mapover a 10MB file is paid in full, so collect everything you need in one pass.
If extractor B depends on data from extractor A:
- Set A’s priority lower than B’s (A runs first)
- Have A add data to
note-data - Have B read from
note-data
;; Extractor A: priority 30
(defun extractor-a (ctx note-data)
(let ((data (extract-something ctx)))
(plist-put note-data :a-data data)
note-data))
;; Extractor B: priority 50 (runs after A)
(defun extractor-b (ctx note-data)
(let ((a-data (plist-get note-data :a-data)))
(when a-data
(process-a-data a-data))
note-data))Remember that :a-data here is transient - it exists so B can see what
A computed within the same extraction run, and it is gone afterwards.
If either extractor wants to keep the data, it has to write it to its
own table.
A question that came up in vulpea#382: what if my plugin computes
exactly one value per note, say a reading time? Custom note-data
keys do not help (they are transient, see
:schema '((note-reading-time
[(note-id :not-null :primary-key)
(minutes :not-null)]
(:foreign-key [note-id] :references notes [id]
:on-delete :cascade)))
The extractor writes at most one row per note:
(emacsql (vulpea-db)
[:insert :or :replace :into note-reading-time :values $v1]
(list (vector note-id minutes)))And queries join it in:
(emacsql (vulpea-db)
[:select [notes:id notes:title note-reading-time:minutes]
:from notes
:left :join note-reading-time
:on (= notes:id note-reading-time:note-id)])If you expect several such per-note attributes, do not multiply
tables (note-reading-time, note-foo, note-bar, …). Use one
generic table keyed by (note-id, axis):
:schema '((note-attrs
[(note-id :not-null)
(axis :not-null)
(value :not-null)]
(:primary-key [note-id axis])
(:foreign-key [note-id] :references notes [id]
:on-delete :cascade)))One table, one row per (note, axis) pair, and a new axis is a new
axis value instead of a new table.
Do not let row counts scare you away from either shape: a table of skinny rows keyed by an indexed primary key is exactly what SQLite is built for, and a few hundred (or a few hundred thousand) of them is not duplication, it is just normalized data.
One more option worth considering: if the value really is an attribute
of the note, maybe it belongs in the file rather than only in the
database. A property or a metadata entry survives re-extraction by
definition, shows up in note-data (:properties / :meta) for free,
and stays queryable through the normalized properties and meta
tables without any plugin code at all.
Skip extraction based on file properties:
(defun my-conditional-extractor (ctx note-data)
;; Only extract from files in specific directory
(let ((path (vulpea-parse-ctx-path ctx)))
(if (string-match-p "/projects/" path)
(progn
;; Do extraction
note-data)
;; Skip extraction
note-data)))Extract summary data across the entire file:
(defun my-summary-extractor (ctx note-data)
(let* ((file-node (vulpea-parse-ctx-file-node ctx))
(heading-nodes (vulpea-parse-ctx-heading-nodes ctx))
(all-nodes (cons file-node heading-nodes)))
;; Calculate aggregate data
(let ((total-todos (seq-count
(lambda (n) (plist-get n :todo))
all-nodes)))
;; Store summary for file-level note only
(when (= (plist-get note-data :level) 0)
(emacsql (vulpea-db)
[:insert :into file-summaries :values $v1]
(list (vector (plist-get note-data :id)
total-todos)))))
note-data))(defun my-debug-extractor (ctx note-data)
;; Print context information
(message "Processing: %s" (vulpea-parse-ctx-path ctx))
(message "File size: %s bytes" (vulpea-parse-ctx-size ctx))
(message "Note ID: %s" (plist-get note-data :id))
(message "Note title: %s" (plist-get note-data :title))
;; Inspect AST structure (nil unless registered with :requires-ast t)
(let ((ast (vulpea-parse-ctx-ast ctx)))
(message "AST type: %s" (org-element-type ast)))
note-data)(ert-deftest my-extractor-test ()
(vulpea-test--with-temp-db
(vulpea-db)
(let ((vulpea-db--extractors nil))
;; Register only your extractor
(vulpea-db-register-extractor
(make-vulpea-extractor
:name 'my-test
:version 1
:priority 50
:schema '(...)
:extract-fn #'my-extract-fn))
;; Test with specific content. The ID must live in a property
;; drawer - a #+ID: keyword is not an org ID and the file would
;; not be indexed at all.
(let ((path (vulpea-test--create-temp-org-file
":PROPERTIES:\n:ID: test-id\n:END:\n#+TITLE: Test\n\nTest content")))
(unwind-protect
(progn
(vulpea-db-update-file path)
;; Verify extraction results
(should (= (my-count-extracted-data) 1)))
(delete-file path))))))(vulpea-db-register-extractor EXTRACTOR)- Register a new extractor
(vulpea-db-unregister-extractor NAME)- Unregister an extractor
(vulpea-db-get-extractor NAME)- Get registered extractor by name
(vulpea-db--table-exists-p TABLE)- Check if table exists
(vulpea-db--index-exists-p INDEX)- Check if index exists
Both checks normalize dashes to underscores, matching emacsql identifier escaping, so either spelling of a name works.
Registered schema versions live in the schema-registry table (keyed
by extractor name as a string); query it with emacsql as shown in
Migration Helpers.
(vulpea-parse-ctx-path CTX)- Get file path
(vulpea-parse-ctx-hash CTX)- Get file hash
(vulpea-parse-ctx-mtime CTX)- Get modification time
(vulpea-parse-ctx-size CTX)- Get file size
(vulpea-parse-ctx-ast CTX)- Get org-element AST (nil unless the
extractor declares
:requires-ast t) (vulpea-parse-ctx-file-node CTX)- Get file-level note data
(vulpea-parse-ctx-heading-nodes CTX)- Get heading-level notes
All extractors have access to:
(vulpea-db)- Get database connection
(emacsql DB QUERY ARGS...)- Execute SQL query
See test/vulpea-db-extract-test.el for:
vulpea-db-extract-plugin-example-citations- Citation extraction
- Architecture
- Design decisions and rationale
- API Reference
- Core API documentation
- Sync Architecture
- File watching and async updates
- org-element API
- org-element documentation
- emacsql
- SQL database library
- SQLite SQL
- SQL syntax reference
Plugins live in their own packages, not in this repository. vulpea-tag-links is one to learn from. When yours is ready, open a pull request adding it to the Ecosystem section of the README.