aboutsummaryrefslogtreecommitdiff
path: root/consult-hl-todo.el
blob: fd3630ff435c5650d18c6892a0cfac7a63a292f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
;;; consult-hl-todo.el --- Consult hl-todo keywords in files -*- lexical-binding: t; -*-

;; Copyright (C) 2026  Martin Michalec

;; Author: Martin Michalec <martin@michalec.dev>
;; Maintainer: Martin Michalec <martin@michalec.dev>
;; URL: https://git.michalec.dev/consult-hl-todo
;; Created: 2026
;; Keywords: convenience, matching, outlining

;; Version: 0.0.0
;; Package-Requires: ((emacs   "29.1")
;;                    (compat  "31")
;;                    (conslut "3")
;;                    (hl-todo "3"))

;; SPDX-License-Identifier: GPL-3.0-or-later

;; 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 <https://www.gnu.org/licenses/>.

;;; Commentary:

;; Reworked version of Eki Zhang's consult-todo.el
;; (https://github.com/eki3z/consult-todo).  The reason for the
;; rewrite was that `consult-todo-dir' was completely broken for about
;; a year.

;; This library makes good use of consult's async pipeline, using it
;; only to feed in extra candidates and not to rerun the search
;; command.

;; REVIEW(cmmm): inspect if the hashtable actually improves anything
;; TODO(cmmm): remove dependence on custom changes to hl-todo
;; TODO(cmmm): improve docstrings

;;; Code:

(eval-when-compile
  (require 'cl-lib)
  (require 'subr-x))
(require 'consult)
(require 'hl-todo)

(defgroup consult-hl-todo nil
  "Search and navigate `hl-todo' markers via `consult'."
  :link '(url-link :tag "Website" "https://git.michalec.dev/consult-hl-todo/about")
  :link '(emacs-library-link :tag "Library Source" "consult-hl-todo.el")
  :group 'consult
  :group 'hl-todo
  :prefix "consult-hl-todo-")

(defcustom consult-hl-todo-ripgrep-args consult-ripgrep-args
  "Command line arguments for ripgrep."
  :type 'string
  :group 'consult-hl-todo)

(defcustom consult-hl-todo-other-type '(?o . "OTHER")
  "Type for markers with unassigned type."
  :type '(cons character string)
  :group 'consult-hl-todo)

(defcustom consult-hl-todo-require-author nil
  "Whether to require author after keywords."
  :type 'boolean
  :group 'consult-hl-todo)

;; MAYBE(cmmm): construct from `hl-todo-keyword-faces'
(defcustom consult-hl-todo-types
  `((?t . "TODO")
    (?n . "NEXT")
    (?N . "NOTE")
    (?f . "FIXME")
    (?r . "REVIEW")
    (?b . "BUG")
    (?h . "HACK")
    ,consult-hl-todo-other-type)
  "List of known types."
  :type '(repeat (cons character string))
  :group 'consult-hl-todo)

(defcustom consult-hl-todo-align-init [10 3 4 4]
  "Initial column alignment in the form (FILENAME LINE KEYWORD AUTHOR)"
  :type 'vector
  :group 'consult-hl-todo)

(defcustom consult-hl-todo-align-cap [30 5 10 10]
  "Column alignment upper bounds in the form (FILENAME LINE KEYWORD AUTHOR)"
  :type 'vector
  :group 'consult-hl-todo)

(hl-todo--setup-regexp t)
(defconst consult-hl-todo--regexp-rg hl-todo--regexp)
(hl-todo--setup-regexp nil)
(defconst consult-hl-todo--regexp-el hl-todo--regexp)

(defun consult-hl-todo--make-builder (paths)
  "Make a builder for running `consult-hl-todo-rg-executable' on PATHS with
EXTRA-FLAGS.  Note that the builder ignores it's input, and so it won't
be rerun on input change."
  (lambda (_)
    `(,@(split-string consult-hl-todo-ripgrep-args)
      "-e" ,consult-hl-todo--regexp-rg ,@paths)))

(defun consult-hl-todo--format (locations template info)
  "Format each entry in INFO into a propertized candidate string.

TEMPLATE is the `format' template produced by
`consult-hl-todo--build-template'.  INFO is a list of (COLS TYPE
LOC) triples, where COLS is the list of already-propertized column
strings, TYPE is the narrow/group character, and LOC is the
(file row col) list identifying the hit.

Each returned candidate carries the `consult--type' property so that
`consult--type-group' and `consult--type-narrow' can dispatch on it, and
its unpropertized text is registered in the LOCATIONS hash table as a
key mapping to LOC, so the `:lookup' function can recover the location
after the completion framework strips the text properties."
  (mapcar
   (lambda (entry)
     (cl-destructuring-bind (cols type loc) entry
       (let* ((str (propertize (apply #'format template cols)
                               'consult--type type
                               'consult--candidate loc)))
         (puthash (substring-no-properties str) loc locations)
         str)))
   info))

(defun consult-hl-todo--extract-info (lines)
  "Parse LINES from rg into structured info triples.

Each element of the result is a (COLS TYPE LOC) triple:

  COLS  A list of the five display strings (filename, line number,
        keyword, author, message).  The first four are propertized
        with their display faces; the message is left plain.
  TYPE  The character used by `consult--type-group' and
        `consult--type-narrow', taken from `consult-hl-todo-types' (or
        `consult-hl-todo-other-type' when the keyword is not listed).
  LOC   The (FILE ROW COL) list identifying the hit.  FILE is the path
        as reported by rg, ROW and COL are integers.

Lines that do not match the rg output format, or in which the hl-todo
keyword regexp does not match, are dropped from the result rather than
signalled as errors.  The output is intended for
`consult-hl-todo--format', which turns it into candidate strings and
registers LOC in the locations hash table."
  (delq
   nil
   (mapcar
    (lambda (line)
      (when (string-match
             (concat "\\`\\(.+\\)\0\\([0-9]+\\):.*"
                     consult-hl-todo--regexp-el "\\(.*\\)\\'")
             line)
        (let* ((file   (match-string 1 line))
               (base   (file-name-nondirectory file))
               (rows   (match-string 2 line))
               (row    (string-to-number rows))
               (col    (- (match-beginning 6) (match-end 2)))
               (kw     (match-string 4 line))
               (author (s-trim (or (match-string 5 line) "")))
               (msg    (s-trim (match-string 6 line)))
               (type (car (or (rassoc kw consult-hl-todo-types)
                              consult-hl-todo-other-type))))
          (unless (and consult-hl-todo-require-author (eq author ""))
            `((,(propertize base 'face 'consult-file)
               ,(propertize rows 'face 'consult-line-number)
               ,(propertize kw 'face
                            (hl-todo--combine-face
                             (cdr (assoc kw hl-todo-keyword-faces))))
               ,(propertize author 'face 'magit-log-author)
               ,msg)
              ,type
              (,file ,row ,col))))))
    lines)))

(defun consult-hl-todo--measure-align (info init)
 "Return the column widths needed to align INFO, starting from INIT.

INFO is a list of (COLS TYPE LOC) triples as returned by
`consult-hl-todo--extract-info'.  Only the first four elements of
COLS (filename, line number, keyword, author) participate in the
measurement; the trailing message column is variable-length and is never
padded, so it is skipped.

INIT is the width vector to grow from; it is copied first, so the
caller's vector is left untouched.  Each aligned column is then clamped
to the corresponding entry of `consult-hl-todo-align-cap', which bounds
the display width of pathological inputs (a single very long filename,
for example) at the cost of letting those rows overflow their column.

The result is a fresh vector of the same length as INIT, suitable for
passing to `consult-hl-todo--build-template'."
  (let ((align (copy-sequence init)))
    (dolist (entry info)
      (cl-loop for (s . rest) on (car entry)
               for i from 0
               while rest
               do (aset align i (max (aref align i)
                                     (length s)))))
    (cl-loop for i below (length align)
             do (aset align i (min (aref align i)
                                   (aref consult-hl-todo-align-cap i))))
    align))

(defun consult-hl-todo--build-template (align)
  "Build format template for the current alignment, this way we don't build
it each time we need to align a candidate"
  (apply #'format "%%-%ds %%%ds %%-%ds %%-%ds %%s" (append align nil)))

(defun consult-hl-todo--async-format (locs)
"Return a `consult' async decorator that formats rg output incrementally.

LOCS is a hash table used as an out-parameter: each candidate
string, keyed by its unpropertized text, is registered there with
its (FILE ROW COL) location so that `:lookup' can recover the
location after the completion framework strips text properties.

The decorator accumulates the (COLS TYPE LOC) triples produced by
`consult-hl-todo--extract-info' across chunks from rg and reformats them
on two paths:

  Fast path  When the incoming chunk does not widen any aligned
             column, only the new triples are formatted (with the
             current template) and pushed to the sink.  This is the
             common case: widths stabilise within the first few
             hundred hits and then never change again.

  Slow path  When a column grows, the accumulated triples are
             reformatted against the new template, the sink is
             flushed, and the full list is pushed.  LOCS is
             cleared first because the entire candidate list is being
             replaced and old keys would otherwise linger as stale
             entries.

On `setup' and `destroy' the internal accumulators are reset from
`consult-hl-todo-align-init'; `destroy' additionally releases the
buffered triples."
  (lambda (sink)
    (let (info align capped template)
      (lambda (action)
        (pcase action
          ((pred consp)
           (if capped
               (let* ((new-info (consult-hl-todo--extract-info action)))
                 (setq info (append info new-info))
                 (funcall sink (consult-hl-todo--format locs template new-info)))
             (let* ((new-info (consult-hl-todo--extract-info action))
                    (new-align (consult-hl-todo--measure-align new-info align)))
               (setq info (append info new-info))
               (if (equal new-align align)
                   (funcall sink (consult-hl-todo--format locs template new-info))
                 (setq align new-align
                       template (consult-hl-todo--build-template align))
                 (clrhash locs)
                 (let ((cands (consult-hl-todo--format locs template info)))
                   (funcall sink 'flush)
                   (funcall sink cands))
                 (when (equal align consult-hl-todo-align-cap)
                   (setq capped t))))))
          ((or 'setup 'destroy)
           (setq info nil align (copy-sequence consult-hl-todo-align-init)
                 capped nil template (consult-hl-todo--build-template align))
           (funcall sink action))
          (_(funcall sink action)))))))

(cl-defun consult-hl-todo--pipeline (locations paths &rest props)
  (declare (indent 1))
  (consult--async-pipeline
   (apply #'consult--async-process (consult-hl-todo--make-builder paths)
          (consult--plist-remove
           '(:min-input :throttle :debounce :transform :highlight) props))
   (consult-hl-todo--async-format locations)
   (consult--async-indicator)
   (consult--async-refresh 0)))

(defun consult-hl-todo--state ()
"Return the state function for `consult-hl-todo'.

The returned function is passed to `consult--read' as its :state
argument and is called with an ACTION and a candidate CAND.  It
delegates the actual preview, return, and exit handling to
`consult--jump-state', supplying it with a marker computed from CAND
when one is available.

CAND is the (FILE ROW COL) list produced by :lookup, not the candidate
string, so the location is available directly without re-reading text
properties -- `completing-read' strips those before the selection
reaches the state function.

Files are opened through `consult--temporary-files', so previewing a
candidate does not permanently visit its buffer; the same opener is
handed to `consult--jump-state' so that it can find the buffer for the
marker.  When CAND is nil -- the exit path, with no selection made --
the temporary files are closed and the original position is restored by
`consult--jump-state'.

A fresh state function is created on each call, so every
`consult-hl-todo' invocation gets its own temporary-file session and no
state leaks between runs."
  (let ((jump (consult--jump-state))
        (open (consult--temporary-files)))
    (lambda (action cand)
      (unless cand
        (funcall open))
      (funcall jump action
               (consult-hl-todo--position
                cand (and (not (eq action 'return)) open))))))

(defun consult-hl-todo--position (cand &optional find-file)
  "Return the position marker for CAND.
FIND-FILE is the file open function, defaulting to `find-file-noselect'."
  (when (consp cand)
    (cl-destructuring-bind (file row col) cand
      (consult--marker-from-line-column
       (funcall (or find-file #'consult--file-action) file) row col))))

(defun consult-hl-todo-embark-goto (cand)
  "Jump to the location of the hl-todo candidate CAND."
  (consult--jump (consult-hl-todo--position
                  (get-text-property 0 'consult--candidate cand)))
  (pulse-momentary-highlight-one-line (point)))

(with-eval-after-load 'embark
  (setf (alist-get 'consult-hl-todo embark-default-action-overrides)
        #'consult-hl-todo-embark-goto))

(defun consult-hl-todo--run (paths)
  (let ((locations (make-hash-table :test #'equal)))
    (consult--read
     (consult-hl-todo--pipeline locations paths)
     :prompt "hl-todo: "
     :state (consult-hl-todo--state)
     :category 'consult-hl-todo
     :require-match t
     :async-wrap #'identity
     :lookup (lambda (cand &rest _) (gethash cand locations))
     ;; :lookup #'consult--lookup-candidate
     :group (consult--type-group consult-hl-todo-types)
     :narrow (consult--type-narrow consult-hl-todo-types))))

(defun consult-hl-todo--default-path (&optional confirm supplied prompt)
  "Guesses the wanted path in the following order
SUPPLIED -> PROJECT-ROOT -> DEFAULT-DIRECTORY.  When CONFIRM is non-nil,
the user is prompted with PROMPT to modify the guessed path."
  (let* ((proj (project-current))
         (guessed (or supplied (and proj (project-root proj)) default-directory)))
    (expand-file-name (if confirm (read-file-name (or prompt "Path: ") guessed nil t)
                        guessed))))

;;;###autoload
(defun consult-hl-todo (paths &optional confirm)
  "Jump to hl-todo keywords in files within PATHS.  CONFIRM is used in
interactive mode to prompt for path, with a sensible initial guess."
  (interactive
   `((,(consult-hl-todo--default-path current-prefix-arg)) nil))
  (consult-hl-todo--run paths))

;;;###autoload
(defun consult-hl-todo-buffer-file (path &optional confirm)
  "Jump to hl-todo keywords in file PATH.  CONFIRM is used in
interactive mode to prompt for path, with current buffer's path as
initial guess."
  (interactive
   `(,(consult-hl-todo--default-path current-prefix-arg (buffer-file-name)) nil))
  (let ((path (expand-file-name path)))
    (when-let* ((buf (find-buffer-visiting path)))
      (when (buffer-modified-p buf)
        (unless (yes-or-no-p (format "Save %s? " (buffer-name buf)))
          (user-error "Aborted, buffer not saved"))
        (with-current-buffer buf
          (save-buffer))))
    (consult-hl-todo--run (list path))))

(provide 'consult-hl-todo)

;;; consult-hl-todo.el ends here