;;; elel.el --- Front end for the elel notes engine -*- lexical-binding: t; -*-
;; Copyright (C) 2026 Durand
;; Author: Durand
;; Keywords: outlines, files
;; Package-Requires: ((emacs "27.1"))
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see .
;;; Commentary:
;; This is the Emacs side of elel. The engine (a Rust program in the
;; same directory) reads the note files and keeps an index; this file
;; only shows what the engine reports and helps to write notes.
;;
;; The interface follows Gnus:
;;
;; Group buffer -> the views buffer, M-x elel
;; Summary buffer -> the summary buffer, threaded by Parent
;; Article buffer -> the article buffer, the note as it is in its
;; file, in the major mode of its file, with the
;; minor mode `elel-article-mode' on top
;;
;; The summary and the article are shown together; close either.
;; The engine never writes to the note files. Creating notes and
;; adding missing IDs is done here.
;;; Code:
(require 'cl-lib)
(require 'subr-x)
(require 'button)
(require 'outline)
(require 'rx)
(require 'hl-line)
(declare-function org-link-set-parameters "ol" (type &rest parameters))
(declare-function org-entry-get "org" (epom property &optional inherit literal-nil))
(defvar elel-article-id)
(defvar elel-capture-id)
(declare-function org-next-link "org" (&optional search-backward))
(declare-function org-previous-link "org" ())
(declare-function org-fold-hide-drawer-all "org-fold" ())
(declare-function org-hide-drawer-all "org" ())
(declare-function org-open-at-point "org" (&optional arg))
(declare-function org-back-to-heading "org" (&optional invisible-ok))
(declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
;;; Customization
(defgroup elel nil
"A notes system with full-text search and links."
:group 'applications
:prefix "elel-")
(defconst elel--directory
(file-name-directory (or load-file-name buffer-file-name default-directory))
"The directory of this file.")
(defcustom elel-root (expand-file-name "~/notes")
"The directory that holds the note files."
:type 'directory)
(defcustom elel-index-directory nil
"The directory of the derived index.
If nil, the engine chooses its own default."
:type '(choice (const :tag "Engine default" nil) directory))
(defcustom elel-program
(let ((release (expand-file-name "target/release/elel" elel--directory))
(debug (expand-file-name "target/debug/elel" elel--directory)))
(cond
((file-executable-p release) release)
((file-executable-p debug) debug)
((executable-find "elel"))
("elel")))
"The engine executable."
:type 'file)
(defcustom elel-capture-file "inbox.org"
"The file, relative to `elel-root', where new notes are written.
The extension decides the format: \".org\" or \".txt\"."
:type 'string)
(defcustom elel-auto-index t
"If non-nil, update the index after saving a file under `elel-root'."
:type 'boolean)
(defcustom elel-id-function #'elel-generate-id
"The function that makes the ID of a new note."
:type 'function)
(defcustom elel-views
(list
(list "Inbox" "is:inbox")
(list "Recent" "" :limit 30)
(list "All" ""))
"The views listed in the views buffer, like the groups of Gnus.
Each element is (NAME QUERY . PLIST). QUERY is a search query (see
the README), and PLIST may have these properties:
:limit N show at most N notes;
:hidden t list the view only after \\`L' (list all views).
Views for a tag or a file are just entries such as
(\"Math\" \"tag:math\") or (\"Journal\" \"file:journal\" :hidden t)."
:type '(repeat (cons string (cons string plist))))
(defcustom elel-major-mode-alist
(list (cons (rx-to-string (list 'seq ".org" 'eos) t) 'org-mode)
(cons (rx-to-string (list 'seq 'any) t) 'text-mode))
"Alist of (REGEXP . MODE): the major mode for showing a note.
The first REGEXP that matches the file name of the note decides."
:type '(alist :key-type regexp :value-type function))
(defcustom elel-summary-window-height 0.3
"The fraction of the height that the summary window keeps.
It applies when an article window is made below the summary."
:type 'number)
(defcustom elel-article-keep-summary t
"Non-nil to show the article below the summary.
If nil, the article replaces the summary window; press \\`h' in the
article to go back to the summary."
:type 'boolean)
(defcustom elel-thread-root ""
"What to draw before the title of a note without a parent."
:type 'string)
(defcustom elel-thread-false-root "─┬> "
"What to draw before a note whose parent is not in the summary."
:type 'string)
(defcustom elel-thread-indent " "
"What to draw under a note that has no younger siblings."
:type 'string)
(defcustom elel-thread-vertical "│"
"What to draw under a note that has younger siblings."
:type 'string)
(defcustom elel-thread-leaf-with-other "├─> "
"What to draw before a note that has younger siblings."
:type 'string)
(defcustom elel-thread-single-leaf "└─> "
"What to draw before a note that is the last child of its parent."
:type 'string)
;;; Faces
(defface elel-title
'((t :weight bold))
"Face of note titles.")
(defface elel-mark
'((t :inherit font-lock-warning-face :weight bold))
"Face of the mark column of the summary buffer."
:group 'elel)
(defcustom elel-suggest-after-capture t
"Non-nil means a new note is followed by suggestions of links and tags."
:type 'boolean
:group 'elel)
(defcustom elel-suggest-limit 15
"How many notes to suggest."
:type 'integer
:group 'elel)
(defface elel-date
'((t :inherit shadow))
"Face of dates.")
(defface elel-tag
'((t :inherit font-lock-type-face))
"Face of tags.")
(defface elel-hit
'((t :inherit highlight))
"Face of the words that matched a search.")
(defface elel-thread
'((t :inherit shadow))
"Face of the lines that draw the threads.")
(defface elel-heading
'((t :inherit font-lock-keyword-face :weight bold))
"Face of section headings.")
;;; Talking to the engine
(defun elel--environment ()
"The process environment for running the engine."
(append
(list (concat "ELEL_ROOT=" (expand-file-name elel-root)))
(cond
(elel-index-directory
(list (concat "ELEL_INDEX=" (expand-file-name elel-index-directory)))))
process-environment))
(defun elel--parse-lines ()
"Parse the JSON objects, one per line, in the current buffer."
(goto-char (point-min))
(let (objects)
(while (not (eobp))
(cond
((eq (char-after) ?{)
(push (json-parse-buffer :object-type 'alist
:array-type 'list
:null-object nil
:false-object nil)
objects))
((forward-line 1))))
(nreverse objects)))
(defun elel--call (&rest args)
"Run the engine with ARGS. Return the list of objects it prints."
(let ((process-environment (elel--environment))
(coding-system-for-read 'utf-8)
(coding-system-for-write 'utf-8))
(with-temp-buffer
(let ((status (apply #'call-process elel-program nil t nil args)))
(cond
((eq status 0) (elel--parse-lines))
((user-error "elel: %s" (string-trim (buffer-string)))))))))
(defvar elel--index-process nil
"The running asynchronous index process, if any.")
(defvar elel--index-pending nil
"Non-nil if another index was requested while one was running.")
(defun elel-index ()
"Update the index now, and wait for it."
(interactive)
(let ((r (car (elel--call "index"))))
(message "elel: %d files, %d notes (%d changed, %d removed)"
(alist-get 'files r) (alist-get 'notes r)
(alist-get 'changed r) (alist-get 'removed r))
r))
(defvar elel--index-callbacks nil
"Functions to call once the running index has finished.")
(defun elel-index-async ()
"Update the index in the background."
(interactive)
(cond
((process-live-p elel--index-process)
(setq elel--index-pending t))
(t
(let ((process-environment (elel--environment))
(buffer (generate-new-buffer " *elel-index*")))
(setq elel--index-pending nil)
(setq elel--index-process
(make-process
:name "elel-index"
:buffer buffer
:command (list elel-program "index")
:connection-type 'pipe
:noquery t
:sentinel
(lambda (process _event)
(cond
((not (process-live-p process))
(let ((ok (eq (process-exit-status process) 0))
(out (with-current-buffer (process-buffer process)
(string-trim (buffer-string)))))
(kill-buffer (process-buffer process))
(cond
((not ok)
(setq elel--index-callbacks nil)
(message "elel: indexing failed: %s" out))
(elel--index-pending (elel-index-async))
(t (elel--run-index-callbacks)))))))))))))
(defun elel--run-index-callbacks ()
"Call and forget the functions waiting for the index."
(let ((callbacks (nreverse elel--index-callbacks)))
(setq elel--index-callbacks nil)
(dolist (f callbacks)
(condition-case err
(funcall f)
(error (message "elel: %s" (error-message-string err)))))))
(defun elel--maybe-index ()
"Index after saving a file under `elel-root'."
(cond
((and elel-auto-index
buffer-file-name
(string-prefix-p
(file-name-as-directory (expand-file-name elel-root))
(expand-file-name buffer-file-name)))
(elel-index-async))))
(add-hook 'after-save-hook #'elel--maybe-index)
;;; Rendering helpers
(defun elel--field (note key)
"The value of KEY in NOTE."
(alist-get key note))
(defun elel--short-date (note)
"The date of NOTE, cut to ten characters."
(let ((d (elel--field note 'date)))
(cond
((stringp d) (substring d 0 (min 10 (length d))))
((make-string 10 ?\s)))))
(defun elel--tags (note)
"The tags of NOTE as a propertized string."
(let ((tags (elel--field note 'tags)))
(cond
(tags (propertize (concat ":" (mapconcat #'identity tags ":") ":")
'face 'elel-tag))
(""))))
(defun elel--fontify-snippet (string)
"Turn the highlight markers of the engine in STRING into faces."
(with-temp-buffer
(insert string)
(goto-char (point-min))
(while (search-forward (string #xe000) nil t)
(let ((beg (match-beginning 0)))
(delete-region beg (point))
(cond
((search-forward (string #xe001) nil t)
(let ((end (match-beginning 0)))
(delete-region end (point))
(put-text-property beg end 'face 'elel-hit))))))
(buffer-string)))
;;; Asking the engine for notes
(defun elel--get (id)
"The engine's answer for the note ID.
If the files moved since the last index, update the index and retry."
(condition-case err
(car (elel--call "get" id))
(user-error
(cond
((string-match-p "index out of date" (error-message-string err))
(elel-index)
(car (elel--call "get" id)))
((signal (car err) (cdr err)))))))
(defun elel--quote-id (id)
"ID, quoted if needed to be the value of a filter in a query."
(cond
((string-match-p "[ \t\"]" id) (concat "\"" id "\""))
(id)))
(defun elel--filter (key id)
"The query term that selects with KEY (such as \"thread\") the note ID."
(concat key ":" (elel--quote-id id)))
(defcustom elel-hybrid-search t
"Non-nil means a search also ranks by meaning.
The words of the query are embedded and the result is fused with the
text search. If Ollama is not running, only the text search is used."
:type 'boolean
:group 'elel)
(defun elel--search (query &optional limit)
"The notes matching QUERY, at most LIMIT (default: all)."
(apply #'elel--call "search" "-n" (number-to-string (or limit 1000000))
(append (and elel-hybrid-search
(not (string-empty-p (string-trim (or query ""))))
(list "--hybrid"))
(list "--" (or query "")))))
(defun elel--counts (queries)
"The number of notes matching each of QUERIES."
(mapcar (lambda (o) (alist-get 'count o))
(apply #'elel--call "count" "--" queries)))
;;; Threads
(defun elel--thread (notes)
"Order NOTES so that each child follows its parent.
Return a list of (NOTE PREFIX CONTINUATION), where PREFIX is the
drawing in front of the title (see `elel-thread-root' and friends) and
CONTINUATION is what to put in front of a further line of the note. A
note whose parent is not among NOTES is a root."
(let ((ids (mapcar (lambda (n) (elel--field n 'id)) notes))
(kids (make-hash-table :test 'equal))
(seen (make-hash-table :test 'equal))
roots out)
(dolist (n notes)
(let ((p (elel--field n 'parent)))
(cond
((and p (member p ids) (not (equal p (elel--field n 'id))))
(puthash p (cons n (gethash p kids)) kids))
((push n roots)))))
(cl-labels
((walk (n depth ancestors lastp)
(let ((id (elel--field n 'id)))
(cond
((gethash id seen))
(t
(puthash id t seen)
(let* ((leaf (cond
((= depth 0)
(cond
((elel--field n 'parent) elel-thread-false-root)
(elel-thread-root)))
(lastp elel-thread-single-leaf)
(elel-thread-leaf-with-other)))
(kids-of (cl-remove-if
(lambda (c) (gethash (elel--field c 'id) seen))
(reverse (gethash id kids))))
(below (cond
((= depth 0) "")
(t (concat ancestors
(cond
(lastp elel-thread-indent)
(elel-thread-vertical)))))))
(push (list n
(concat (cond ((= depth 0) "") (ancestors)) leaf)
(concat (cond ((= depth 0) "") (ancestors))
(make-string (string-width leaf) ?\s)))
out)
(let ((rest kids-of))
(while rest
(walk (car rest) (1+ depth) below (null (cdr rest)))
(setq rest (cdr rest))))))))))
(dolist (r (nreverse roots)) (walk r 0 "" t))
;; Notes caught in a cycle of parents have no root.
(dolist (n notes) (walk n 0 "" t)))
(nreverse out)))
;;; The summary buffer
(defconst elel--summary-buffer-name "*elel summary*")
(defconst elel--article-buffer-name "*elel article*")
(defvar-local elel-summary-title nil
"The title of this summary buffer.")
(defvar-local elel-summary-query nil
"The query of this summary buffer, or nil if it has a function.")
(defvar-local elel-summary-limit nil
"The maximum number of notes of the query, or nil.")
(defvar-local elel-summary-function nil
"A function that returns the notes of this summary, instead of a query.")
(defvar-local elel-summary-extra nil
"Queries whose notes are added to this summary (see `elel-summary-refer-thread').")
(defvar-local elel-summary-threaded t
"Non-nil if the notes are threaded by their parents.")
(defvar-local elel-summary-show-snippets nil
"Non-nil if snippets are shown below the notes.")
(defvar-local elel-summary-marks nil
"Alist of (ID . CHAR) for the marked notes: ?+ is liked, ?- is disliked.")
(defvar-local elel-summary-insert-marker nil
"Where `elel-summary-insert-link' puts the link, a marker, or nil.")
(defvar elel-search-history nil
"History of search queries.")
(defvar elel-summary-mode-map (make-sparse-keymap)
"Keymap of `elel-summary-mode'.")
;; Filled in separately, so that loading this file again updates the keys.
(let ((map elel-summary-mode-map))
(set-keymap-parent map special-mode-map)
(define-key map (vector ?\r) #'elel-summary-open)
(define-key map (vector ?\s) #'elel-summary-scroll-up)
(define-key map (vector ?\d) #'elel-summary-scroll-down)
(define-key map (vector ?n) #'elel-summary-next)
(define-key map (vector ?p) #'elel-summary-previous)
(define-key map (vector ?g) #'elel-summary-show-article)
(define-key map (vector ?s) #'elel-summary-toggle-snippets)
(define-key map (vector ?/) #'elel-summary-narrow)
(define-key map (vector ?G) #'elel-search)
(define-key map (vector ?a) #'elel-summary-refer-thread)
(define-key map (vector ?^) #'elel-summary-parent)
(define-key map (vector ?c) #'elel-summary-children)
(define-key map (vector ?o) #'elel-summary-outlinks)
(define-key map (vector ?b) #'elel-summary-backlinks)
(define-key map (vector ?H) #'elel-summary-hood)
(define-key map (vector ?e) #'elel-summary-edit)
(define-key map (vector ?r) #'elel-summary-new-child)
(define-key map (vector ?N) #'elel-new-note)
(define-key map (vector ?#) #'elel-summary-mark-like)
(define-key map (vector ?-) #'elel-summary-mark-unlike)
(define-key map (vector ?R) #'elel-summary-related)
(define-key map (vector ?S) #'elel-suggest)
(define-key map (vector ?i) #'elel-summary-insert-link)
(define-key map (vector ?=) #'elel-summary-expand-window)
(define-key map (vector ?A) #'elel-summary-select-article-buffer)
(define-key map (vector ?q) #'elel-summary-quit))
(define-derived-mode elel-summary-mode special-mode "elel-summary"
"Major mode for a list of notes, like a Gnus summary buffer.
\\{elel-summary-mode-map}"
(setq truncate-lines t)
(hl-line-mode 1)
(setq-local revert-buffer-function
(lambda (&rest _) (elel-summary-refresh))))
(defun elel--id-at-point ()
"The ID of the note at point, in a summary buffer."
(or (get-text-property (point) 'elel-id)
(user-error "No note here")))
(defun elel--note-at-point ()
"The note at point, in a summary buffer."
(or (get-text-property (point) 'elel-note)
(user-error "No note here")))
(defun elel--insert-note-line (entry show-snippets)
"Insert the lines of ENTRY, an element of the value of `elel--thread'."
(let* ((note (nth 0 entry))
(prefix (nth 1 entry))
(continuation (nth 2 entry))
(beg (point))
(rel (elel--field note 'rel))
(score (elel--field note 'score))
(back (elel--field note 'backlinks))
(snippet (elel--field note 'snippet)))
(insert
(propertize (string (or (alist-get (elel--field note 'id) elel-summary-marks
nil nil #'equal)
?\s))
'face 'elel-mark)
(propertize (elel--short-date note) 'face 'elel-date)
" "
(cond
(rel (propertize (format "%-8s " rel) 'face 'elel-date))
(""))
(propertize prefix 'face 'elel-thread)
(propertize (elel--field note 'title) 'face 'elel-title)
" " (elel--tags note)
(cond
((and (numberp back) (> back 0))
(propertize (format " ←%d" back) 'face 'elel-date))
(""))
(cond
(score (propertize (format " %.2f" score) 'face 'elel-date))
(""))
"\n")
(cond
((and show-snippets snippet)
(insert (make-string 13 ?\s)
(propertize continuation 'face 'elel-thread)
(elel--fontify-snippet snippet) "\n")))
(put-text-property beg (point) 'elel-id (elel--field note 'id))
(put-text-property beg (point) 'elel-note note)))
(defun elel--summary-notes ()
"The notes of the current summary buffer, asked of the engine."
(let ((notes (cond
(elel-summary-function (funcall elel-summary-function))
(t (elel--search elel-summary-query elel-summary-limit)))))
(dolist (q elel-summary-extra)
(dolist (n (elel--search q))
(unless (cl-find (elel--field n 'id) notes
:key (lambda (x) (elel--field x 'id))
:test #'equal)
(setq notes (append notes (list n))))))
notes))
(defun elel--render-summary (notes)
"Show NOTES in the current summary buffer."
(let ((inhibit-read-only t)
(id (get-text-property (point) 'elel-id))
(line (line-number-at-pos)))
(erase-buffer)
(insert (propertize (or elel-summary-title "Notes") 'face 'elel-heading)
(format " (%d)\n\n" (length notes)))
(dolist (entry (cond
(elel-summary-threaded (elel--thread notes))
((mapcar (lambda (n) (list n "" "")) notes))))
(elel--insert-note-line entry elel-summary-show-snippets))
(goto-char (point-min))
(cond
((and id (elel--goto-note id)))
((forward-line (max 2 (1- line)))))))
(defun elel--goto-note (id)
"Move to the line of the note ID in this summary buffer.
Return non-nil if it is there."
(let ((pos (point-min))
found)
(while (and (not found)
(setq pos (next-single-property-change pos 'elel-id)))
(cond
((equal (get-text-property pos 'elel-id) id)
(goto-char pos)
(setq found t))))
found))
(defun elel--summary-buffer ()
"The summary buffer, or nil."
(get-buffer elel--summary-buffer-name))
(cl-defun elel--show-summary (title &key query limit function (threaded t) quiet)
"Show a summary buffer named TITLE and select its window.
The notes are those of the QUERY (at most LIMIT of them), or the value
of FUNCTION. THREADED says whether to thread them. With QUIET, only
display the buffer, and leave the selection alone."
(let ((buffer (get-buffer-create elel--summary-buffer-name)))
(with-current-buffer buffer
(elel-summary-mode)
(let ((inhibit-read-only t)) (erase-buffer))
(setq elel-summary-title title)
(setq elel-summary-query query)
(setq elel-summary-limit limit)
(setq elel-summary-function function)
(setq elel-summary-threaded threaded)
(let ((notes (elel--summary-notes)))
(setq elel-summary-show-snippets
(and (seq-some (lambda (n) (elel--field n 'snippet)) notes) t))
(elel--render-summary notes)))
(let ((window (get-buffer-window buffer)))
(cond
(quiet (display-buffer buffer))
(window (select-window window))
(t (switch-to-buffer buffer))))
buffer))
(defun elel-summary-refresh ()
"Ask the engine again and redraw."
(interactive)
(elel--render-summary (elel--summary-notes)))
(defun elel-summary-toggle-snippets ()
"Show or hide the snippets."
(interactive)
(setq elel-summary-show-snippets (not elel-summary-show-snippets))
(elel-summary-refresh))
(defun elel-summary-show-article ()
"Show the note at point again, read fresh from its file, like Gnus's \`g'.
The summary stays as it is; search again (\`G') or use `revert-buffer' to
refresh it."
(interactive)
(elel--show-article (elel--id-at-point)))
(defun elel-summary-open ()
"Show the note at point in the article window."
(interactive)
(elel--show-article (elel--id-at-point)))
(defun elel-summary-expand-window (&optional arg)
"Make the summary window take up the whole frame, like Gnus's `='.
This works from the article window too: the summary is what expands.
With a prefix argument ARG, go back to the summary and article layout,
showing the note at point (or else the note last shown)."
(interactive "P")
(let* ((summary (or (elel--summary-buffer) (user-error "No summary")))
(article (get-buffer elel--article-buffer-name))
(id (or (cond
((eq (current-buffer) summary)
(get-text-property (point) 'elel-id))
((bound-and-true-p elel-article-mode) elel-article-id))
(and article (buffer-local-value 'elel-article-id article))))
(window (get-buffer-window summary)))
(cond
(window (select-window window))
((switch-to-buffer summary)))
(delete-other-windows)
(cond
((not arg))
(id (elel--show-article id))
((message "No note to show")))))
(defun elel-summary-select-article-buffer ()
"Select the article window, like `gnus-summary-select-article-buffer'.
If the article is not shown (say, after `elel-summary-expand-window'),
show it again first. If there is no article yet, show the note at point."
(interactive)
(let ((buffer (get-buffer elel--article-buffer-name))
(window (elel--article-visible-window)))
(cond
((null buffer) (elel--show-article (elel--id-at-point) nil t))
(window (select-window window))
(t
(let ((new (elel--article-window)))
(set-window-buffer new buffer)
(select-window new))))))
(defun elel--article-visible-window ()
"The window that shows the article buffer, or nil."
(get-buffer-window elel--article-buffer-name))
(defun elel-summary-scroll-up ()
"Scroll the article; at its end, show the next note."
(interactive)
(let ((window (elel--article-visible-window)))
(cond
((null window) (elel-summary-open))
(t
(condition-case nil
(with-selected-window window (scroll-up-command))
(end-of-buffer (elel-summary-next)))))))
(defun elel-summary-scroll-down ()
"Scroll the article backward."
(interactive)
(let ((window (elel--article-visible-window)))
(cond
((null window) (user-error "No article"))
((condition-case nil
(with-selected-window window (scroll-down-command))
(beginning-of-buffer (message "Beginning of the note")))))))
(defun elel--move-to-note (step)
"Move STEP (1 or -1) notes in this summary buffer. Return non-nil if moved."
(let ((start (point))
found)
(while (and (not found)
(zerop (forward-line step))
(not (eobp)))
(cond
((get-text-property (point) 'elel-id)
(let ((here (get-text-property (point) 'elel-id))
(there (get-text-property start 'elel-id)))
(cond
((not (equal here there)) (setq found t)))))))
(cond
(found
;; Land on the first line of the note.
(beginning-of-line)
(while (and (> (point) (point-min))
(equal (get-text-property (1- (point)) 'elel-id)
(get-text-property (point) 'elel-id)))
(forward-line -1)))
((goto-char start)))
found))
(defun elel-summary-next ()
"Show the next note."
(interactive)
(cond
((not (get-text-property (point) 'elel-id))
(goto-char (point-min))
(cond ((next-single-property-change (point) 'elel-id)
(goto-char (next-single-property-change (point) 'elel-id))
(elel-summary-open))))
((elel--move-to-note 1) (elel-summary-open))
((message "No more notes"))))
(defun elel-summary-previous ()
"Show the previous note."
(interactive)
(cond
((elel--move-to-note -1) (elel-summary-open))
((message "No previous note"))))
(defun elel-summary-narrow (query)
"Search again, with QUERY, which starts as the current query."
(interactive
(list (read-string "Limit to: "
(cond
(elel-summary-query (concat elel-summary-query " "))
(""))
'elel-search-history)))
(elel--show-summary (format "Search: %s" query) :query query :threaded nil))
;;; Related notes and suggestions (the semantic side)
(defun elel--set-mark (char)
"Toggle the mark CHAR on the note at point, then go to the next note."
(let* ((id (elel--id-at-point))
(note (get-text-property (point) 'elel-note))
(old (alist-get id elel-summary-marks nil nil #'equal)))
(setf (alist-get id elel-summary-marks nil t #'equal)
(cond ((eq old char) nil) (char)))
(let ((inhibit-read-only t))
(save-excursion
(goto-char (line-beginning-position))
(delete-char 1)
(insert (propertize (string (or (alist-get id elel-summary-marks
nil nil #'equal)
?\s))
'face 'elel-mark 'elel-id id 'elel-note note))))
(elel--move-to-note 1)))
(defun elel-summary-mark-like ()
"Mark the note at point as one that the wanted notes resemble."
(interactive)
(elel--set-mark ?+))
(defun elel-summary-mark-unlike ()
"Mark the note at point as one that the wanted notes should not resemble."
(interactive)
(elel--set-mark ?-))
(defun elel--related-query (positive negative)
"The query for the notes like those of IDs POSITIVE and unlike NEGATIVE."
(mapconcat #'identity
(append (mapcar (lambda (id) (format "like:\"%s\"" id)) positive)
(mapcar (lambda (id) (format "-like:\"%s\"" id)) negative))
" "))
(defun elel--related (positive negative)
"Show the notes like those of IDs POSITIVE and unlike NEGATIVE."
(elel--show-summary "Related"
:query (elel--related-query positive negative)
:limit 30 :threaded nil))
(defun elel-summary-related ()
"Show the notes closest in meaning to the marked notes.
Notes marked with \\`#' count for, notes marked with \\`-' count against.
If none is marked, use the note at point."
(interactive)
(let (positive negative)
(dolist (m elel-summary-marks)
(cond
((eq (cdr m) ?+) (push (car m) positive))
((eq (cdr m) ?-) (push (car m) negative))))
(cond
((null positive) (setq positive (list (elel--id-at-point)))))
(elel--related positive negative)))
(defun elel-article-related ()
"Show the notes closest in meaning to this note."
(interactive)
(elel--related (list elel-article-id) nil))
(defun elel--suggested-tags (id)
"The tags that fit the note ID best and that it does not have yet."
(let (tags)
(dolist (x (elel--call "tags" "--like" id))
(cond
((and (not (alist-get 'has x)) (< (length tags) 5))
(push (alist-get 'tag x) tags))))
(nreverse tags)))
;;;###autoload
(defun elel-suggest (&optional id marker quiet)
"Show the notes that a note ID could link to, and tags that fit it.
The notes it already has relations with are left out. If MARKER is a
marker, then \\`i' in the summary inserts a link at that place. With
QUIET, do not select the summary window."
(interactive)
(let* ((id (or id (elel--note-id-here) (user-error "No note here")))
(data (elel--get id))
(excluded (cons id
(mapcar (lambda (n) (elel--field n 'id))
(append (list (alist-get 'parent data))
(alist-get 'children data)
(alist-get 'links data)))))
(tags (elel--suggested-tags id))
(title (format "Suggestions for %s%s"
(elel--field (alist-get 'note data) 'title)
(cond (tags (concat " tags: " (string-join tags " ")))
(""))))
(buffer
(elel--show-summary
title
:function (lambda ()
(cl-remove-if
(lambda (n) (member (elel--field n 'id) excluded))
(elel--search (format "like:\"%s\"" id)
(+ elel-suggest-limit
(length excluded)))))
:threaded nil
:quiet quiet)))
(with-current-buffer buffer
(setq elel-summary-insert-marker (and (markerp marker) marker)))))
(defun elel-summary-insert-link ()
"Insert a link to the note at point where `elel-suggest' was asked for."
(interactive)
(let ((note (elel--note-at-point))
(marker elel-summary-insert-marker))
(cond
((not (and marker (marker-buffer marker)))
(user-error "No place to insert a link; use \\`S' from a capture"))
(t
(with-current-buffer (marker-buffer marker)
(save-excursion
(goto-char marker)
(cond
((and (not (bolp)) (not (memq (char-before) (list ?\s ?\t))))
(insert " ")))
(insert (elel--link-string (elel--field note 'id)
(elel--field note 'title))
" ")
(set-marker marker (point))))
(message "elel: linked %s" (elel--field note 'title))))))
(defun elel-summary-refer-thread (&optional id)
"Add the whole thread of the note ID (default: at point) to this summary."
(interactive)
(let ((id (or id (elel--id-at-point))))
(cl-pushnew (elel--filter "thread" id) elel-summary-extra :test #'equal)
(setq elel-summary-threaded t)
(let ((inhibit-read-only t))
(elel--render-summary (elel--summary-notes)))
(elel--goto-note id)))
(defun elel--summary-query (title query)
"Show a summary of the notes matching QUERY, named TITLE."
(elel--show-summary title :query query :threaded t))
(defun elel-summary-parent ()
"Show the parent of the note at point."
(interactive)
(elel--show-parent (elel--note-at-point)))
(defun elel-summary-children ()
"Summarize the children of the note at point."
(interactive)
(elel--children (elel--id-at-point)))
(defun elel-summary-outlinks ()
"Summarize the notes that the note at point links to."
(interactive)
(elel--outlinks (elel--id-at-point)))
(defun elel-summary-backlinks ()
"Summarize the notes that link to the note at point."
(interactive)
(elel--backlinks (elel--id-at-point)))
(defun elel-summary-hood ()
"Summarize the neighbourhood of the note at point."
(interactive)
(elel-hood (elel--id-at-point) (prefix-numeric-value current-prefix-arg)))
(defun elel-summary-edit ()
"Edit the file of the note at point."
(interactive)
(elel-edit-note (elel--id-at-point)))
(defun elel-summary-new-child ()
"Write a new note whose parent is the note at point."
(interactive)
(elel-new-note (read-string "Title: ") (elel--id-at-point)))
(defun elel-summary-quit ()
"Leave the summary, and close the article window.
The summary and article buffers are killed, as in Gnus, so that quitting
the views buffer afterwards does not bring the summary back."
(interactive)
(let ((window (elel--article-visible-window))
(summary (current-buffer))
(article (get-buffer elel--article-buffer-name))
(views (get-buffer "*elel*")))
(cond
((and window (cdr (window-list nil 'nomini))) (delete-window window)))
(cond
(views (switch-to-buffer views))
((quit-window)))
(cond ((buffer-live-p article) (kill-buffer article)))
(cond ((buffer-live-p summary) (kill-buffer summary)))))
;;; The same queries, from anywhere
(defun elel--children (id)
"Summarize the children of the note ID."
(elel--summary-query (format "Children of %s" id)
(elel--filter "parent" id)))
(defun elel--outlinks (id)
"Summarize the notes that the note ID links to."
(elel--summary-query (format "Links of %s" id) (elel--filter "from" id)))
(defun elel--backlinks (id)
"Summarize the notes that link to the note ID."
(elel--summary-query (format "Backlinks of %s" id) (elel--filter "to" id)))
(defun elel--show-parent (note)
"Show the parent of NOTE in the article window."
(let ((parent (elel--field note 'parent)))
(cond
(parent (elel--show-article parent t))
((user-error "This note has no parent")))))
;;;###autoload
(defun elel-search (query)
"Search the notes for QUERY and show the results.
QUERY may hold filters such as tag:X or date:2025..; see the README."
(interactive (list (read-string "Search: " nil 'elel-search-history)))
(elel--show-summary (format "Search: %s" query)
:query query :threaded nil))
(defun elel--hood-notes (id hops)
"The notes within HOPS steps of ID, with the center first."
(let* ((objects (elel--call "hood" id "--hops" (number-to-string hops)))
(center (alist-get 'center (car objects))))
(cons (cons (cons 'rel "this") center) (cdr objects))))
;;;###autoload
(defun elel-hood (id &optional hops)
"Show the notes around ID, within HOPS steps (default 1)."
(interactive (list (cond
((bound-and-true-p elel-article-mode) elel-article-id)
((elel--id-at-point)))
(prefix-numeric-value current-prefix-arg)))
(let ((hops (or hops 1)))
(elel--show-summary
(format "Neighbourhood of %s" id)
:function (lambda () (elel--hood-notes id hops))
:threaded nil)))
;;; The article buffer
(defvar-local elel-article-id nil
"The ID of the note shown in this article buffer.")
(defvar-local elel-article-note nil
"The note shown in this article buffer, as the engine reported it.")
(defvar elel--history nil
"The IDs of the notes visited before, newest first.")
(defvar elel-article-mode-map (make-sparse-keymap)
"Keymap of `elel-article-mode'.")
;; Filled in separately, so that loading this file again updates the keys.
(let ((map elel-article-mode-map))
(define-key map (vector ?\s) #'elel-article-scroll-up)
(define-key map (vector ?j) #'elel-article-scroll-up)
(define-key map (vector ?\d) #'elel-article-scroll-down)
(define-key map (vector ?k) #'elel-article-scroll-down)
(define-key map (vector ?n) #'elel-article-next)
(define-key map (vector ?p) #'elel-article-previous)
(define-key map (vector ?\t) #'elel-article-next-link)
(define-key map (vector 'backtab) #'elel-article-previous-link)
(define-key map (vector ?\r) #'elel-article-follow)
(define-key map (vector ?l) #'elel-article-back)
(define-key map (vector ?^) #'elel-article-parent)
(define-key map (vector ?c) #'elel-article-children)
(define-key map (vector ?o) #'elel-article-outlinks)
(define-key map (vector ?b) #'elel-article-backlinks)
(define-key map (vector ?H) #'elel-hood)
(define-key map (vector ?a) #'elel-article-refer-thread)
(define-key map (vector ?=) #'elel-summary-expand-window)
(define-key map (vector ?R) #'elel-article-related)
(define-key map (vector ?S) #'elel-suggest)
(define-key map (vector ?h) #'elel-article-goto-summary)
(define-key map (vector ?q) #'elel-article-quit)
(define-key map (vector ?e) #'elel-article-edit)
(define-key map (vector ?r) #'elel-article-new-child)
(define-key map (vector ?g) #'elel-article-refresh)
(define-key map (vector ?/) #'elel-search)
(define-key map (vector ?N) #'elel-new-note))
(define-minor-mode elel-article-mode
"Minor mode for reading a note, like `view-mode' but aware of the summary.
The major mode of the buffer is chosen by the file of the note, through
`elel-major-mode-alist'.
\\{elel-article-mode-map}"
:lighter " elel"
:keymap elel-article-mode-map
(setq truncate-lines nil)
(setq buffer-read-only elel-article-mode))
(defun elel--major-mode (path)
"The major mode in which to show a note of the file PATH."
(let ((mode (assoc-default path elel-major-mode-alist
#'string-match-p 'text-mode)))
(cond
((fboundp mode) mode)
('text-mode))))
(defun elel--article-window ()
"The window in which to show the article.
It is the window that shows the article already. Failing that, it is
a new window below the summary window if `elel-article-keep-summary';
failing that, the selected window."
(let ((summary (get-buffer-window elel--summary-buffer-name)))
(cond
((elel--article-visible-window))
((and elel-article-keep-summary summary
(ignore-errors
(let* ((total (window-total-height summary))
(new (split-window summary nil 'below))
(want (round (* elel-summary-window-height total))))
(ignore-errors
(window-resize summary (- want (window-total-height summary))))
new))))
((selected-window)))))
(defun elel--hide-drawers ()
"Fold the property drawers of the current org buffer."
(cond
((fboundp 'org-fold-hide-drawer-all) (org-fold-hide-drawer-all))
((fboundp 'org-hide-drawer-all) (org-hide-drawer-all))))
(defun elel--show-article (id &optional history select)
"Show the note ID in the article window.
With HISTORY, remember the note shown before. With SELECT, select
the article window. The note is shown as it is in its file, in the
major mode chosen by `elel-major-mode-alist'."
(let* ((data (elel--get id))
(note (alist-get 'note data))
(text (or (alist-get 'raw data) (alist-get 'body data) ""))
(mode (elel--major-mode (elel--field note 'path)))
(buffer (get-buffer-create elel--article-buffer-name))
(previous (buffer-local-value 'elel-article-id buffer)))
(cond
((and history previous (not (equal previous id)))
(push previous elel--history)))
(with-current-buffer buffer
(let ((inhibit-read-only t))
(kill-all-local-variables t)
(erase-buffer)
(insert text)
(cond
((not (bolp)) (insert "\n")))
(funcall mode)
(setq elel-article-id id)
(setq elel-article-note note)
(elel-article-mode 1)
(cond
((derived-mode-p 'org-mode) (elel--hide-drawers))
;; Without org, make the links buttons.
((elel--buttonize-body (point-min) (point-max))))
(goto-char (point-min))
(set-buffer-modified-p nil)))
(cond
((alist-get 'stale data)
(message "elel: the file changed since the last index; update the index")))
(let ((window (elel--article-window)))
(set-window-buffer window buffer)
(set-window-point window (point-min))
(set-window-start window (point-min))
(cond (select (select-window window))))
buffer))
;;;###autoload
(defun elel-open-note (id)
"Show the note with ID in the article window, and select that window."
(interactive "sNote ID: ")
(elel--show-article id (bound-and-true-p elel-article-mode) t))
(defun elel--with-summary (function)
"Call FUNCTION in the summary window, or else in the summary buffer."
(let ((buffer (elel--summary-buffer)))
(cond
((null buffer) (user-error "No summary; search first"))
((get-buffer-window buffer)
(with-selected-window (get-buffer-window buffer)
(funcall function)))
((with-current-buffer buffer (funcall function))))))
(defun elel-article-scroll-up ()
"Scroll forward; at the end of the note, go to the next note."
(interactive)
(condition-case nil
(scroll-up-command)
(end-of-buffer (elel-article-next))))
(defun elel-article-scroll-down ()
"Scroll backward."
(interactive)
(condition-case nil
(scroll-down-command)
(beginning-of-buffer (message "Beginning of the note"))))
(defun elel-article-next ()
"Show the next note of the summary."
(interactive)
(elel--with-summary #'elel-summary-next))
(defun elel-article-previous ()
"Show the previous note of the summary."
(interactive)
(elel--with-summary #'elel-summary-previous))
(defun elel-article-next-link ()
"Move to the next link."
(interactive)
(cond
((derived-mode-p 'org-mode) (org-next-link))
((forward-button 1))))
(defun elel-article-previous-link ()
"Move to the previous link."
(interactive)
(cond
((derived-mode-p 'org-mode) (org-previous-link))
((backward-button 1))))
(defun elel-article-follow ()
"Follow the link at point, in the article window."
(interactive)
(let ((id (elel--link-at-point)))
(cond
(id (elel--show-article id t))
((button-at (point)) (push-button))
((derived-mode-p 'org-mode) (call-interactively #'org-open-at-point))
((user-error "No link here")))))
(defun elel-article-back ()
"Go back to the note shown before."
(interactive)
(cond
(elel--history (elel--show-article (pop elel--history)))
((user-error "No previous note"))))
(defun elel-article-parent ()
"Show the parent of this note."
(interactive)
(elel--show-parent elel-article-note))
(defun elel-article-children ()
"Summarize the children of this note."
(interactive)
(elel--children elel-article-id))
(defun elel-article-outlinks ()
"Summarize the notes this note links to."
(interactive)
(elel--outlinks elel-article-id))
(defun elel-article-backlinks ()
"Summarize the notes that link to this note."
(interactive)
(elel--backlinks elel-article-id))
(defun elel-article-refer-thread ()
"Add the whole thread of this note to the summary."
(interactive)
(let ((id elel-article-id))
(cond
((elel--summary-buffer)
(elel--with-summary (lambda () (elel-summary-refer-thread id))))
((elel--summary-query (format "Thread of %s" id)
(elel--filter "thread" id))))))
(defun elel-article-goto-summary ()
"Select the summary window."
(interactive)
(let ((buffer (elel--summary-buffer)))
(cond
((null buffer) (user-error "No summary"))
((get-buffer-window buffer) (select-window (get-buffer-window buffer)))
((switch-to-buffer buffer)))))
(defun elel-article-quit ()
"Close the article window."
(interactive)
(let ((summary (elel--summary-buffer)))
(cond
((and summary (not (get-buffer-window summary)))
(switch-to-buffer summary))
((cdr (window-list nil 'nomini)) (delete-window))
((bury-buffer)))))
(defun elel-article-edit ()
"Edit the file of this note."
(interactive)
(elel-edit-note elel-article-id))
(defun elel-article-new-child ()
"Write a new note whose parent is this note."
(interactive)
(elel-new-note (read-string "Title: ") elel-article-id))
(defun elel-article-refresh ()
"Read the note again from its file, as if opening it anew.
Point goes back to the start, like `elel-summary-show-article'."
(interactive)
(elel--show-article elel-article-id))
(defconst elel--body-link-regexp
(concat "\\[\\[note:"
;; The kind, for typed links: [[note::KIND:ID]].
"\\(?::\\([[:alnum:]_-]+\\):\\)?"
;; The ID.
"\\([^] \t\n]+\\)\\]"
;; The description, which is for humans.
"\\(?:\\[\\([^]\n]*\\)\\]\\)?"
"\\]")
"Matches a link to a note: [[note:ID][DESCRIPTION]].
Group 1 is the kind (nil if untyped), group 2 the ID and group 3 the
description, if any. The typed form is [[note::KIND:ID][DESCRIPTION]].")
(defun elel--open-button (button)
"Open the note of BUTTON."
(elel--show-article (button-get button 'elel-id) t))
(defun elel--buttonize-body (beg end)
"Replace the links between BEG and END by buttons.
A button shows the description of the link, or the ID if there is none."
(save-excursion
(let ((end (copy-marker end)))
(goto-char beg)
(while (re-search-forward elel--body-link-regexp end t)
(let* ((id (match-string-no-properties 2))
(label (or (match-string-no-properties 3) id))
(start (match-beginning 0)))
(replace-match label t t)
(make-text-button start (+ start (length label))
'elel-id id
'action #'elel--open-button
'follow-link t
'face 'link))))))
(defun elel-edit-note (id)
"Visit the file of the note ID, at the note."
(interactive "sNote ID: ")
(let* ((data (elel--get id))
(note (alist-get 'note data)))
(find-file (elel--field note 'path))
(goto-char (point-min))
(forward-line (1- (elel--field note 'line)))
(cond
((derived-mode-p 'org-mode) (outline-show-entry)))))
;;; The views buffer
(defvar-local elel-views-show-hidden nil
"Non-nil if the views marked :hidden are listed.")
(defvar elel-views-mode-map (make-sparse-keymap)
"Keymap of `elel-views-mode'.")
;; Filled in separately, so that loading this file again updates the keys.
(let ((map elel-views-mode-map))
(set-keymap-parent map special-mode-map)
(define-key map (vector ?\r) #'elel-views-open)
(define-key map (vector ?\s) #'elel-views-open)
(define-key map (vector ?n) #'next-line)
(define-key map (vector ?p) #'previous-line)
(define-key map (vector ?g) #'elel-views-refresh)
(define-key map (vector ?u) #'elel-views-update)
(define-key map (vector ?L) #'elel-views-toggle-hidden)
(define-key map (vector ?/) #'elel-search)
(define-key map (vector ?G) #'elel-search)
(define-key map (vector ?N) #'elel-new-note)
(define-key map (vector ?C) #'elel-check)
(define-key map (vector ?q) #'quit-window))
(define-derived-mode elel-views-mode special-mode "elel-views"
"Major mode for the list of views, like a Gnus group buffer.
\\{elel-views-mode-map}"
(setq truncate-lines t)
(hl-line-mode 1))
(defun elel--view-plist (view)
"The property list of the view VIEW, which is (NAME QUERY . PLIST)."
(cddr view))
(defun elel-views-refresh ()
"Redraw the views buffer."
(interactive)
(let* ((inhibit-read-only t)
(line (line-number-at-pos))
(shown (cl-remove-if
(lambda (v)
(and (plist-get (elel--view-plist v) :hidden)
(not elel-views-show-hidden)))
elel-views))
(counts (and shown (elel--counts (mapcar #'cadr shown)))))
(erase-buffer)
(insert (propertize "elel" 'face 'elel-heading)
" " (abbreviate-file-name (expand-file-name elel-root))
(cond (elel-views-show-hidden " (all views)") (""))
"\n\n")
(cl-mapc
(lambda (v count)
(let* ((beg (point))
(limit (plist-get (elel--view-plist v) :limit))
(count (cond (limit (min count limit)) (count))))
(insert (format "%6d %s%s\n" count (car v)
(cond
((plist-get (elel--view-plist v) :hidden)
(propertize " (hidden)" 'face 'elel-date))
(""))))
(put-text-property beg (point) 'elel-view v)))
shown counts)
(goto-char (point-min))
(forward-line (max 2 (1- line)))))
(defun elel-views-toggle-hidden ()
"List the hidden views, or hide them again."
(interactive)
(setq elel-views-show-hidden (not elel-views-show-hidden))
(elel-views-refresh))
(defun elel-views-update ()
"Update the index, then redraw."
(interactive)
(elel-index)
(elel-views-refresh))
(defun elel-views-open ()
"Open the view at point."
(interactive)
(let ((v (get-text-property (point) 'elel-view)))
(cond
((null v) (user-error "No view here"))
(t
(elel--show-summary (car v)
:query (cadr v)
:limit (plist-get (elel--view-plist v) :limit)
:threaded t)))))
;;;###autoload
(defun elel ()
"Show the views buffer."
(interactive)
(let ((buffer (get-buffer-create "*elel*")))
(with-current-buffer buffer
(elel-views-mode)
(condition-case err
(elel-views-refresh)
(user-error
(cond
;; The first time, there is no index yet: make one.
((string-match-p "no index yet" (error-message-string err))
(elel-index)
(elel-views-refresh))
((signal (car err) (cdr err)))))))
(switch-to-buffer buffer)))
;;; Writing notes
(defun elel-generate-id ()
"Make an ID that sorts by time, such as 20261117T143005-7f3a."
(format "%s-%04x" (format-time-string "%Y%m%dT%H%M%S") (random #x10000)))
(defun elel--now (&optional time)
"TIME (default: now) in ISO 8601, with a colon in the zone."
(let ((s (format-time-string "%Y-%m-%dT%H:%M:%S%z" time)))
(concat (substring s 0 -2) ":" (substring s -2))))
(defun elel--context ()
"Where the user is: the file of the current buffer, if outside the notes."
(cond
((and buffer-file-name
(not (string-prefix-p
(file-name-as-directory (expand-file-name elel-root))
(expand-file-name buffer-file-name))))
(abbreviate-file-name buffer-file-name))))
(defun elel--skeleton (format title id parent context)
"The text of a new note in FORMAT (\"org\" or \"txt\")."
(let ((date (elel--now)))
(cond
((string= format "org")
(concat "* " title "\n:PROPERTIES:\n"
":ID: " id "\n"
":DATE: " date "\n"
(and parent (concat ":PARENT: " parent "\n"))
(and context (concat ":CONTEXT: " context "\n"))
":END:\n"))
((concat "ID: " id "\n"
"Title: " title "\n"
"Date: " date "\n"
(and parent (concat "Parent: " parent "\n"))
(and context (concat "Context: " context "\n"))
"\n")))))
(defvar elel-capture-mode-map (make-sparse-keymap)
"Keymap of `elel-capture-mode'.")
;; Filled in separately, so that loading this file again updates the keys.
(let ((map elel-capture-mode-map))
(define-key map (vector 3 3) #'elel-capture-finish))
(define-minor-mode elel-capture-mode
"Minor mode while writing a new note.
\\Type \\[elel-capture-finish] to save the note and update the index."
:lighter " elel"
:keymap elel-capture-mode-map)
(defvar-local elel-capture-id nil
"The ID of the note being written in this buffer.")
(defun elel-capture-finish ()
"Save the new note, update the index, and leave the capture mode.
If `elel-suggest-after-capture' is non-nil, then show suggestions of
links and tags when the index is ready."
(interactive)
(let ((id elel-capture-id)
(marker (point-marker)))
(cond
((and id elel-suggest-after-capture)
(push (lambda () (elel-suggest id marker t)) elel--index-callbacks)
(save-buffer)
(elel-capture-mode -1)
(elel-index-async)
(message "elel: saved; indexing, then suggestions"))
(t
(save-buffer)
(elel-capture-mode -1)
(message "elel: saved; indexing")))))
;;;###autoload
(defun elel-new-note (title &optional parent)
"Start a new note with TITLE, as a child of PARENT if given.
The note is appended to `elel-capture-file'."
(interactive (list (read-string "Title: ") nil))
(let* ((file (expand-file-name elel-capture-file elel-root))
(format (or (file-name-extension file) "org"))
(context (elel--context))
(id (funcall elel-id-function)))
(make-directory (file-name-directory file) t)
(find-file file)
(goto-char (point-max))
(cond
((and (not (bobp)) (not (bolp))) (insert "\n")))
(cond
((> (buffer-size) 0)
(insert (cond ((string= format "txt") "\n\f\n") ("\n")))))
(insert (elel--skeleton format title id parent context))
(setq elel-capture-id id)
(elel-capture-mode 1)
(message "Write the note, then type C-c C-c")))
;;; Fixing missing IDs
(defconst elel--txt-key-regexp
"^\\(id\\|title\\|date\\|kind\\|tags\\|parent\\|links\\|context\\|summary\\):"
"Matches the first line of the header of a plain text note.")
(defun elel--insert-id (path line id)
"Give the note that starts at LINE of PATH the ID."
(with-current-buffer (find-file-noselect path)
(save-excursion
(goto-char (point-min))
(forward-line (1- line))
(cond
((string= (file-name-extension path) "org")
(forward-line 1)
(while (looking-at "[ \t]*\\(SCHEDULED\\|DEADLINE\\|CLOSED\\):")
(forward-line 1))
(cond
((looking-at "[ \t]*:PROPERTIES:[ \t]*$")
(forward-line 1)
(insert ":ID: " id "\n"))
((insert ":PROPERTIES:\n:ID: " id "\n:END:\n"))))
(t
(while (and (looking-at "[ \t]*$") (not (eobp)))
(forward-line 1))
(let ((case-fold-search t))
(cond
((looking-at elel--txt-key-regexp) (insert "ID: " id "\n"))
((insert "ID: " id "\n\n")))))))
(current-buffer)))
(defun elel-assign-ids ()
"Add an ID to every note that has none."
(interactive)
(elel-index)
(let ((issues (cl-remove-if-not
(lambda (i) (equal (alist-get 'issue i) "missing-id"))
(elel--call "check"))))
(cond
((null issues) (message "elel: every note has an ID"))
((y-or-n-p (format "Add IDs to %d notes? " (length issues)))
;; Work from the end of each file, so that line numbers stay valid.
(let ((sorted (sort (copy-sequence issues)
(lambda (a b)
(let ((pa (alist-get 'path a))
(pb (alist-get 'path b)))
(cond
((string< pa pb) t)
((string= pa pb)
(> (alist-get 'line a) (alist-get 'line b)))))))))
(dolist (i sorted)
(let ((b (get-file-buffer (alist-get 'path i))))
(cond
((and b (buffer-modified-p b))
(user-error "Save %s first" (buffer-name b))))))
(let (buffers)
(dolist (i sorted)
(cl-pushnew (elel--insert-id (alist-get 'path i)
(alist-get 'line i)
(funcall elel-id-function))
buffers))
(dolist (b buffers)
(with-current-buffer b (save-buffer))))
(elel-index))))))
;;; Checking
(defun elel--check-button (button)
"Visit the place of BUTTON."
(find-file (button-get button 'path))
(goto-char (point-min))
(forward-line (1- (button-get button 'line))))
(defun elel-check ()
"Report notes without IDs, duplicate IDs and dangling links."
(interactive)
(let ((issues (elel--call "check"))
(buffer (get-buffer-create "*elel check*")))
(with-current-buffer buffer
(let ((inhibit-read-only t))
(special-mode)
(erase-buffer)
(insert (propertize "elel check" 'face 'elel-heading)
(format " (%d)\n\n" (length issues)))
(dolist (i issues)
(insert (format "%-16s " (alist-get 'issue i)))
(insert-text-button
(or (alist-get 'title i) "(untitled)")
'path (alist-get 'path i)
'line (alist-get 'line i)
'action #'elel--check-button
'follow-link t)
(cond
((alist-get 'target i)
(insert " -> " (alist-get 'target i))))
(insert "\n"))
(goto-char (point-min))))
(switch-to-buffer buffer)))
;;; Links in the note files
;;
;; A link to a note is written [[note:ID][TITLE]] in every format, and
;; [[note::KIND:ID][TITLE]] when it has a type. The title is for the
;; reader; the ID is how the engine finds the note. In org, "note" is a
;; registered link type, so org follows, completes and exports these
;; links itself (see the end of this section).
(defun elel--note-id-here ()
"The ID of the note that the current buffer or point is about, or nil."
(cond
(elel-capture-id)
((derived-mode-p 'elel-summary-mode) (get-text-property (point) 'elel-id))
((bound-and-true-p elel-article-mode) elel-article-id)
((derived-mode-p 'org-mode) (org-entry-get nil "ID" t))))
(defun elel--choose-note ()
"Ask for a note by title, and return it.
The notes closest in meaning to the current note come first."
(let* ((here (ignore-errors (elel--note-id-here)))
(near (and here
(ignore-errors
(elel--search (format "like:\"%s\"" here) 50))))
(notes (append near
(cl-remove-if
(lambda (n)
(cl-find (elel--field n 'id) near
:key (lambda (x) (elel--field x 'id))
:test #'equal))
(elel--search ""))))
(table (mapcar
(lambda (n)
(cons (format "%s (%s)"
(elel--field n 'title)
(string-trim (elel--short-date n)))
n))
notes)))
(cond
(table
(cdr (assoc (completing-read
"Link to: "
(lambda (string pred action)
(cond
((eq action 'metadata)
(list 'metadata
(cons 'display-sort-function #'identity)
(cons 'cycle-sort-function #'identity)))
((complete-with-action action table string pred))))
nil t)
table)))
((user-error "No notes in the index")))))
(defun elel--link-string (id description &optional kind)
"The text of a link to the note ID, with DESCRIPTION and maybe KIND."
(concat "[[note:" (and kind (concat ":" kind ":")) id "]"
(and description (concat "[" description "]"))
"]"))
(defun elel-insert-link (&optional typed)
"Insert a link to a note, chosen by title.
If the region is active, its text becomes the description of the
link; otherwise the title of the note does. With a prefix argument
TYPED, also ask for the type of the link."
(interactive "P")
(let* ((note (elel--choose-note))
(kind (and typed
(let ((k (string-trim (read-string "Type of link: "))))
(and (not (string-empty-p k)) k))))
(description
(cond
((use-region-p)
(prog1 (buffer-substring-no-properties
(region-beginning) (region-end))
(delete-region (region-beginning) (region-end))))
((elel--field note 'title)))))
(insert (elel--link-string (elel--field note 'id) description kind))))
(defun elel--link-at-point ()
"The ID of the note link at point, or nil."
(let ((pos (point))
found)
(save-excursion
(beginning-of-line)
(while (and (not found)
(re-search-forward elel--body-link-regexp
(line-end-position) t))
(cond
((and (<= (match-beginning 0) pos) (<= pos (match-end 0)))
(setq found (match-string-no-properties 2))))))
found))
(defun elel-follow-link ()
"Open the note linked at point.
If there is no note link at point, do what \\`C-c C-o' normally does."
(interactive)
(let ((id (elel--link-at-point)))
(cond
(id (elel-open-note id))
((derived-mode-p 'org-mode) (call-interactively #'org-open-at-point))
((user-error "No note link at point")))))
(defun elel-open-this-note ()
"Open the note around point in the note buffer."
(interactive)
(let ((id (save-excursion
(cond
((string= (file-name-extension (or buffer-file-name "")) "org")
(org-back-to-heading t)
(org-entry-get nil "ID"))
((progn
(cond ((search-backward "\f" nil t) (forward-line 1))
((goto-char (point-min))))
(let ((case-fold-search t))
(re-search-forward "^id:[ \t]*\\(.+\\)$"
(line-end-position 8) t)))
(match-string-no-properties 1))))))
(cond
(id (elel-open-note (string-trim id)))
((user-error "No ID for this note")))))
(defvar elel-link-mode-map (make-sparse-keymap)
"Keymap of `elel-link-mode'.")
;; Filled in separately, so that loading this file again updates the keys.
(let ((map elel-link-mode-map))
(define-key map (vector 3 15) #'elel-follow-link)
(define-key map (vector 3 ?n ?l) #'elel-insert-link)
(define-key map (vector 3 ?n ?o) #'elel-open-this-note))
(define-minor-mode elel-link-mode
"Minor mode for the note files: follow and insert note links.
\\{elel-link-mode-map}"
:lighter " elel"
:keymap elel-link-mode-map)
(defun elel--maybe-link-mode ()
"Turn on `elel-link-mode' in org and text files under `elel-root'."
(cond
((and buffer-file-name
(member (file-name-extension buffer-file-name) (list "org" "txt"))
(string-prefix-p
(file-name-as-directory (expand-file-name elel-root))
(expand-file-name buffer-file-name)))
(elel-link-mode 1))))
(add-hook 'find-file-hook #'elel--maybe-link-mode)
;;;; The org link type
(defun elel--parse-path (path)
"Split the PATH of a note link into (KIND . ID).
KIND is nil for an untyped link, whose path is just the ID."
(cond
((string-match "\\`:\\([[:alnum:]_-]+\\):\\(.+\\)\\'" path)
(cons (match-string 1 path) (match-string 2 path)))
((cons nil path))))
(defun elel--org-follow (path _arg)
"Open the note of the org link whose path is PATH."
(elel-open-note (cdr (elel--parse-path path))))
(defun elel--org-complete (&optional _arg)
"Choose a note by title and return the path of a link to it."
(concat "note:" (elel--field (elel--choose-note) 'id)))
(defun elel--org-description (link desc)
"The description for LINK, if DESC is nil: the title of the note."
(or desc
(ignore-errors
(let* ((id (cdr (elel--parse-path (string-remove-prefix "note:" link))))
(data (car (elel--call "get" id))))
(elel--field (alist-get 'note data) 'title)))))
(defun elel--org-export (path description _backend _info)
"Export the link to PATH as just its DESCRIPTION."
(or description (cdr (elel--parse-path path))))
(with-eval-after-load 'org
(org-link-set-parameters
"note"
:follow #'elel--org-follow
:complete #'elel--org-complete
:insert-description #'elel--org-description
:export #'elel--org-export))
(provide 'elel)
;;; elel.el ends here