aboutsummaryrefslogtreecommitdiff
path: root/consult-hl-todo.el
diff options
context:
space:
mode:
Diffstat (limited to 'consult-hl-todo.el')
-rw-r--r--consult-hl-todo.el388
1 files changed, 388 insertions, 0 deletions
diff --git a/consult-hl-todo.el b/consult-hl-todo.el
new file mode 100644
index 0000000..fd3630f
--- /dev/null
+++ b/consult-hl-todo.el
@@ -0,0 +1,388 @@
1;;; consult-hl-todo.el --- Consult hl-todo keywords in files -*- lexical-binding: t; -*-
2
3;; Copyright (C) 2026 Martin Michalec
4
5;; Author: Martin Michalec <martin@michalec.dev>
6;; Maintainer: Martin Michalec <martin@michalec.dev>
7;; URL: https://git.michalec.dev/consult-hl-todo
8;; Created: 2026
9;; Keywords: convenience, matching, outlining
10
11;; Version: 0.0.0
12;; Package-Requires: ((emacs "29.1")
13;; (compat "31")
14;; (conslut "3")
15;; (hl-todo "3"))
16
17;; SPDX-License-Identifier: GPL-3.0-or-later
18
19;; This program is free software; you can redistribute it and/or modify
20;; it under the terms of the GNU General Public License as published by
21;; the Free Software Foundation, either version 3 of the License, or
22;; (at your option) any later version.
23
24;; This program is distributed in the hope that it will be useful,
25;; but WITHOUT ANY WARRANTY; without even the implied warranty of
26;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27;; GNU General Public License for more details.
28
29;; You should have received a copy of the GNU General Public License
30;; along with this program. If not, see <https://www.gnu.org/licenses/>.
31
32;;; Commentary:
33
34;; Reworked version of Eki Zhang's consult-todo.el
35;; (https://github.com/eki3z/consult-todo). The reason for the
36;; rewrite was that `consult-todo-dir' was completely broken for about
37;; a year.
38
39;; This library makes good use of consult's async pipeline, using it
40;; only to feed in extra candidates and not to rerun the search
41;; command.
42
43;; REVIEW(cmmm): inspect if the hashtable actually improves anything
44;; TODO(cmmm): remove dependence on custom changes to hl-todo
45;; TODO(cmmm): improve docstrings
46
47;;; Code:
48
49(eval-when-compile
50 (require 'cl-lib)
51 (require 'subr-x))
52(require 'consult)
53(require 'hl-todo)
54
55(defgroup consult-hl-todo nil
56 "Search and navigate `hl-todo' markers via `consult'."
57 :link '(url-link :tag "Website" "https://git.michalec.dev/consult-hl-todo/about")
58 :link '(emacs-library-link :tag "Library Source" "consult-hl-todo.el")
59 :group 'consult
60 :group 'hl-todo
61 :prefix "consult-hl-todo-")
62
63(defcustom consult-hl-todo-ripgrep-args consult-ripgrep-args
64 "Command line arguments for ripgrep."
65 :type 'string
66 :group 'consult-hl-todo)
67
68(defcustom consult-hl-todo-other-type '(?o . "OTHER")
69 "Type for markers with unassigned type."
70 :type '(cons character string)
71 :group 'consult-hl-todo)
72
73(defcustom consult-hl-todo-require-author nil
74 "Whether to require author after keywords."
75 :type 'boolean
76 :group 'consult-hl-todo)
77
78;; MAYBE(cmmm): construct from `hl-todo-keyword-faces'
79(defcustom consult-hl-todo-types
80 `((?t . "TODO")
81 (?n . "NEXT")
82 (?N . "NOTE")
83 (?f . "FIXME")
84 (?r . "REVIEW")
85 (?b . "BUG")
86 (?h . "HACK")
87 ,consult-hl-todo-other-type)
88 "List of known types."
89 :type '(repeat (cons character string))
90 :group 'consult-hl-todo)
91
92(defcustom consult-hl-todo-align-init [10 3 4 4]
93 "Initial column alignment in the form (FILENAME LINE KEYWORD AUTHOR)"
94 :type 'vector
95 :group 'consult-hl-todo)
96
97(defcustom consult-hl-todo-align-cap [30 5 10 10]
98 "Column alignment upper bounds in the form (FILENAME LINE KEYWORD AUTHOR)"
99 :type 'vector
100 :group 'consult-hl-todo)
101
102(hl-todo--setup-regexp t)
103(defconst consult-hl-todo--regexp-rg hl-todo--regexp)
104(hl-todo--setup-regexp nil)
105(defconst consult-hl-todo--regexp-el hl-todo--regexp)
106
107(defun consult-hl-todo--make-builder (paths)
108 "Make a builder for running `consult-hl-todo-rg-executable' on PATHS with
109EXTRA-FLAGS. Note that the builder ignores it's input, and so it won't
110be rerun on input change."
111 (lambda (_)
112 `(,@(split-string consult-hl-todo-ripgrep-args)
113 "-e" ,consult-hl-todo--regexp-rg ,@paths)))
114
115(defun consult-hl-todo--format (locations template info)
116 "Format each entry in INFO into a propertized candidate string.
117
118TEMPLATE is the `format' template produced by
119`consult-hl-todo--build-template'. INFO is a list of (COLS TYPE
120LOC) triples, where COLS is the list of already-propertized column
121strings, TYPE is the narrow/group character, and LOC is the
122(file row col) list identifying the hit.
123
124Each returned candidate carries the `consult--type' property so that
125`consult--type-group' and `consult--type-narrow' can dispatch on it, and
126its unpropertized text is registered in the LOCATIONS hash table as a
127key mapping to LOC, so the `:lookup' function can recover the location
128after the completion framework strips the text properties."
129 (mapcar
130 (lambda (entry)
131 (cl-destructuring-bind (cols type loc) entry
132 (let* ((str (propertize (apply #'format template cols)
133 'consult--type type
134 'consult--candidate loc)))
135 (puthash (substring-no-properties str) loc locations)
136 str)))
137 info))
138
139(defun consult-hl-todo--extract-info (lines)
140 "Parse LINES from rg into structured info triples.
141
142Each element of the result is a (COLS TYPE LOC) triple:
143
144 COLS A list of the five display strings (filename, line number,
145 keyword, author, message). The first four are propertized
146 with their display faces; the message is left plain.
147 TYPE The character used by `consult--type-group' and
148 `consult--type-narrow', taken from `consult-hl-todo-types' (or
149 `consult-hl-todo-other-type' when the keyword is not listed).
150 LOC The (FILE ROW COL) list identifying the hit. FILE is the path
151 as reported by rg, ROW and COL are integers.
152
153Lines that do not match the rg output format, or in which the hl-todo
154keyword regexp does not match, are dropped from the result rather than
155signalled as errors. The output is intended for
156`consult-hl-todo--format', which turns it into candidate strings and
157registers LOC in the locations hash table."
158 (delq
159 nil
160 (mapcar
161 (lambda (line)
162 (when (string-match
163 (concat "\\`\\(.+\\)\0\\([0-9]+\\):.*"
164 consult-hl-todo--regexp-el "\\(.*\\)\\'")
165 line)
166 (let* ((file (match-string 1 line))
167 (base (file-name-nondirectory file))
168 (rows (match-string 2 line))
169 (row (string-to-number rows))
170 (col (- (match-beginning 6) (match-end 2)))
171 (kw (match-string 4 line))
172 (author (s-trim (or (match-string 5 line) "")))
173 (msg (s-trim (match-string 6 line)))
174 (type (car (or (rassoc kw consult-hl-todo-types)
175 consult-hl-todo-other-type))))
176 (unless (and consult-hl-todo-require-author (eq author ""))
177 `((,(propertize base 'face 'consult-file)
178 ,(propertize rows 'face 'consult-line-number)
179 ,(propertize kw 'face
180 (hl-todo--combine-face
181 (cdr (assoc kw hl-todo-keyword-faces))))
182 ,(propertize author 'face 'magit-log-author)
183 ,msg)
184 ,type
185 (,file ,row ,col))))))
186 lines)))
187
188(defun consult-hl-todo--measure-align (info init)
189 "Return the column widths needed to align INFO, starting from INIT.
190
191INFO is a list of (COLS TYPE LOC) triples as returned by
192`consult-hl-todo--extract-info'. Only the first four elements of
193COLS (filename, line number, keyword, author) participate in the
194measurement; the trailing message column is variable-length and is never
195padded, so it is skipped.
196
197INIT is the width vector to grow from; it is copied first, so the
198caller's vector is left untouched. Each aligned column is then clamped
199to the corresponding entry of `consult-hl-todo-align-cap', which bounds
200the display width of pathological inputs (a single very long filename,
201for example) at the cost of letting those rows overflow their column.
202
203The result is a fresh vector of the same length as INIT, suitable for
204passing to `consult-hl-todo--build-template'."
205 (let ((align (copy-sequence init)))
206 (dolist (entry info)
207 (cl-loop for (s . rest) on (car entry)
208 for i from 0
209 while rest
210 do (aset align i (max (aref align i)
211 (length s)))))
212 (cl-loop for i below (length align)
213 do (aset align i (min (aref align i)
214 (aref consult-hl-todo-align-cap i))))
215 align))
216
217(defun consult-hl-todo--build-template (align)
218 "Build format template for the current alignment, this way we don't build
219it each time we need to align a candidate"
220 (apply #'format "%%-%ds %%%ds %%-%ds %%-%ds %%s" (append align nil)))
221
222(defun consult-hl-todo--async-format (locs)
223"Return a `consult' async decorator that formats rg output incrementally.
224
225LOCS is a hash table used as an out-parameter: each candidate
226string, keyed by its unpropertized text, is registered there with
227its (FILE ROW COL) location so that `:lookup' can recover the
228location after the completion framework strips text properties.
229
230The decorator accumulates the (COLS TYPE LOC) triples produced by
231`consult-hl-todo--extract-info' across chunks from rg and reformats them
232on two paths:
233
234 Fast path When the incoming chunk does not widen any aligned
235 column, only the new triples are formatted (with the
236 current template) and pushed to the sink. This is the
237 common case: widths stabilise within the first few
238 hundred hits and then never change again.
239
240 Slow path When a column grows, the accumulated triples are
241 reformatted against the new template, the sink is
242 flushed, and the full list is pushed. LOCS is
243 cleared first because the entire candidate list is being
244 replaced and old keys would otherwise linger as stale
245 entries.
246
247On `setup' and `destroy' the internal accumulators are reset from
248`consult-hl-todo-align-init'; `destroy' additionally releases the
249buffered triples."
250 (lambda (sink)
251 (let (info align capped template)
252 (lambda (action)
253 (pcase action
254 ((pred consp)
255 (if capped
256 (let* ((new-info (consult-hl-todo--extract-info action)))
257 (setq info (append info new-info))
258 (funcall sink (consult-hl-todo--format locs template new-info)))
259 (let* ((new-info (consult-hl-todo--extract-info action))
260 (new-align (consult-hl-todo--measure-align new-info align)))
261 (setq info (append info new-info))
262 (if (equal new-align align)
263 (funcall sink (consult-hl-todo--format locs template new-info))
264 (setq align new-align
265 template (consult-hl-todo--build-template align))
266 (clrhash locs)
267 (let ((cands (consult-hl-todo--format locs template info)))
268 (funcall sink 'flush)
269 (funcall sink cands))
270 (when (equal align consult-hl-todo-align-cap)
271 (setq capped t))))))
272 ((or 'setup 'destroy)
273 (setq info nil align (copy-sequence consult-hl-todo-align-init)
274 capped nil template (consult-hl-todo--build-template align))
275 (funcall sink action))
276 (_(funcall sink action)))))))
277
278(cl-defun consult-hl-todo--pipeline (locations paths &rest props)
279 (declare (indent 1))
280 (consult--async-pipeline
281 (apply #'consult--async-process (consult-hl-todo--make-builder paths)
282 (consult--plist-remove
283 '(:min-input :throttle :debounce :transform :highlight) props))
284 (consult-hl-todo--async-format locations)
285 (consult--async-indicator)
286 (consult--async-refresh 0)))
287
288(defun consult-hl-todo--state ()
289"Return the state function for `consult-hl-todo'.
290
291The returned function is passed to `consult--read' as its :state
292argument and is called with an ACTION and a candidate CAND. It
293delegates the actual preview, return, and exit handling to
294`consult--jump-state', supplying it with a marker computed from CAND
295when one is available.
296
297CAND is the (FILE ROW COL) list produced by :lookup, not the candidate
298string, so the location is available directly without re-reading text
299properties -- `completing-read' strips those before the selection
300reaches the state function.
301
302Files are opened through `consult--temporary-files', so previewing a
303candidate does not permanently visit its buffer; the same opener is
304handed to `consult--jump-state' so that it can find the buffer for the
305marker. When CAND is nil -- the exit path, with no selection made --
306the temporary files are closed and the original position is restored by
307`consult--jump-state'.
308
309A fresh state function is created on each call, so every
310`consult-hl-todo' invocation gets its own temporary-file session and no
311state leaks between runs."
312 (let ((jump (consult--jump-state))
313 (open (consult--temporary-files)))
314 (lambda (action cand)
315 (unless cand
316 (funcall open))
317 (funcall jump action
318 (consult-hl-todo--position
319 cand (and (not (eq action 'return)) open))))))
320
321(defun consult-hl-todo--position (cand &optional find-file)
322 "Return the position marker for CAND.
323FIND-FILE is the file open function, defaulting to `find-file-noselect'."
324 (when (consp cand)
325 (cl-destructuring-bind (file row col) cand
326 (consult--marker-from-line-column
327 (funcall (or find-file #'consult--file-action) file) row col))))
328
329(defun consult-hl-todo-embark-goto (cand)
330 "Jump to the location of the hl-todo candidate CAND."
331 (consult--jump (consult-hl-todo--position
332 (get-text-property 0 'consult--candidate cand)))
333 (pulse-momentary-highlight-one-line (point)))
334
335(with-eval-after-load 'embark
336 (setf (alist-get 'consult-hl-todo embark-default-action-overrides)
337 #'consult-hl-todo-embark-goto))
338
339(defun consult-hl-todo--run (paths)
340 (let ((locations (make-hash-table :test #'equal)))
341 (consult--read
342 (consult-hl-todo--pipeline locations paths)
343 :prompt "hl-todo: "
344 :state (consult-hl-todo--state)
345 :category 'consult-hl-todo
346 :require-match t
347 :async-wrap #'identity
348 :lookup (lambda (cand &rest _) (gethash cand locations))
349 ;; :lookup #'consult--lookup-candidate
350 :group (consult--type-group consult-hl-todo-types)
351 :narrow (consult--type-narrow consult-hl-todo-types))))
352
353(defun consult-hl-todo--default-path (&optional confirm supplied prompt)
354 "Guesses the wanted path in the following order
355SUPPLIED -> PROJECT-ROOT -> DEFAULT-DIRECTORY. When CONFIRM is non-nil,
356the user is prompted with PROMPT to modify the guessed path."
357 (let* ((proj (project-current))
358 (guessed (or supplied (and proj (project-root proj)) default-directory)))
359 (expand-file-name (if confirm (read-file-name (or prompt "Path: ") guessed nil t)
360 guessed))))
361
362;;;###autoload
363(defun consult-hl-todo (paths &optional confirm)
364 "Jump to hl-todo keywords in files within PATHS. CONFIRM is used in
365interactive mode to prompt for path, with a sensible initial guess."
366 (interactive
367 `((,(consult-hl-todo--default-path current-prefix-arg)) nil))
368 (consult-hl-todo--run paths))
369
370;;;###autoload
371(defun consult-hl-todo-buffer-file (path &optional confirm)
372 "Jump to hl-todo keywords in file PATH. CONFIRM is used in
373interactive mode to prompt for path, with current buffer's path as
374initial guess."
375 (interactive
376 `(,(consult-hl-todo--default-path current-prefix-arg (buffer-file-name)) nil))
377 (let ((path (expand-file-name path)))
378 (when-let* ((buf (find-buffer-visiting path)))
379 (when (buffer-modified-p buf)
380 (unless (yes-or-no-p (format "Save %s? " (buffer-name buf)))
381 (user-error "Aborted, buffer not saved"))
382 (with-current-buffer buf
383 (save-buffer))))
384 (consult-hl-todo--run (list path))))
385
386(provide 'consult-hl-todo)
387
388;;; consult-hl-todo.el ends here