From 9edba2a6942104a6d69c06dff293b4e9c1b90731 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Sat, 24 Oct 2026 01:50:55 +0300 Subject: feat: initial implementation --- consult-hl-todo.el | 388 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 388 insertions(+) create mode 100644 consult-hl-todo.el (limited to 'consult-hl-todo.el') 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 @@ +;;; consult-hl-todo.el --- Consult hl-todo keywords in files -*- lexical-binding: t; -*- + +;; Copyright (C) 2026 Martin Michalec + +;; Author: Martin Michalec +;; Maintainer: Martin Michalec +;; 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 . + +;;; 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 -- cgit v1.3.1