aboutsummaryrefslogtreecommitdiff
path: root/modules
diff options
context:
space:
mode:
Diffstat (limited to 'modules')
-rw-r--r--modules/ai-config.el577
-rw-r--r--modules/ai-conversations-browser.el241
-rw-r--r--modules/ai-conversations.el375
-rw-r--r--modules/ai-mcp.el416
-rw-r--r--modules/ai-quick-ask.el141
-rw-r--r--modules/ai-rewrite.el108
-rw-r--r--modules/ai-term.el440
-rw-r--r--modules/auth-config.el9
-rw-r--r--modules/browser-config.el9
-rw-r--r--modules/calendar-sync.el180
-rw-r--r--modules/calibredb-epub-config.el56
-rw-r--r--modules/chrono-tools.el39
-rw-r--r--modules/cj-window-geometry-lib.el69
-rw-r--r--modules/cj-window-toggle-lib.el30
-rw-r--r--modules/config-utilities.el19
-rw-r--r--modules/coverage-core.el42
-rw-r--r--modules/custom-case.el120
-rw-r--r--modules/custom-comments.el167
-rw-r--r--modules/custom-datetime.el61
-rw-r--r--modules/custom-ordering.el102
-rw-r--r--modules/custom-text-enclose.el78
-rw-r--r--modules/dashboard-config.el64
-rw-r--r--modules/diff-config.el6
-rw-r--r--modules/dirvish-config.el231
-rw-r--r--modules/dwim-shell-config.el86
-rw-r--r--modules/elfeed-config.el71
-rw-r--r--modules/erc-config.el70
-rw-r--r--modules/eshell-config.el36
-rw-r--r--modules/eww-config.el9
-rw-r--r--modules/face-diagnostic.el60
-rw-r--r--modules/flycheck-config.el8
-rw-r--r--modules/font-config.el83
-rw-r--r--modules/games-config.el32
-rw-r--r--modules/gcmh-config.el30
-rw-r--r--modules/google-keep-config.el210
-rw-r--r--modules/help-config.el10
-rw-r--r--modules/help-utils.el4
-rw-r--r--modules/httpd-config.el12
-rw-r--r--modules/jumper.el132
-rw-r--r--modules/keybindings.el4
-rw-r--r--modules/latex-config.el9
-rw-r--r--modules/ledger-config.el47
-rw-r--r--modules/local-repository.el16
-rw-r--r--modules/mail-config.el137
-rw-r--r--modules/markdown-config.el12
-rw-r--r--modules/modeline-config.el32
-rw-r--r--modules/mousetrap-mode.el46
-rw-r--r--modules/mu4e-org-contacts-integration.el1
-rw-r--r--modules/mu4e-org-contacts-setup.el4
-rw-r--r--modules/music-config.el380
-rw-r--r--modules/nerd-icons-config.el46
-rw-r--r--modules/org-agenda-config-debug.el3
-rw-r--r--modules/org-agenda-config.el46
-rw-r--r--modules/org-babel-config.el6
-rw-r--r--modules/org-capture-config.el52
-rw-r--r--modules/org-config.el85
-rw-r--r--modules/org-contacts-config.el56
-rw-r--r--modules/org-faces-config.el56
-rw-r--r--modules/org-noter-config.el25
-rw-r--r--modules/org-refile-config.el11
-rw-r--r--modules/org-roam-config.el36
-rw-r--r--modules/pdf-config.el21
-rw-r--r--modules/prog-general.el87
-rw-r--r--modules/prog-json.el31
-rw-r--r--modules/prog-webdev.el27
-rw-r--r--modules/prog-yaml.el31
-rw-r--r--modules/selection-framework.el6
-rw-r--r--modules/system-defaults.el19
-rw-r--r--modules/system-lib.el47
-rw-r--r--modules/system-utils.el36
-rw-r--r--modules/term-config.el128
-rw-r--r--modules/test-runner.el1
-rw-r--r--modules/tramp-config.el9
-rw-r--r--modules/transcription-config.el14
-rw-r--r--modules/ui-config.el7
-rw-r--r--modules/ui-navigation.el84
-rw-r--r--modules/ui-theme.el6
-rw-r--r--modules/user-constants.el56
-rw-r--r--modules/vc-config.el21
-rw-r--r--modules/video-audio-recording.el7
80 files changed, 2853 insertions, 3328 deletions
diff --git a/modules/ai-config.el b/modules/ai-config.el
deleted file mode 100644
index 20bf6ec88..000000000
--- a/modules/ai-config.el
+++ /dev/null
@@ -1,577 +0,0 @@
-;;; ai-config.el --- Configuration for AI Integrations -*- lexical-binding: t; coding: utf-8; -*-
-;; author Craig Jennings <c@cjennings.net>
-;;
-;;; Commentary:
-;;
-;; Layer: 3 (Domain Workflow).
-;; Category: D/P.
-;; Load shape: eager.
-;; Eager reason: registers the cj/ai-keymap (C-; a); GPTel itself should load on
-;; command, a Phase 5 deferral candidate.
-;; Top-level side effects: defines cj/ai-keymap, registers it under cj/custom-keymap.
-;; Runtime requires: keybindings, system-lib.
-;; Direct test load: yes (requires keybindings explicitly).
-;;
-;; Configuration for AI integrations in Emacs, focused on GPTel.
-;;
-;; Main Features:
-;; - Quick toggle for AI assistant window (C-; a t)
-;; - Custom keymap (C-; a prefix) for AI-related commands.
-;; - Enhanced org-mode conversation formatting with timestamps
-;; allows switching models and easily compare and track responses.
-;; - Various specialized AI directives (coder, reviewer, etc.)
-;; - Context management for adding files/buffers to conversations
-;; - Conversation persistence with save/load functionality
-;; - Integration with Magit for code review
-;;
-;; Basic Workflow
-;;
-;; Using a side-chat window:
-;; - Launch GPTel via C-; a t, and chat in the AI-Assistant side window (C-<return> to send)
-;; - Change system prompt (expertise, personalities) with C-; a p
-;; - Add context from files (C-; a f) or current buffer (C-; a .)
-;; - Save conversations with C-; a s, load previous ones with C-; a l
-;; - Clear the conversation and start over with C-; a x
-;; Or in any buffer:
-;; - Add directive as above, and select a region to rewrite with C-; a r.
-;;
-
-;;; Code:
-
-(require 'keybindings) ;; provides cj/custom-keymap
-(require 'system-lib) ;; provides cj/auth-source-secret-value
-(require 'cj-window-toggle-lib) ;; side-window size memory for the panel
-
-(autoload 'cj/gptel-save-conversation "ai-conversations" "Save the AI conversation to a file." t)
-(autoload 'cj/gptel-load-conversation "ai-conversations" "Load a saved AI conversation." t)
-(autoload 'cj/gptel-delete-conversation "ai-conversations" "Delete a saved AI conversation." t)
-(autoload 'cj/gptel-autosave-toggle "ai-conversations" "Toggle autosave in the current GPTel buffer." t)
-(autoload 'cj/gptel-quick-ask "ai-quick-ask" "One-shot quick-ask in a transient buffer." t)
-(autoload 'cj/gptel-rewrite-with-directive "ai-rewrite" "Pick a directive and run gptel-rewrite on the region." t)
-(autoload 'cj/gptel-rewrite-redo-with-different-directive "ai-rewrite" "Re-run the previous rewrite with a different directive." t)
-(autoload 'cj/gptel-browse-conversations "ai-conversations-browser" "Browse saved GPTel conversations." t)
-
-;;; ------------------------- AI Config Helper Functions ------------------------
-
-;; Define variables upfront
-(defvar cj/anthropic-api-key-cached nil "Cached Anthropic API key.")
-(defvar cj/openai-api-key-cached nil "Cached OpenAI API key.")
-(defvar gptel-claude-backend nil "Claude backend, lazy-initialized.")
-(defvar gptel-chatgpt-backend nil "ChatGPT backend, lazy-initialized.")
-
-(defcustom cj/gptel-tools-directory
- (expand-file-name "gptel-tools/" user-emacs-directory)
- "Directory containing optional local GPTel tool modules."
- :type 'directory
- :group 'cj)
-
-(defcustom cj/gptel-local-tool-features
- '(read_buffer
- read_text_file
- write_text_file
- update_text_file
- list_directory_files
- move_to_trash
- git_status
- git_log
- git_diff
- web_fetch)
- "Feature symbols for optional local GPTel tool modules."
- :type '(repeat symbol)
- :group 'cj)
-
-(defun cj/gptel-load-local-tools
- (&optional tools-directory tool-features)
- "Load optional GPTel tools from TOOLS-DIRECTORY.
-TOOL-FEATURES defaults to `cj/gptel-local-tool-features'. Return a list
-of loaded feature symbols. Missing directories or individual optional
-tools are reported with `message' and do not signal."
- (let ((dir (file-name-as-directory
- (expand-file-name (or tools-directory cj/gptel-tools-directory))))
- (features (or tool-features cj/gptel-local-tool-features))
- (loaded nil))
- (cond
- ((not (file-directory-p dir))
- (message "GPTel tools directory not found: %s" dir)
- nil)
- (t
- (add-to-list 'load-path dir)
- (dolist (feature features)
- (condition-case err
- (if (require feature nil 'noerror)
- (push feature loaded)
- (message "Optional GPTel tool not found: %s" feature))
- (error
- (message "Failed to load GPTel tool %s: %s"
- feature
- (error-message-string err)))))
- (nreverse loaded)))))
-
-(with-eval-after-load 'gptel
- (require 'ai-conversations)
- (cj/gptel-load-local-tools))
-
-(defun cj/auth-source-secret (host user)
- "Fetch a required secret from auth-source for HOST and USER.
-
-HOST and USER must be strings that identify the credential to return.
-Errors when no secret is found."
- (or (cj/auth-source-secret-value host user)
- (error "No usable secret found for host %s and user %s" host user)))
-
-(defun cj/anthropic-api-key ()
- "Return the Anthropic API key, caching the result after first retrieval."
- (or cj/anthropic-api-key-cached
- (setq cj/anthropic-api-key-cached
- (cj/auth-source-secret "api.anthropic.com" "apikey"))))
-
-(defun cj/openai-api-key ()
- "Return the OpenAI API key, caching the result after first retrieval."
- (or cj/openai-api-key-cached
- (setq cj/openai-api-key-cached
- (cj/auth-source-secret "api.openai.com" "apikey"))))
-
-(defun cj/--gptel-load-backend-libs ()
- "Require the gptel backend libraries so their `gptel-make-*' constructors exist.
-The local fork (`:load-path \"~/code/gptel\"', `:ensure nil') ships no generated
-autoloads, so requiring `gptel' alone never loads `gptel-anthropic' /
-`gptel-openai', where the constructors are defined."
- (require 'gptel-anthropic)
- (require 'gptel-openai))
-
-(defun cj/ensure-gptel-backends ()
- "Initialize GPTel backends if they are not already available.
-Loads the backend libraries first so the `gptel-make-*' constructors are
-defined even when gptel is the local fork without generated autoloads."
- (cj/--gptel-load-backend-libs)
- (unless gptel-claude-backend
- (setq gptel-claude-backend
- (gptel-make-anthropic
- "Claude"
- :key (cj/anthropic-api-key)
- :models '(
- "claude-opus-4-7"
- "claude-sonnet-4-6"
- "claude-haiku-4-5-20251001"
- )
- :stream t)))
- (unless gptel-chatgpt-backend
- (setq gptel-chatgpt-backend
- (gptel-make-openai
- "ChatGPT"
- :key (cj/openai-api-key)
- :models '(
- "gpt-5.5"
- "gpt-5.4-mini"
- "o3"
- )
- :stream t)))
- ;; Set default backend and model
- (unless gptel-backend
- (setq gptel-backend (or gptel-chatgpt-backend gptel-claude-backend))
- (setq gptel-model 'gpt-5.5)))
-
-;; ------------------ GPTel Conversation And Utility Commands ------------------
-
-(defun cj/gptel--available-backends ()
- "Return an alist of (NAME . BACKEND).
-Ensures gptel and backends are initialized."
- (unless (featurep 'gptel)
- (require 'gptel))
- (cj/ensure-gptel-backends)
- (delq nil
- (list (and (bound-and-true-p gptel-claude-backend)
- (cons "Anthropic - Claude" gptel-claude-backend))
- (and (bound-and-true-p gptel-chatgpt-backend)
- (cons "OpenAI - ChatGPT" gptel-chatgpt-backend)))))
-
-(defun cj/gptel--model-to-string (m)
- "Return model M as a string regardless of its type."
- (cond
- ((stringp m) m)
- ((symbolp m) (symbol-name m))
- (t (format "%s" m))))
-
-(defun cj/gptel--model-to-symbol (m)
- "Return model M as a symbol regardless of its type.
-`gptel-model' must be a symbol: gptel's modeline code calls `symbolp'
-on it and signals `wrong-type-argument' on a string, which surfaces as a
-redisplay hang. Coerce any model value through this before assigning it."
- (cond
- ((symbolp m) m)
- ((stringp m) (intern m))
- (t (intern (format "%s" m)))))
-
-;; Backend/model switching helpers (pure logic, extracted for testability)
-
-(defun cj/gptel--build-model-list (backends model-fn)
- "Build a flat list of all models across BACKENDS.
-BACKENDS is an alist of (NAME . BACKEND-OBJECT). MODEL-FN is called
-with each backend object and should return a list of model identifiers.
-Returns a list of entries: (DISPLAY-STRING BACKEND MODEL-STRING BACKEND-NAME)
-where DISPLAY-STRING is \"Backend: model\" for use in completing-read."
- (mapcan
- (lambda (pair)
- (let* ((backend-name (car pair))
- (backend (cdr pair))
- (models (funcall model-fn backend)))
- (mapcar (lambda (m)
- (list (format "%s: %s" backend-name (cj/gptel--model-to-string m))
- backend
- (cj/gptel--model-to-string m)
- backend-name))
- models)))
- backends))
-
-(defun cj/gptel--current-model-selection (backends current-backend current-model)
- "Format the current backend/model as a display string.
-BACKENDS is the alist from `cj/gptel--available-backends'.
-CURRENT-BACKEND and CURRENT-MODEL are the active gptel settings.
-Returns a string like \"Anthropic - Claude: claude-opus-4-7\"."
- (let ((backend-name (car (rassoc current-backend backends))))
- (format "%s: %s"
- (or backend-name "AI")
- (cj/gptel--model-to-string current-model))))
-
-;; Backend/model switching commands
-(defun cj/gptel-change-model ()
- "Change the GPTel backend and select a model from that backend.
-Present all available models from every backend, switching backends when
-necessary. Prompt for whether to apply the selection globally or buffer-locally."
- (interactive)
- (let* ((backends (cj/gptel--available-backends))
- (all-models (cj/gptel--build-model-list
- backends
- (lambda (b)
- (when (fboundp 'gptel-backend-models)
- (gptel-backend-models b)))))
- (current-selection (cj/gptel--current-model-selection
- backends
- (bound-and-true-p gptel-backend)
- (bound-and-true-p gptel-model)))
- (scope (completing-read "Set model for: " '("buffer" "global") nil t))
- (selected (completing-read
- (format "Select model (current: %s): " current-selection)
- (mapcar #'car all-models) nil t nil nil current-selection)))
- (let* ((model-info (assoc selected all-models))
- (backend (nth 1 model-info))
- (model (intern (nth 2 model-info)))
- (backend-name (nth 3 model-info)))
- (if (string= scope "global")
- (progn
- (setq gptel-backend backend)
- (setq gptel-model model)
- (message "Changed to %s model: %s (global)" backend-name model))
- (setq-local gptel-backend backend)
- (setq-local gptel-model (if (stringp model) (intern model) model))
- (message "Changed to %s model: %s (buffer-local)" backend-name model)))))
-
-(defun cj/gptel-switch-backend ()
- "Switch the GPTel backend and then choose one of its models."
- (interactive)
- (let* ((backends (cj/gptel--available-backends))
- (choice (completing-read "Select GPTel backend: " (mapcar #'car backends) nil t))
- (backend (cdr (assoc choice backends))))
- (unless backend
- (user-error "Invalid GPTel backend: %s" choice))
- (let* ((models (when (fboundp 'gptel-backend-models)
- (gptel-backend-models backend)))
- (model (completing-read (format "Select %s model: " choice)
- (mapcar #'cj/gptel--model-to-string models)
- nil t nil nil (cj/gptel--model-to-string (bound-and-true-p gptel-model)))))
- (setq gptel-backend backend
- gptel-model (cj/gptel--model-to-symbol model))
- (message "Switched to %s with model: %s" choice model))))
-
-;; Clear assistant buffer (moved out so it's always available)
-(defun cj/gptel-clear-buffer ()
- "Erase the current GPTel buffer while preserving the initial Org heading.
-Operate only when `gptel-mode' is active in an Org buffer so the heading
-can be reinserted."
- (interactive)
- (let ((is-gptel (bound-and-true-p gptel-mode))
- (is-org (derived-mode-p 'org-mode)))
- (if (and is-gptel is-org)
- (progn
- (erase-buffer)
- (when (fboundp 'cj/gptel--fresh-org-prefix)
- (insert (cj/gptel--fresh-org-prefix)))
- (message "GPTel buffer cleared and heading reset"))
- (message "Not a GPTel buffer in org-mode. Nothing cleared."))))
-
-;; ----------------------------- Context Management ----------------------------
-
-(defun cj/gptel--add-file-to-context (file-path)
- "Add FILE-PATH to the GPTel context.
-Returns t on success, nil on failure.
-Provides consistent user feedback about the context state."
- (when (and file-path (file-exists-p file-path))
- (gptel-add-file file-path)
- (let ((context-count (if (boundp 'gptel-context--alist)
- (length gptel-context--alist)
- 0)))
- (message "Added %s to GPTel context (%d sources total)"
- (file-name-nondirectory file-path)
- context-count))
- t))
-
-(defun cj/gptel-add-file ()
- "Add a file to the GPTel context.
-If inside a Projectile project, prompt from that project's file list.
-Otherwise, prompt with `read-file-name'."
- (interactive)
- (let* ((in-proj (and (featurep 'projectile)
- (fboundp 'projectile-project-p)
- (projectile-project-p)))
- (file-name (if in-proj
- (let ((cands (projectile-current-project-files)))
- (if (fboundp 'projectile-completing-read)
- (projectile-completing-read "GPTel add file: " cands)
- (completing-read "GPTel add file: " cands nil t)))
- (read-file-name "GPTel add file: ")))
- (file-path (if in-proj
- (expand-file-name file-name (projectile-project-root))
- file-name)))
- (unless (cj/gptel--add-file-to-context file-path)
- (error "Failed to add file: %s" file-path))))
-
-(defun cj/gptel-add-buffer-file ()
- "Select a buffer and add its associated file to the GPTel context.
-Lists all open buffers for selection. If the selected buffer is visiting
-a file, that file is added to the GPTel context. Otherwise, an error
-message is displayed."
- (interactive)
- (let* ((buffers (mapcar #'buffer-name (buffer-list)))
- (selected-buffer-name (completing-read "Add file from buffer: " buffers nil t))
- (selected-buffer (get-buffer selected-buffer-name))
- (file-path (and selected-buffer
- (buffer-file-name selected-buffer))))
- (if file-path
- (cj/gptel--add-file-to-context file-path)
- (message "Buffer '%s' is not visiting a file" selected-buffer-name))))
-
-(defun cj/gptel-add-this-buffer ()
- "Add the current buffer to the GPTel context.
-Works for any buffer, whether it's visiting a file or not."
- (interactive)
- ;; Load gptel-context if needed
- (unless (featurep 'gptel-context)
- (require 'gptel-context))
- ;; Use gptel-add with prefix arg '(4) to add current buffer
- (gptel-add '(4))
- (message "Added buffer '%s' to GPTel context" (buffer-name)))
-
-;;; -------------------------- Org Header Construction --------------------------
-
-(defun cj/gptel--fresh-org-prefix ()
- "Generate a fresh org-mode header with current timestamp for user messages."
- (concat "* " user-login-name " " (format-time-string "[%Y-%m-%d %H:%M:%S]") "\n"))
-
-(defun cj/gptel--refresh-org-prefix (&rest _)
- "Update the org-mode prefix with fresh timestamp before sending message."
- (setf (alist-get 'org-mode gptel-prompt-prefix-alist)
- (cj/gptel--fresh-org-prefix)))
-
-(defun cj/gptel-backend-and-model ()
- "Return backend, model, and timestamp as a single string."
- (let* ((backend (pcase (bound-and-true-p gptel-backend)
- ((and v (pred vectorp)) (aref v 1))
- (_ "AI")))
- (model (format "%s" (or (bound-and-true-p gptel-model) "")))
- (ts (format-time-string "[%Y-%m-%d %H:%M:%S]")))
- (format "%s: %s %s" backend model ts)))
-
-(defun cj/gptel-insert-model-heading (response-begin-pos _response-end-pos)
- "Insert an Org heading for the AI reply at RESPONSE-BEGIN-POS."
- (save-excursion
- (goto-char response-begin-pos)
- (insert (format "* %s\n" (cj/gptel-backend-and-model)))))
-
-;;; ---------------------------- GPTel Configuration ----------------------------
-
-(use-package gptel
- :load-path "~/code/gptel"
- :ensure nil
- :defer t
- :commands (gptel gptel-send gptel-menu)
- :bind
- (:map gptel-mode-map
- ("C-<return>" . gptel-send))
- :custom
- (gptel-default-mode 'org-mode)
- (gptel-expert-commands t)
- (gptel-track-media t)
- ;; Options: t (include + resend), 'ignore (show but don't resend),
- ;; nil (discard), or a buffer name to redirect reasoning to
- (gptel-include-reasoning "*AI-Reasoning*")
- (gptel-log-level 'info)
- (gptel--debug nil)
- :config
- (cj/ensure-gptel-backends)
- ;; Set ChatGPT (gpt-5.5) as default after initialization. Model
- ;; must be a symbol -- gptel's modeline-display code calls `symbolp'
- ;; on it and signals `wrong-type-argument' otherwise.
- (setq gptel-backend gptel-chatgpt-backend)
- (setq gptel-model 'gpt-5.5)
-
- (setq gptel-confirm-tool-calls nil) ;; allow tool access by default
-
- ;; Initialize org-mode user prefix and wire up hooks
- (setf (alist-get 'org-mode gptel-prompt-prefix-alist)
- (cj/gptel--fresh-org-prefix))
- (advice-add 'gptel-send :before #'cj/gptel--refresh-org-prefix)
- (add-hook 'gptel-post-response-functions #'cj/gptel-insert-model-heading))
-
-;;; ---------------------------- Toggle GPTel Window ----------------------------
-
-(defvar cj/ai-assistant-window-width 0.4
- "Default fraction of frame width for the *AI-Assistant* side window.
-Used until the panel is resized and toggled off this session; after that,
-the toggled-off width is remembered in `cj/--ai-assistant-width'.")
-
-(defvar cj/--ai-assistant-width nil
- "Last width fraction the *AI-Assistant* side window was toggled off at.
-nil falls back to `cj/ai-assistant-window-width'. Shared by the panel's
-entry points (toggle, load-conversation, quick-ask escalation) so the
-panel reopens at one consistent width. In-memory only -- resets each
-Emacs session.")
-
-(defun cj/toggle-gptel ()
- "Toggle the visibility of the AI-Assistant buffer, and place point at its end.
-The panel opens at `cj/ai-assistant-window-width'; once it has been resized
-and toggled off this session, it reopens at that remembered width."
- (interactive)
- (let* ((buf-name "*AI-Assistant*")
- (buffer (get-buffer buf-name))
- (win (and buffer (get-buffer-window buffer))))
- (if win
- (progn
- (cj/side-window-capture-size win 'right 'cj/--ai-assistant-width)
- (delete-window win))
- ;; Ensure GPTel and our backends are initialized before creating the buffer
- (unless (featurep 'gptel)
- (require 'gptel))
- (cj/ensure-gptel-backends)
- (unless buffer
- ;; Pass backend, not model
- (gptel buf-name gptel-backend))
- (setq buffer (get-buffer buf-name))
- (setq win
- (cj/side-window-display
- buffer 'right 'cj/--ai-assistant-width
- cj/ai-assistant-window-width))
- (select-window win)
- (with-current-buffer buffer
- (goto-char (point-max))))))
-
-;; ------------------------------- Clear Context -------------------------------
-
-(defun cj/gptel-context-clear ()
- "Clear all GPTel context sources, with compatibility across GPTel versions."
- (interactive)
- (cond
- ((fboundp 'gptel-context-remove-all)
- (call-interactively 'gptel-context-remove-all)
- (message "GPTel context cleared"))
- ((fboundp 'gptel-context-clear)
- (call-interactively 'gptel-context-clear)
- (message "GPTel context cleared"))
- ((boundp 'gptel-context--alist)
- (setq gptel-context--alist nil)
- (message "GPTel context cleared"))
- (t
- (message "No known GPTel context clearing function available"))))
-
-;;; -------------------------------- GPTel-Magit --------------------------------
-
-;; Each integration point waits on its actual dependency, not on `magit'
-;; broadly. `magit.el' calls `(provide 'magit)' BEFORE its
-;; `cl-eval-when (load eval) ...' block requires `magit-commit' and
-;; `magit-stash', so a single `with-eval-after-load 'magit' fires while
-;; the transient prefixes the wiring references are still undefined.
-;; `transient-append-suffix' silently no-ops on missing prefixes (it
-;; calls `message' unless `transient-error-on-insert-failure' is set),
-;; which is how the failure stayed invisible.
-;;
-;; Keys:
-;; M-g — generate commit message (in commit message buffer)
-;; g — generate commit (in magit-commit transient)
-;; x — explain diff (in magit-diff transient)
-
-(use-package gptel-magit
- :defer t
- :commands (gptel-magit-generate-message
- gptel-magit-commit-generate
- gptel-magit-diff-explain)
- :init
- (with-eval-after-load 'git-commit
- (define-key git-commit-mode-map (kbd "M-g") #'gptel-magit-generate-message))
- (with-eval-after-load 'magit-commit
- (transient-append-suffix 'magit-commit #'magit-commit-create
- '("g" "Generate commit" gptel-magit-commit-generate)))
- (with-eval-after-load 'magit-diff
- (transient-append-suffix 'magit-diff #'magit-stash-show
- '("x" "Explain" gptel-magit-diff-explain))))
-
-;; ------------------------------ GPTel Directives -----------------------------
-
-(use-package gptel-prompts
- :load-path (lambda () (expand-file-name "custom/" user-emacs-directory))
- :after gptel
- :if (file-exists-p (expand-file-name "custom/gptel-prompts.el" user-emacs-directory))
- :custom
- (gptel-prompts-directory (concat user-emacs-directory "ai-prompts"))
- :config
- (gptel-prompts-update)
- (gptel-prompts-add-update-watchers)
- ;; gptel--system-message is set at gptel load time, before gptel-prompts
- ;; replaces the default directive. Re-apply it now.
- (when-let* ((dir (alist-get 'default gptel-directives)))
- (setq gptel--system-message dir)))
-
-;;; --------------------------------- AI Keymap ---------------------------------
-
-(defvar-keymap cj/ai-keymap
- :doc "Keymap for gptel and other AI operations."
- "A" #'cj/gptel-autosave-toggle ;; toggle autosave on the current GPTel buffer
- "B" #'cj/gptel-switch-backend ;; change the backend (OpenAI, Anthropic, etc.
- "M" #'gptel-menu ;; gptel's transient menu
- "d" #'cj/gptel-delete-conversation ;; delete conversation
- "." #'cj/gptel-add-this-buffer ;; add buffer to context
- "f" #'cj/gptel-add-file ;; add a file to context
- "b" #'cj/gptel-browse-conversations ;; browse saved conversations
- "l" #'cj/gptel-load-conversation ;; load and continue conversation
- "m" #'cj/gptel-change-model ;; change the LLM model
- "p" #'gptel-system-prompt ;; change prompt
- "q" #'cj/gptel-quick-ask ;; one-shot quick ask
- "r" #'cj/gptel-rewrite-with-directive ;; rewrite region with a chosen directive
- "R" #'cj/gptel-rewrite-redo-with-different-directive ;; redo last rewrite, new directive
- "c" #'cj/gptel-context-clear ;; clear all context
- "s" #'cj/gptel-save-conversation ;; save conversation
- "t" #'cj/toggle-gptel ;; toggles the ai-assistant window
- "x" #'cj/gptel-clear-buffer) ;; clears the assistant buffer
-(cj/register-prefix-map "a" cj/ai-keymap)
-
-(with-eval-after-load 'which-key
- (which-key-add-key-based-replacements
- "C-; a" "AI assistant menu"
- "C-; a A" "toggle autosave"
- "C-; a B" "switch backend"
- "C-; a M" "gptel menu"
- "C-; a b" "browse conversations"
- "C-; a d" "delete conversation"
- "C-; a ." "add buffer"
- "C-; a f" "add file"
- "C-; a l" "load conversation"
- "C-; a m" "change model"
- "C-; a p" "change prompt"
- "C-; a q" "quick ask"
- "C-; a r" "rewrite region (directive)"
- "C-; a R" "redo rewrite, new directive"
- "C-; a c" "clear context"
- "C-; a s" "save conversation"
- "C-; a t" "toggle window"
- "C-; a x" "clear buffer"))
-
-(provide 'ai-config)
-;;; ai-config.el ends here.
diff --git a/modules/ai-conversations-browser.el b/modules/ai-conversations-browser.el
deleted file mode 100644
index 9f2a7de43..000000000
--- a/modules/ai-conversations-browser.el
+++ /dev/null
@@ -1,241 +0,0 @@
-;;; ai-conversations-browser.el --- Browse saved GPTel conversations -*- lexical-binding: t; coding: utf-8; -*-
-
-;; Author: Craig Jennings <c@cjennings.net>
-
-;;; Commentary:
-;; Provides `cj/gptel-browse-conversations': a dired-style buffer
-;; listing saved conversations in `cj/gptel-conversations-directory'.
-;; Each row shows date, time, topic, and a short preview of the most
-;; recent message. Single-key bindings load / delete / rename a
-;; conversation in place.
-;;
-;; RET, l Load the conversation under point
-;; d Delete the conversation under point
-;; r Rename the conversation under point (renames the file)
-;; g Refresh the listing
-;; n / p Move to next / previous row
-;; q Quit the browser window
-
-;;; Code:
-
-(require 'cl-lib)
-(require 'subr-x)
-
-(declare-function cj/gptel-load-conversation "ai-conversations" ())
-(declare-function cj/gptel--slugify-topic "ai-conversations" (s))
-(declare-function cj/gptel--timestamp-from-filename "ai-conversations" (filename))
-
-(defcustom cj/gptel-browser-preview-length 60
- "Number of preview characters shown per row in the browser."
- :type 'integer
- :group 'cj/ai-conversations)
-
-(defconst cj/gptel-browser--buffer-name "*GPTel-Conversations*"
- "Buffer name for the saved-conversations browser.")
-
-(defvar-keymap cj/gptel-browser-mode-map
- :doc "Keymap for `cj/gptel-browser-mode'."
- "RET" #'cj/gptel-browser-load
- "l" #'cj/gptel-browser-load
- "d" #'cj/gptel-browser-delete
- "r" #'cj/gptel-browser-rename
- "g" #'cj/gptel-browser-refresh
- "n" #'next-line
- "p" #'previous-line
- "q" #'quit-window)
-
-(define-derived-mode cj/gptel-browser-mode special-mode "GPTel-Browser"
- "Major mode for browsing saved GPTel conversations."
- (setq-local truncate-lines t))
-
-;; -------------------------- helpers (pure where possible)
-
-(defun cj/gptel-browser--topic-from-filename (filename)
- "Return the topic slug from FILENAME, or nil if it isn't a gptel file."
- (when (string-match "\\`\\(.+\\)_[0-9]\\{8\\}-[0-9]\\{6\\}\\.gptel\\'" filename)
- (match-string 1 filename)))
-
-(defun cj/gptel-browser--strip-headers (text)
- "Drop the org #+STARTUP / #+VISIBILITY headers from TEXT and return the rest."
- (let ((s text))
- (while (string-match "\\`#\\+\\(STARTUP\\|VISIBILITY\\):.*\n" s)
- (setq s (substring s (match-end 0))))
- (while (and (> (length s) 0) (eq (aref s 0) ?\n))
- (setq s (substring s 1)))
- s))
-
-(defun cj/gptel-browser--last-message (text)
- "Return a short preview of the last user/AI message in TEXT.
-Returns the empty string when no message body is present."
- (let* ((stripped (cj/gptel-browser--strip-headers text))
- ;; Last org-mode top-level heading body, or the whole text if
- ;; there isn't one.
- (body (if (string-match "\\`\\*+[^\n]*\n\\(\\(?:.\\|\n\\)*\\)\\'" stripped)
- (let* ((all-text stripped)
- ;; Walk backward to find the last '* ' or '** ' heading
- (idx (or (cl-loop for i from (1- (length all-text)) downto 0
- when (and (or (zerop i)
- (eq (aref all-text (1- i)) ?\n))
- (eq (aref all-text i) ?*))
- return i)
- 0)))
- (substring all-text idx))
- stripped)))
- ;; Drop the heading line itself, then collapse whitespace.
- (when (string-match "\\`\\*+[^\n]*\n" body)
- (setq body (substring body (match-end 0))))
- (setq body (replace-regexp-in-string "[\n\t ]+" " " body))
- (string-trim body)))
-
-(defun cj/gptel-browser--preview (text length)
- "Return a LENGTH-char preview from TEXT, ellipsized when truncated."
- (let* ((line (cj/gptel-browser--last-message text))
- (max-len (max 1 length)))
- (cond
- ((string-empty-p line) "")
- ((> (length line) max-len)
- (concat (substring line 0 (1- max-len)) "…"))
- (t line))))
-
-(defun cj/gptel-browser--row-for-file (file dir)
- "Return a propertized row string for FILE under DIR, or nil."
- (let* ((filename (file-name-nondirectory file))
- (topic (cj/gptel-browser--topic-from-filename filename))
- (ts (and topic (cj/gptel--timestamp-from-filename filename))))
- (when (and topic ts)
- (let* ((preview (with-temp-buffer
- (ignore-errors (insert-file-contents file))
- (cj/gptel-browser--preview
- (buffer-string) cj/gptel-browser-preview-length)))
- (row (format "%s %-22s %s"
- (format-time-string "%Y-%m-%d %H:%M" ts)
- topic preview)))
- (propertize row
- 'cj/gptel-browser-file filename
- 'cj/gptel-browser-topic topic)))))
-
-(defun cj/gptel-browser--rows ()
- "Return propertized row strings for every conversation in the directory."
- (when (and (boundp 'cj/gptel-conversations-directory)
- (file-directory-p cj/gptel-conversations-directory))
- (let ((dir cj/gptel-conversations-directory))
- (delq nil
- (mapcar (lambda (f) (cj/gptel-browser--row-for-file f dir))
- (directory-files dir t "\\.gptel\\'"))))))
-
-(defun cj/gptel-browser--render ()
- "Replace the current buffer's contents with the conversation listing.
-Sort newest first."
- (let ((inhibit-read-only t)
- (rows (sort (cj/gptel-browser--rows)
- (lambda (a b)
- (string> (substring-no-properties a 0 16)
- (substring-no-properties b 0 16))))))
- (erase-buffer)
- (insert (propertize
- "Saved GPTel conversations -- RET/l load d delete r rename g refresh q quit\n\n"
- 'face 'header-line))
- (cond
- ((null rows)
- (insert " (no saved conversations)\n"))
- (t
- (dolist (row rows)
- (insert row "\n"))))
- (goto-char (point-min))
- (forward-line 2)))
-
-;; -------------------------- entry point
-
-;;;###autoload
-(defun cj/gptel-browse-conversations ()
- "Open the saved GPTel conversations browser."
- (interactive)
- (let ((buf (get-buffer-create cj/gptel-browser--buffer-name)))
- (with-current-buffer buf
- (cj/gptel-browser-mode)
- (cj/gptel-browser--render))
- (pop-to-buffer buf)))
-
-(defun cj/gptel-browser-refresh ()
- "Re-read the conversations directory and refresh the browser."
- (interactive)
- (cj/gptel-browser--render))
-
-;; -------------------------- row-level actions
-
-(defun cj/gptel-browser--filename-at-point ()
- "Return the conversation filename on the current line, or nil."
- (get-text-property (line-beginning-position) 'cj/gptel-browser-file))
-
-(defun cj/gptel-browser--filepath-at-point ()
- "Return the absolute filepath for the row at point, or nil."
- (when-let ((filename (cj/gptel-browser--filename-at-point)))
- (expand-file-name filename cj/gptel-conversations-directory)))
-
-(defun cj/gptel-browser-load ()
- "Load the conversation on the current row via `cj/gptel-load-conversation'.
-The browser is buried after the load fires."
- (interactive)
- (let ((filepath (cj/gptel-browser--filepath-at-point)))
- (unless filepath
- (user-error "No conversation on this line"))
- (let ((filename (file-name-nondirectory filepath)))
- ;; Stand in for cj/gptel-load-conversation's completing-read so
- ;; the user doesn't get prompted twice.
- (cl-letf (((symbol-function 'completing-read)
- (lambda (_p cands &rest _)
- (or (car (cl-find filename cands
- :key (lambda (c) (cdr c))
- :test #'equal))
- (caar cands))))
- ((symbol-function 'y-or-n-p) (lambda (&rest _) nil)))
- (cj/gptel-load-conversation)))
- (quit-window)))
-
-(defun cj/gptel-browser-delete ()
- "Delete the conversation file on the current row, after confirmation."
- (interactive)
- (let ((filepath (cj/gptel-browser--filepath-at-point)))
- (unless filepath
- (user-error "No conversation on this line"))
- (let ((filename (file-name-nondirectory filepath)))
- (when (y-or-n-p (format "Delete %s? " filename))
- (delete-file filepath)
- (message "Deleted %s" filename)
- (cj/gptel-browser--render)))))
-
-(defun cj/gptel-browser--rename-target (filepath new-topic)
- "Compute the renamed FILEPATH for NEW-TOPIC, preserving the timestamp.
-NEW-TOPIC is slugified. Returns the new absolute filepath."
- (let* ((dir (file-name-directory filepath))
- (filename (file-name-nondirectory filepath))
- (timestamp (and (string-match "_\\([0-9]\\{8\\}-[0-9]\\{6\\}\\)\\.gptel\\'"
- filename)
- (match-string 1 filename)))
- (slug (cj/gptel--slugify-topic new-topic)))
- (unless timestamp
- (error "Cannot extract timestamp from filename: %s" filename))
- (expand-file-name (format "%s_%s.gptel" slug timestamp) dir)))
-
-(defun cj/gptel-browser-rename ()
- "Rename the conversation file on the current row, preserving its timestamp."
- (interactive)
- (let ((filepath (cj/gptel-browser--filepath-at-point)))
- (unless filepath
- (user-error "No conversation on this line"))
- (let* ((old (file-name-nondirectory filepath))
- (current-topic (cj/gptel-browser--topic-from-filename old))
- (new-topic (read-string
- (format "New topic (was %s): " current-topic)
- current-topic))
- (target (cj/gptel-browser--rename-target filepath new-topic)))
- (when (equal target filepath)
- (user-error "Topic unchanged"))
- (when (file-exists-p target)
- (user-error "Target already exists: %s" (file-name-nondirectory target)))
- (rename-file filepath target)
- (message "Renamed to %s" (file-name-nondirectory target))
- (cj/gptel-browser--render))))
-
-(provide 'ai-conversations-browser)
-;;; ai-conversations-browser.el ends here
diff --git a/modules/ai-conversations.el b/modules/ai-conversations.el
deleted file mode 100644
index 839af9ad3..000000000
--- a/modules/ai-conversations.el
+++ /dev/null
@@ -1,375 +0,0 @@
-;;; ai-conversations.el --- GPTel conversation persistence and autosave -*- lexical-binding: t; coding: utf-8; -*-
-;; Author: Craig Jennings <c@cjennings.net>
-;; Maintainer: Craig Jennings <c@cjennings.net>
-;; Version 0.1
-;; Package-Requires: ((emacs "27.1"))
-;; Keywords: convenience, tools
-;;
-;;; Commentary:
-;; Provides conversation save/load/delete, autosave after responses, and
-;; org-visibility headers for GPTel-powered assistant buffers.
-;;
-;; Loads lazily via autoloads for the interactive entry points.
-
-;;; Code:
-
-(require 'cj-window-toggle-lib) ;; cj/side-window-display
-
-;; Shared *AI-Assistant* remembered-width state, owned by ai-config.el.
-;; Forward-declared so loading a conversation reopens the panel at the same
-;; width as the F-key toggle without a circular require.
-(defvar cj/--ai-assistant-width)
-
-(defgroup cj/ai-conversations nil
- "Conversation persistence for GPTel (save/load/delete, autosave)."
- :group 'gptel
- :prefix "cj/")
-
-(defcustom cj/gptel-conversations-directory
- (expand-file-name "ai-conversations" user-emacs-directory)
- "Directory where GPTel conversations are stored."
- :type 'directory
- :group 'cj/ai-conversations)
-
-(defcustom cj/gptel-conversations-window-side 'right
- "Side to display the AI-Assistant buffer when loading a conversation."
- :type '(choice (const :tag "Right" right)
- (const :tag "Left" left)
- (const :tag "Bottom" bottom)
- (const :tag "Top" top))
- :group 'cj/ai-conversations)
-
-(defcustom cj/gptel-conversations-window-width 0.4
- "Set the side window width when loading a conversation.
-
-If displaying on the top or bottom, treat this value as a height fraction."
- :type 'number
- :group 'cj/ai-conversations)
-
-(defcustom cj/gptel-conversations-sort-order 'newest-first
- "Sort order for conversation selection prompts."
- :type '(choice (const :tag "Newest first" newest-first)
- (const :tag "Oldest first" oldest-first))
- :group 'cj/ai-conversations)
-
-(defvar-local cj/gptel-autosave-enabled nil
- "Non-nil means auto-save after each AI response in GPTel buffers.")
-
-(defvar-local cj/gptel-autosave-filepath nil
- "File path used for auto-saving the conversation buffer.")
-
-(defvar-local cj/gptel-autosave--timer nil
- "Repeating timer used to auto-save the current GPTel buffer.")
-
-(defcustom cj/gptel-autosave-interval 60
- "Seconds between periodic GPTel conversation autosaves."
- :type 'number
- :group 'cj/ai-conversations)
-
-(defvar cj/gptel-autosave-mode-line-format
- '(:eval (when (bound-and-true-p cj/gptel-autosave-enabled) " [AS]"))
- "Mode-line construct that surfaces autosave state in GPTel buffers.")
-(put 'cj/gptel-autosave-mode-line-format 'risky-local-variable t)
-
-(defun cj/gptel--autosave-active-p ()
- "Return non-nil when the current buffer has an autosave target."
- (and (bound-and-true-p gptel-mode)
- cj/gptel-autosave-enabled
- (stringp cj/gptel-autosave-filepath)
- (> (length cj/gptel-autosave-filepath) 0)))
-
-(defun cj/gptel--autosave-stop-timer ()
- "Cancel the current buffer's periodic autosave timer, if any."
- (when cj/gptel-autosave--timer
- (cancel-timer cj/gptel-autosave--timer)
- (setq-local cj/gptel-autosave--timer nil)))
-
-(defun cj/gptel--autosave-timer-callback (buffer)
- "Auto-save BUFFER from a periodic timer when autosave is still active."
- (when (buffer-live-p buffer)
- (with-current-buffer buffer
- (if (cj/gptel--autosave-active-p)
- (condition-case err
- (cj/gptel--save-buffer-to-file (current-buffer) cj/gptel-autosave-filepath)
- (error (message "cj/gptel periodic autosave failed: %s"
- (error-message-string err))))
- (cj/gptel--autosave-stop-timer)))))
-
-(defun cj/gptel--autosave-start-timer ()
- "Start the current buffer's periodic autosave timer when autosave is active."
- (when (and (cj/gptel--autosave-active-p)
- (not cj/gptel-autosave--timer))
- (setq-local cj/gptel-autosave--timer
- (run-with-timer cj/gptel-autosave-interval
- cj/gptel-autosave-interval
- #'cj/gptel--autosave-timer-callback
- (current-buffer)))))
-
-(defun cj/gptel-autosave-toggle ()
- "Toggle autosave on/off in the current GPTel buffer.
-Flips `cj/gptel-autosave-enabled' and forces a mode-line redisplay so
-the [AS] indicator updates immediately. When turning autosave ON
-without a configured filepath, prompt to save the conversation first
-so a path exists to autosave to."
- (interactive)
- (unless (bound-and-true-p gptel-mode)
- (user-error "Not a GPTel buffer"))
- (if cj/gptel-autosave-enabled
- (progn
- (setq-local cj/gptel-autosave-enabled nil)
- (cj/gptel--autosave-stop-timer)
- (message "Autosave disabled"))
- (cond
- ((and (stringp cj/gptel-autosave-filepath)
- (> (length cj/gptel-autosave-filepath) 0))
- (setq-local cj/gptel-autosave-enabled t)
- (cj/gptel--autosave-start-timer)
- (message "Autosave enabled (saving to %s)"
- (file-name-nondirectory cj/gptel-autosave-filepath)))
- ((y-or-n-p "No save target yet. Save conversation first? ")
- (call-interactively #'cj/gptel-save-conversation))
- (t
- (message "Autosave not enabled (no save target)"))))
- (force-mode-line-update))
-
-(defcustom cj/gptel-conversations-autosave-on-send t
- "Non-nil means auto-save the conversation immediately after `gptel-send'."
- :type 'boolean
- :group 'cj/ai-conversations)
-
-(defun cj/gptel--autosave-after-send (&rest _args)
- "Auto-save current GPTel buffer right after `gptel-send' if enabled."
- (when (and cj/gptel-conversations-autosave-on-send
- (bound-and-true-p gptel-mode)
- cj/gptel-autosave-enabled
- (stringp cj/gptel-autosave-filepath)
- (> (length cj/gptel-autosave-filepath) 0))
- (condition-case err
- (cj/gptel--save-buffer-to-file (current-buffer) cj/gptel-autosave-filepath)
- (error (message "cj/gptel autosave-on-send failed: %s" (error-message-string err))))))
-
-(with-eval-after-load 'gptel
- (unless (advice-member-p #'cj/gptel--autosave-after-send #'gptel-send)
- (advice-add 'gptel-send :after #'cj/gptel--autosave-after-send)))
-
-(defun cj/gptel--install-autosave-mode-line ()
- "Add the [AS] autosave indicator to the current buffer's mode-line.
-Idempotent: re-running in the same buffer does not duplicate the
-construct."
- (unless (member 'cj/gptel-autosave-mode-line-format mode-line-format)
- (setq-local mode-line-format
- (append mode-line-format
- (list 'cj/gptel-autosave-mode-line-format)))))
-
-(defun cj/gptel--install-autosave-buffer-hooks ()
- "Install buffer-local cleanup hooks for GPTel autosave."
- (add-hook 'kill-buffer-hook #'cj/gptel--autosave-stop-timer nil t))
-
-(with-eval-after-load 'gptel
- (add-hook 'gptel-mode-hook #'cj/gptel--install-autosave-mode-line)
- (add-hook 'gptel-mode-hook #'cj/gptel--install-autosave-buffer-hooks))
-
-(defun cj/gptel--slugify-topic (s)
- "Return a filesystem-friendly slug for topic string S."
- (let* ((down (downcase (or s "")))
- (repl (replace-regexp-in-string "[^a-z0-9]+" "-" down))
- (trim (replace-regexp-in-string "^-+\\|-+$" "" repl)))
- (or (and (> (length trim) 0) trim) "conversation")))
-
-(defun cj/gptel--existing-topics ()
- "Return topic slugs, without timestamps, present in the conversations directory."
- (when (file-exists-p cj/gptel-conversations-directory)
- (let* ((files (directory-files cj/gptel-conversations-directory nil "\\.gptel$")))
- (delete-dups
- (mapcar
- (lambda (f)
- (replace-regexp-in-string "_[0-9]\\{8\\}-[0-9]\\{6\\}\\.gptel$" "" f))
- files)))))
-
-(defun cj/gptel--latest-file-for-topic (topic-slug)
- "Return the newest saved conversation filename for TOPIC-SLUG, or nil."
- (let* ((rx (format "^%s_[0-9]\\{8\\}-[0-9]\\{6\\}\\.gptel$"
- (regexp-quote topic-slug)))
- (files (and (file-exists-p cj/gptel-conversations-directory)
- (directory-files cj/gptel-conversations-directory nil rx))))
- (car (sort files #'string>))))
-
-(defun cj/gptel--timestamp-from-filename (filename)
- "Return an Emacs timestamp extracted from FILENAME, or nil.
-
-Expect FILENAME to match _YYYYMMDD-HHMMSS.gptel."
- (when (string-match "_\\([0-9]\\{8\\}\\)-\\([0-9]\\{6\\}\\)\\.gptel\\'" filename)
- (let* ((date (match-string 1 filename))
- (time (match-string 2 filename))
- (Y (string-to-number (substring date 0 4)))
- (M (string-to-number (substring date 4 6)))
- (D (string-to-number (substring date 6 8)))
- (h (string-to-number (substring time 0 2)))
- (m (string-to-number (substring time 2 4)))
- (s (string-to-number (substring time 4 6))))
- (encode-time s m h D M Y))))
-
-(defun cj/gptel--conversation-candidates ()
- "Return conversation candidates sorted per `cj/gptel-conversations-sort-order'."
- (unless (file-exists-p cj/gptel-conversations-directory)
- (user-error "Conversations directory doesn't exist: %s" cj/gptel-conversations-directory))
- (let* ((files (directory-files cj/gptel-conversations-directory nil "\\.gptel$"))
- (enriched
- (mapcar
- (lambda (f)
- (let* ((full (expand-file-name f cj/gptel-conversations-directory))
- (ptime (or (cj/gptel--timestamp-from-filename f)
- (nth 5 (file-attributes full))))
- (disp (format "%s [%s]" f (format-time-string "%Y-%m-%d %H:%M" ptime))))
- (list :file f :time ptime :display disp)))
- files))
- (sorted
- (sort enriched
- (lambda (a b)
- (let ((ta (plist-get a :time))
- (tb (plist-get b :time)))
- (if (eq cj/gptel-conversations-sort-order 'newest-first)
- (time-less-p tb ta) ;; tb earlier than ta => a first
- (time-less-p ta tb))))))
- (cands (mapcar (lambda (pl)
- (cons (plist-get pl :display)
- (plist-get pl :file)))
- sorted)))
- cands))
-
-(defun cj/gptel--save-buffer-to-file (buffer filepath)
- "Save BUFFER content to FILEPATH with Org visibility properties."
- (with-current-buffer buffer
- (let ((content (buffer-string)))
- (with-temp-buffer
- (insert "#+STARTUP: showeverything\n")
- (insert "#+VISIBILITY: all\n\n")
- (insert content)
- (write-region (point-min) (point-max) filepath nil 'silent))))
- filepath)
-
-(defun cj/gptel--ensure-ai-buffer ()
- "Return the *AI-Assistant* buffer, creating it via `gptel' if needed."
- (let* ((buf-name "*AI-Assistant*")
- (buffer (get-buffer buf-name)))
- (unless buffer
- (gptel buf-name))
- (or (get-buffer buf-name)
- (user-error "Could not create or find *AI-Assistant* buffer"))))
-
-(defun cj/gptel-save-conversation ()
- "Save the current AI-Assistant buffer to a .gptel file.
-
-Enable autosave for subsequent AI responses to the same file."
- (interactive)
- (let ((buf (get-buffer "*AI-Assistant*")))
- (unless buf
- (user-error "No AI-Assistant buffer found"))
- (unless (file-exists-p cj/gptel-conversations-directory)
- (make-directory cj/gptel-conversations-directory t)
- (message "Created directory: %s" cj/gptel-conversations-directory))
- (let* ((topics (or (cj/gptel--existing-topics) '()))
- (input (completing-read "Conversation topic: " topics nil nil))
- (topic-slug (cj/gptel--slugify-topic input))
- (latest (cj/gptel--latest-file-for-topic topic-slug))
- (use-existing (and latest
- (y-or-n-p (format "Update existing file %s? " latest))))
- (filepath (if use-existing
- (expand-file-name latest cj/gptel-conversations-directory)
- (let* ((timestamp (format-time-string "%Y%m%d-%H%M%S"))
- (filename (format "%s_%s.gptel" topic-slug timestamp)))
- (expand-file-name filename cj/gptel-conversations-directory)))))
- (cj/gptel--save-buffer-to-file buf filepath)
- (with-current-buffer buf
- (setq-local cj/gptel-autosave-filepath filepath)
- (setq-local cj/gptel-autosave-enabled t)
- (cj/gptel--autosave-start-timer))
- (message "Conversation saved to: %s" filepath))))
-
-(defun cj/gptel-delete-conversation ()
- "Delete a saved GPTel conversation file (chronologically sorted candidates)."
- (interactive)
- (unless (file-exists-p cj/gptel-conversations-directory)
- (user-error "Conversations directory doesn't exist: %s" cj/gptel-conversations-directory))
- (let* ((cands (cj/gptel--conversation-candidates)))
- (unless cands
- (user-error "No saved conversations found in %s" cj/gptel-conversations-directory))
- (let* ((completion-extra-properties '(:display-sort-function identity
- :cycle-sort-function identity))
- (selection (completing-read "Delete conversation: " cands nil t))
- (filename (cdr (assoc selection cands)))
- (filepath (and filename
- (expand-file-name filename cj/gptel-conversations-directory))))
- (unless filename
- (user-error "No conversation selected"))
- (when (y-or-n-p (format "Really delete %s? " filename))
- (delete-file filepath)
- (message "Deleted conversation: %s" filename)))))
-
-(defun cj/gptel--strip-visibility-headers ()
- "Strip org visibility headers at the top of the current buffer if present."
- (save-excursion
- (goto-char (point-min))
- (while (looking-at "^#\\+\\(STARTUP\\|VISIBILITY\\):.*\n")
- (delete-region (match-beginning 0) (match-end 0)))
- (when (looking-at "^\n+")
- (delete-region (point) (match-end 0)))))
-
-(defun cj/gptel-load-conversation ()
- "Load a saved GPTel conversation into the AI-Assistant buffer.
-
-Prompt to save the current conversation first when appropriate, then
-enable autosave."
- (interactive)
- (let ((ai-buffer (get-buffer-create "*AI-Assistant*")))
- (when (and (with-current-buffer ai-buffer (> (buffer-size) 0))
- (with-current-buffer ai-buffer (bound-and-true-p gptel-mode)))
- (when (y-or-n-p "Save current conversation before loading new one? ")
- (with-current-buffer ai-buffer
- (call-interactively #'cj/gptel-save-conversation)))))
- (unless (file-exists-p cj/gptel-conversations-directory)
- (user-error "Conversations directory doesn't exist: %s" cj/gptel-conversations-directory))
- (let* ((cands (cj/gptel--conversation-candidates)))
- (unless cands
- (user-error "No saved conversations found in %s" cj/gptel-conversations-directory))
- (let* ((completion-extra-properties '(:display-sort-function identity
- :cycle-sort-function identity))
- (selection (completing-read "Load conversation: " cands nil t))
- (filename (cdr (assoc selection cands)))
- (filepath (and filename
- (expand-file-name filename cj/gptel-conversations-directory))))
- (unless filename
- (user-error "No conversation selected"))
- (with-current-buffer (cj/gptel--ensure-ai-buffer)
- (erase-buffer)
- (insert-file-contents filepath)
- (cj/gptel--strip-visibility-headers)
- (goto-char (point-max))
- (set-buffer-modified-p t)
- (setq-local cj/gptel-autosave-filepath filepath)
- (setq-local cj/gptel-autosave-enabled t)
- (cj/gptel--autosave-start-timer))
- (let ((buf (get-buffer "*AI-Assistant*")))
- (unless (get-buffer-window buf)
- (cj/side-window-display
- buf cj/gptel-conversations-window-side
- 'cj/--ai-assistant-width cj/gptel-conversations-window-width)))
- (select-window (get-buffer-window "*AI-Assistant*"))
- (message "Loaded conversation from: %s" filepath))))
-
-(defun cj/gptel--autosave-after-response (&rest _args)
- "Auto-save the current GPTel buffer when enabled."
- (when (and (bound-and-true-p gptel-mode)
- cj/gptel-autosave-enabled
- (stringp cj/gptel-autosave-filepath)
- (> (length cj/gptel-autosave-filepath) 0))
- (condition-case err
- (cj/gptel--save-buffer-to-file (current-buffer) cj/gptel-autosave-filepath)
- (error (message "cj/gptel autosave failed: %s" (error-message-string err))))))
-
-(with-eval-after-load 'gptel
- (unless (member #'cj/gptel--autosave-after-response gptel-post-response-functions)
- (add-hook 'gptel-post-response-functions #'cj/gptel--autosave-after-response)))
-
-(provide 'ai-conversations)
-;;; ai-conversations.el ends here
diff --git a/modules/ai-mcp.el b/modules/ai-mcp.el
deleted file mode 100644
index 510805be4..000000000
--- a/modules/ai-mcp.el
+++ /dev/null
@@ -1,416 +0,0 @@
-;;; ai-mcp.el --- MCP server integration for GPTel -*- lexical-binding: t; coding: utf-8; -*-
-;; Author: Craig Jennings <c@cjennings.net>
-;; Maintainer: Craig Jennings <c@cjennings.net>
-;; Version 0.1
-;; Package-Requires: ((emacs "30.1") (mcp "0.1.0") (gptel "0.9.8"))
-;; Keywords: convenience, tools, ai
-;;
-;;; Commentary:
-;; Wires mcp.el's MCP server inventory into GPTel. GPTel agents gain
-;; access to the MCP servers Claude Code already uses (linear, notion,
-;; figma, slack-deepsat, drawio, google-calendar, google-docs-personal,
-;; google-docs-work, google-keep), with write-confirmation gating and a
-;; doctor for diagnosing prerequisites.
-;;
-;; Design doc: docs/specs/mcp-el-gptel-integration-spec-doing.org
-;;
-;; File organization (seven sections, populated by phases):
-;; 1. Constants and defcustoms <- this phase
-;; 2. Public commands <- later phase
-;; 3. Pure helpers <- this phase
-;; 4. mcp.el compatibility layer <- later phase
-;; 5. Registration pipeline <- later phase
-;; 6. Async state machine <- later phase
-;; 7. UI <- later phase
-
-;;; Code:
-
-(require 'cl-lib)
-(require 'json)
-
-;;;; --- 1. Constants and defcustoms -----------------------------------
-
-(defgroup cj/ai-mcp nil
- "MCP server integration for GPTel."
- :group 'gptel
- :prefix "cj/")
-
-(defcustom cj/mcp-claude-config
- (expand-file-name "~/.claude.json")
- "Path to the Claude Code config that holds MCP server env vars.
-The config is read at server-spawn time and cached by mtime."
- :type 'file
- :group 'cj/ai-mcp)
-
-(defconst cj/mcp-server-specs
- '((:name "linear"
- :transport http
- :url "https://mcp.linear.app/mcp"
- :auth in-protocol
- :risk write-capable)
- (:name "notion"
- :transport http
- :url "https://mcp.notion.com/mcp"
- :auth in-protocol
- :risk write-capable)
- (:name "figma"
- :transport stdio
- :command "npx"
- :args ("-y" "figma-developer-mcp" "--stdio")
- :secret-args ("--figma-api-key" :figma-api-key)
- :auth args-token
- :risk arg-leak)
- (:name "slack-deepsat"
- :transport sse
- :url "http://127.0.0.1:13080/sse"
- :auth local
- :risk write-capable)
- (:name "drawio"
- :transport stdio
- :command "npx"
- :args ("-y" "@drawio/mcp")
- :auth none
- :risk none)
- (:name "google-calendar"
- :transport stdio
- :command "npx"
- :args ("-y" "@cocal/google-calendar-mcp")
- :env (:GOOGLE_OAUTH_CREDENTIALS t)
- :auth oauth
- :risk write-capable)
- (:name "google-docs-personal"
- :transport stdio
- :command "npx"
- :args ("-y" "@a-bonus/google-docs-mcp")
- :env (:GOOGLE_CLIENT_ID t :GOOGLE_CLIENT_SECRET t :GOOGLE_MCP_PROFILE t)
- :auth oauth
- :risk write-capable)
- (:name "google-docs-work"
- :transport stdio
- :command "npx"
- :args ("-y" "@a-bonus/google-docs-mcp")
- :env (:GOOGLE_CLIENT_ID t :GOOGLE_CLIENT_SECRET t :GOOGLE_MCP_PROFILE t)
- :auth oauth
- :risk write-capable)
- (:name "google-keep"
- :transport stdio
- :command "uvx"
- :args ("--from" "keep-mcp" "python" "-m" "server.cli")
- :env (:GOOGLE_EMAIL t :GOOGLE_MASTER_TOKEN t)
- :auth token
- :risk write-capable))
- "Static, secret-free description of the MCP servers we wire to GPTel.
-Each entry is a plist describing one server. `:env' values are
-placeholders (t) replaced at spawn time from `cj/mcp-claude-config'.
-`:secret-args' (e.g. for figma) names the flag whose value is pulled
-from the Claude config's args at spawn time.")
-
-(defcustom cj/mcp-enabled-servers
- (mapcar (lambda (s) (plist-get s :name)) cj/mcp-server-specs)
- "List of MCP server names to start.
-Defaults to every server in `cj/mcp-server-specs'. Set to a
-shorter list to disable specific servers without editing the
-spec. Changes take effect on next `cj/mcp-restart-failed' or
-Emacs restart."
- :type '(repeat string)
- :group 'cj/ai-mcp)
-
-(defcustom cj/mcp-start-on-entry-points
- '(toggle-gptel)
- "GPTel entry points that trigger MCP startup.
-Symbols correspond to commands: `toggle-gptel', `gptel-send',
-`gptel-quick-ask', `gptel-rewrite-with-directive',
-`gptel-magit-generate-message'. Default: only full chat
-\(`toggle-gptel')."
- :type '(repeat symbol)
- :group 'cj/ai-mcp)
-
-(defcustom cj/mcp-startup-timeout 30
- "Seconds before a still-starting MCP server is marked failed."
- :type 'integer
- :group 'cj/ai-mcp)
-
-(defcustom cj/mcp-tool-timeout 60
- "Seconds before an in-flight MCP tool call times out."
- :type 'integer
- :group 'cj/ai-mcp)
-
-(defcustom cj/mcp-tool-confirm-overrides nil
- "Per-tool confirmation overrides.
-Alist mapping fully qualified MCP tool name (e.g.,
-\"mcp__linear__create_issue\") to t or nil. Wins over the
-pattern-based classifier in `cj/mcp--confirm-p'."
- :type '(alist :key-type string :value-type boolean)
- :group 'cj/ai-mcp)
-
-(defcustom cj/mcp-tool-audit-log-enabled t
- "When non-nil, append metadata for every MCP tool call to the audit log."
- :type 'boolean
- :group 'cj/ai-mcp)
-
-;; Classifier patterns: name prefixes that indicate read vs write.
-
-(defconst cj/mcp--write-name-patterns
- '("\\`create\\b" "\\`update\\b" "\\`delete\\b" "\\`remove\\b"
- "\\`send\\b" "\\`post\\b" "\\`add\\b" "\\`move\\b"
- "\\`invite\\b" "\\`share\\b" "\\`upload\\b" "\\`set\\b"
- "\\`patch\\b" "\\`import\\b" "\\`sync\\b" "\\`merge\\b"
- "\\`close\\b" "\\`reopen\\b" "\\`archive\\b" "\\`unarchive\\b"
- "\\`approve\\b" "\\`reject\\b" "\\`label\\b" "\\`assign\\b"
- "\\`reply\\b" "\\`comment\\b" "\\`trash\\b" "\\`restore\\b"
- "\\`pin\\b" "\\`unpin\\b" "\\`copy\\b" "\\`rename\\b")
- "Tool-name prefixes that indicate a write/mutate operation.
-Matched after the `mcp__SERVER__' prefix is stripped.")
-
-(defconst cj/mcp--read-name-patterns
- '("\\`get\\b" "\\`list\\b" "\\`read\\b" "\\`search\\b"
- "\\`find\\b" "\\`fetch\\b" "\\`view\\b" "\\`query\\b"
- "\\`describe\\b" "\\`show\\b" "\\`check\\b")
- "Tool-name prefixes that indicate a read-only operation.")
-
-;; Secret-pattern list for redaction. Each entry is (REGEX
-;; . GROUP-NUMBER); the substring matched by GROUP-NUMBER is replaced
-;; with "***".
-
-(defconst cj/mcp--secret-redaction-patterns
- '(("\\(--token\\)\\(=\\|\\s-+\\)\\(\\S-+\\)" . 3)
- ("\\(--secret\\)\\(=\\|\\s-+\\)\\(\\S-+\\)" . 3)
- ("\\(--password\\)\\(=\\|\\s-+\\)\\(\\S-+\\)" . 3)
- ("\\(--figma-api-key\\)\\(=\\|\\s-+\\)\\(\\S-+\\)" . 3)
- ("\\(Authorization:\\s-*\\)\\(\\S-[^\"\n]*\\)" . 2)
- ("\\([?&]token=\\)\\([^&[:space:]\"]+\\)" . 2))
- "List of (REGEX . GROUP-NUMBER) for masking secrets in user-facing strings.
-Applied in order by `cj/mcp--redact'.")
-
-;;;; --- 3. Pure helpers -----------------------------------------------
-
-;; ---- secrets redaction ----
-
-(defun cj/mcp--redact (str)
- "Return STR with known secret patterns replaced by `***'.
-Returns nil when STR is not a string. See
-`cj/mcp--secret-redaction-patterns' for the matched patterns."
- (when (stringp str)
- (let ((result str))
- (dolist (entry cj/mcp--secret-redaction-patterns result)
- (let ((re (car entry))
- (group (cdr entry))
- (start 0))
- (while (and (< start (length result))
- (string-match re result start))
- (setq result
- (concat (substring result 0 (match-beginning group))
- "***"
- (substring result (match-end group))))
- (setq start (+ (match-beginning group) 3))))))))
-
-;; ---- confirm-policy classifier ----
-
-(defun cj/mcp--strip-name-prefix (name)
- "Strip the `mcp__SERVER__' prefix from NAME, if present."
- (replace-regexp-in-string "\\`mcp__[^_]+__" "" name))
-
-(defun cj/mcp--name-matches-p (name patterns)
- "Non-nil if NAME matches any regexp in PATTERNS."
- (cl-some (lambda (p) (string-match-p p name)) patterns))
-
-(defun cj/mcp--confirm-p (gptel-name &optional remote-name)
- "Return non-nil if a tool should register with `:confirm t'.
-GPTEL-NAME is the fully qualified `mcp__SERVER__TOOL' string.
-REMOTE-NAME, if provided, overrides the prefix-strip of GPTEL-NAME.
-
-Decision order:
-1. `cj/mcp-tool-confirm-overrides' alist entry wins.
-2. Bare name matches a write pattern → t.
-3. Bare name matches a read pattern → nil.
-4. Neither → t (fail closed)."
- (let ((override (assoc gptel-name cj/mcp-tool-confirm-overrides)))
- (cond
- (override (cdr override))
- (t
- (let ((bare (or remote-name (cj/mcp--strip-name-prefix gptel-name))))
- (cond
- ((cj/mcp--name-matches-p bare cj/mcp--write-name-patterns) t)
- ((cj/mcp--name-matches-p bare cj/mcp--read-name-patterns) nil)
- (t t)))))))
-
-;; ---- description normalizer ----
-
-(defun cj/mcp--normalize-description (server-name raw-tool)
- "Return a normalized description string for RAW-TOOL from SERVER-NAME.
-Prefix `[SERVER]' for reads, `[SERVER WRITE]' for writes,
-`[SERVER ?]' for unknown classification, then the upstream
-description unchanged."
- (let* ((remote-name (plist-get raw-tool :name))
- (upstream (or (plist-get raw-tool :description)
- "(no description provided by server)"))
- (suffix (cond
- ((cj/mcp--name-matches-p remote-name
- cj/mcp--write-name-patterns)
- " WRITE")
- ((cj/mcp--name-matches-p remote-name
- cj/mcp--read-name-patterns)
- "")
- (t " ?"))))
- (format "[%s%s] %s" server-name suffix upstream)))
-
-;; ---- Claude config reader (mtime-cached, structured returns) ----
-
-(defvar cj/mcp--config-cache nil
- "Cache for the parsed Claude config.
-Plist of (:path P :mtime M :data PARSED) or nil when empty.")
-
-(defun cj/mcp--invalidate-config-cache ()
- "Force the next `cj/mcp--read-claude-config' call to reparse."
- (setq cj/mcp--config-cache nil))
-
-(defun cj/mcp--read-claude-config (&optional path)
- "Return a structured plist describing the Claude config state.
-PATH defaults to `cj/mcp-claude-config'.
-
-Result shape:
- (:ok t :data PLIST)
- (:ok nil :reason missing-file)
- (:ok nil :reason unreadable)
- (:ok nil :reason malformed-json :message STR)
-
-The parsed result is cached by (PATH, MTIME); subsequent calls
-reparse only if the file has changed."
- (let ((path (or path cj/mcp-claude-config)))
- (cond
- ((not (file-exists-p path))
- (list :ok nil :reason 'missing-file))
- ((not (file-readable-p path))
- (list :ok nil :reason 'unreadable))
- (t
- (let ((mtime (file-attribute-modification-time
- (file-attributes path))))
- (if (and cj/mcp--config-cache
- (equal (plist-get cj/mcp--config-cache :path) path)
- (equal (plist-get cj/mcp--config-cache :mtime) mtime))
- (list :ok t :data (plist-get cj/mcp--config-cache :data))
- (condition-case err
- (let* ((json-object-type 'plist)
- (json-array-type 'list)
- (data (with-temp-buffer
- (insert-file-contents path)
- (goto-char (point-min))
- (json-read))))
- (setq cj/mcp--config-cache
- (list :path path :mtime mtime :data data))
- (list :ok t :data data))
- (error
- (setq cj/mcp--config-cache nil)
- (list :ok nil :reason 'malformed-json
- :message (error-message-string err))))))))))
-
-;; ---- env / secret-args resolution ----
-
-(defun cj/mcp--get-server-entry (server-name &optional config-result)
- "Return the parsed Claude-config entry plist for SERVER-NAME.
-CONFIG-RESULT, if provided, is a return value from
-`cj/mcp--read-claude-config' (avoids re-reading). Returns nil
-when the config is unavailable or SERVER-NAME is unknown."
- (let ((result (or config-result (cj/mcp--read-claude-config))))
- (when (plist-get result :ok)
- (let* ((data (plist-get result :data))
- (servers (plist-get data :mcpServers))
- (server-key (intern (concat ":" server-name))))
- (plist-get servers server-key)))))
-
-(defun cj/mcp--get-env (server-name &optional config-result)
- "Return the env plist for SERVER-NAME from the parsed Claude config.
-CONFIG-RESULT, if provided, is reused to avoid re-reading the
-config. Returns nil when the config is unavailable, the server
-is unknown, or the server has no env section."
- (plist-get (cj/mcp--get-server-entry server-name config-result) :env))
-
-(defun cj/mcp--get-secret-arg (server-name flag &optional config-result)
- "Return the secret value for SERVER-NAME's FLAG from the Claude config.
-FLAG is the option name (e.g. \"--figma-api-key\"). Returns the
-value following `FLAG=' in the server entry's args, or nil if
-not found."
- (let* ((entry (cj/mcp--get-server-entry server-name config-result))
- (args (plist-get entry :args))
- (prefix (concat flag "=")))
- (cl-some
- (lambda (a)
- (when (and (stringp a) (string-prefix-p prefix a))
- (substring a (length prefix))))
- args)))
-
-;; ---- server-alist builder (pure transform from specs + config) ----
-
-(defun cj/mcp--resolve-env (env-spec server-name config-result)
- "Return a flat (KEY1 VAL1 KEY2 VAL2 ...) list for ENV-SPEC.
-ENV-SPEC is a plist of `(:VAR1 t :VAR2 t)`. Values come from
-SERVER-NAME's env subtree in the parsed Claude config. Vars
-without a value are omitted."
- (let ((source-env (cj/mcp--get-env server-name config-result))
- (result nil))
- (cl-loop for (key _placeholder) on env-spec by #'cddr
- do (let ((value (plist-get source-env key)))
- (when value
- (push key result)
- (push value result))))
- (nreverse result)))
-
-(defun cj/mcp--resolve-args (args secret-args-spec server-name config-result)
- "Return ARGS with `:secret-args' placeholders filled in.
-SECRET-ARGS-SPEC is (FLAG-STRING SLOT-KEYWORD). When the value is
-available in the Claude config, append `FLAG=VALUE' to ARGS;
-otherwise return ARGS unchanged."
- (if (not secret-args-spec)
- args
- (let* ((flag (car secret-args-spec))
- (value (cj/mcp--get-secret-arg server-name flag config-result)))
- (if value
- (append args (list (format "%s=%s" flag value)))
- args))))
-
-(defun cj/mcp--spec-to-alist-entry (spec config-result)
- "Translate one SPEC plist into a `(NAME . PLIST)' alist entry.
-Pulls env values from CONFIG-RESULT; splices `:secret-args' into
-`:args' for stdio specs that declare one."
- (let* ((name (plist-get spec :name))
- (transport (plist-get spec :transport))
- (entry (list :type (symbol-name transport)))
- (env-spec (plist-get spec :env))
- (secret-args-spec (plist-get spec :secret-args)))
- (pcase transport
- ('stdio
- (setq entry (append entry
- (list :command (plist-get spec :command)
- :args (cj/mcp--resolve-args
- (plist-get spec :args)
- secret-args-spec
- name
- config-result)))))
- ((or 'http 'sse)
- (setq entry (append entry
- (list :url (plist-get spec :url))))))
- (when env-spec
- (let ((env-pairs (cj/mcp--resolve-env env-spec name config-result)))
- (when env-pairs
- (setq entry (append entry (list :env env-pairs))))))
- (cons name entry)))
-
-(defun cj/mcp--build-server-alist (&optional specs enabled-names config-result)
- "Return an alist suitable for `mcp-hub-servers'.
-SPECS defaults to `cj/mcp-server-specs'. ENABLED-NAMES defaults
-to `cj/mcp-enabled-servers'. CONFIG-RESULT, if provided, is a
-parsed Claude-config result (reused for env/secret resolution).
-Does not mutate SPECS."
- (let* ((specs (or specs cj/mcp-server-specs))
- (enabled-names (or enabled-names cj/mcp-enabled-servers))
- (config-result (or config-result (cj/mcp--read-claude-config))))
- (delq nil
- (mapcar
- (lambda (spec)
- (let ((name (plist-get spec :name)))
- (when (member name enabled-names)
- (cj/mcp--spec-to-alist-entry spec config-result))))
- specs))))
-
-(provide 'ai-mcp)
-;;; ai-mcp.el ends here
diff --git a/modules/ai-quick-ask.el b/modules/ai-quick-ask.el
deleted file mode 100644
index 16f3afae4..000000000
--- a/modules/ai-quick-ask.el
+++ /dev/null
@@ -1,141 +0,0 @@
-;;; ai-quick-ask.el --- One-shot GPTel quick-ask -*- lexical-binding: t; coding: utf-8; -*-
-
-;; Author: Craig Jennings <c@cjennings.net>
-
-;;; Commentary:
-;; Provides `cj/gptel-quick-ask': read a single prompt in the
-;; minibuffer, stream the response into a transient *GPTel-Quick*
-;; buffer. The transient buffer is dismissible with q or escape and
-;; can be escalated with c into a full *AI-Assistant* conversation
-;; seeded with the prompt + response.
-;;
-;; Designed for impromptu help where the conversation thread doesn't
-;; matter. Doesn't touch the *AI-Assistant* side window unless the
-;; user explicitly escalates, doesn't autosave anywhere.
-
-;;; Code:
-
-(require 'cj-window-toggle-lib) ;; cj/side-window-display
-
-;; Shared *AI-Assistant* panel-width state, owned by ai-config.el. Forward-
-;; declared here so the escalation reopens the panel at the same remembered
-;; width as the F-key toggle without a circular require.
-(defvar cj/ai-assistant-window-width)
-(defvar cj/--ai-assistant-width)
-
-(defvar-local cj/gptel-quick--prompt nil
- "Buffer-local: the prompt used for the current *GPTel-Quick* session.")
-
-(defconst cj/gptel-quick--buffer-name "*GPTel-Quick*"
- "Buffer used for one-shot quick-ask Q&A.")
-
-(defconst cj/gptel-quick--response-marker "A: "
- "String inserted before the response in the quick-ask buffer.")
-
-(defvar-keymap cj/gptel-quick-mode-map
- :doc "Keymap for `cj/gptel-quick-mode'."
- "q" #'cj/gptel-quick-dismiss
- "<escape>" #'cj/gptel-quick-dismiss
- "c" #'cj/gptel-quick-continue)
-
-(define-derived-mode cj/gptel-quick-mode special-mode "GPTel-Quick"
- "Major mode for the one-shot *GPTel-Quick* buffer."
- ;; Allow gptel-request to stream into the buffer despite the
- ;; special-mode read-only default.
- (setq-local buffer-read-only nil))
-
-(defun cj/gptel-quick--initial-text (prompt)
- "Return the initial buffer body for a quick-ask of PROMPT.
-The result is \"Q: <prompt>\\n\\nA: \", with the response marker at
-the end so the streamed response lands right after it."
- (format "Q: %s\n\n%s" prompt cj/gptel-quick--response-marker))
-
-(defun cj/gptel-quick--extract-response (text)
- "Return the response portion of TEXT, or nil if not found.
-TEXT is the contents of a *GPTel-Quick* buffer. The response is
-everything after the first occurrence of `cj/gptel-quick--response-marker'
-on its own line. Returns nil when the marker is absent."
- (when (string-match
- (concat "^" (regexp-quote cj/gptel-quick--response-marker))
- text)
- (substring text (match-end 0))))
-
-(defun cj/gptel-quick--seed-text (prompt response)
- "Format a *AI-Assistant* seed from PROMPT and RESPONSE.
-Matches the org-heading shape that `cj/gptel--fresh-org-prefix' and
-`cj/gptel-insert-model-heading' produce: a user heading followed by
-the prompt body, followed by an AI heading followed by the response."
- (let ((ts (format-time-string "[%Y-%m-%d %H:%M:%S]")))
- (format "* %s %s\n%s\n\n* AI %s\n%s\n"
- user-login-name ts prompt
- ts (or response ""))))
-
-;;;###autoload
-(defun cj/gptel-quick-ask (prompt)
- "Read a one-shot PROMPT in the minibuffer and stream the answer.
-The response lands in a transient *GPTel-Quick* buffer. Press q or
-escape to dismiss, or c to escalate into a full *AI-Assistant*
-conversation seeded with the prompt and response."
- (interactive (list (read-string "Quick ask: ")))
- (when (string-empty-p prompt)
- (user-error "Empty prompt"))
- (let ((buf (get-buffer-create cj/gptel-quick--buffer-name)))
- (with-current-buffer buf
- (cj/gptel-quick-mode)
- (let ((inhibit-read-only t))
- (erase-buffer)
- (insert (cj/gptel-quick--initial-text prompt))
- (setq-local cj/gptel-quick--prompt prompt)))
- (unless (featurep 'gptel)
- (require 'gptel))
- (when (fboundp 'cj/ensure-gptel-backends)
- (cj/ensure-gptel-backends))
- (gptel-request prompt
- :buffer buf
- :position (with-current-buffer buf (point-max))
- :stream t)
- (display-buffer buf
- '((display-buffer-reuse-window
- display-buffer-pop-up-window)
- (window-height . 0.3)))
- buf))
-
-(defun cj/gptel-quick-dismiss ()
- "Kill the *GPTel-Quick* buffer if it exists."
- (interactive)
- (when-let ((buf (get-buffer cj/gptel-quick--buffer-name)))
- (when-let ((win (get-buffer-window buf)))
- (delete-window win))
- (kill-buffer buf)))
-
-(defun cj/gptel-quick-continue ()
- "Escalate the current quick-ask into a full *AI-Assistant* conversation.
-Reads the prompt and response from the *GPTel-Quick* buffer, seeds
-them into *AI-Assistant* under proper org headings, displays the
-side window, then dismisses the quick buffer."
- (interactive)
- (unless (eq major-mode 'cj/gptel-quick-mode)
- (user-error "Not in a *GPTel-Quick* buffer"))
- (let* ((prompt cj/gptel-quick--prompt)
- (response (cj/gptel-quick--extract-response (buffer-string)))
- (seed (cj/gptel-quick--seed-text prompt response)))
- (unless prompt
- (user-error "No prompt recorded in this buffer"))
- ;; Ensure *AI-Assistant* exists in gptel-mode.
- (unless (featurep 'gptel)
- (require 'gptel))
- (let ((ai-buf (get-buffer "*AI-Assistant*")))
- (unless ai-buf
- (when (fboundp 'cj/ensure-gptel-backends)
- (cj/ensure-gptel-backends))
- (gptel "*AI-Assistant*")
- (setq ai-buf (get-buffer "*AI-Assistant*")))
- (with-current-buffer ai-buf
- (goto-char (point-max))
- (insert seed))
- (cj/side-window-display
- ai-buf 'right 'cj/--ai-assistant-width cj/ai-assistant-window-width)
- (cj/gptel-quick-dismiss))))
-
-(provide 'ai-quick-ask)
-;;; ai-quick-ask.el ends here
diff --git a/modules/ai-rewrite.el b/modules/ai-rewrite.el
deleted file mode 100644
index fb25c1379..000000000
--- a/modules/ai-rewrite.el
+++ /dev/null
@@ -1,108 +0,0 @@
-;;; ai-rewrite.el --- Directive-picker wrappers for gptel-rewrite -*- lexical-binding: t; coding: utf-8; -*-
-
-;; Author: Craig Jennings <c@cjennings.net>
-
-;;; Commentary:
-;; Adds two ergonomic wrappers around `gptel-rewrite':
-;;
-;; cj/gptel-rewrite-with-directive Pick a named directive,
-;; then rewrite the region.
-;; cj/gptel-rewrite-redo-with-different-directive
-;; Re-run the previous region
-;; with a different directive.
-;;
-;; A directive is a short system-message snippet attached to a name
-;; (e.g. "terse", "fix-grammar"). The directive body is injected
-;; into the rewrite via `gptel-rewrite-directives-hook' just for that
-;; call -- no global state changes.
-
-;;; Code:
-
-;; Declare the hook variable special so our `let'-binding below is
-;; dynamic (visible across the `call-interactively' that follows)
-;; rather than lexical when this file is byte-compiled.
-(defvar gptel-rewrite-directives-hook)
-
-(defcustom cj/gptel-rewrite-directives
- '(("terse"
- . "Rewrite the text to be as terse as possible without losing meaning.\nDo not add commentary. Return only the rewritten text.")
- ("fix-grammar"
- . "Fix grammar and spelling errors only. Do not rephrase, restructure,\nor change tone. Return only the corrected text.")
- ("refactor-readability"
- . "Refactor the code for readability. Improve naming, split long\nfunctions when appropriate, remove unnecessary complexity, and preserve\nbehavior exactly. Return only the refactored code.")
- ("add-docstring"
- . "Add or improve docstrings for every function in the region. Use the\nidiomatic docstring style for the language. Do not change executable\ncode. Return the whole region with the updated docstrings.")
- ("explain-as-comment"
- . "Replace the region with the original code, preceded by a concise\nblock comment explaining what the code does. Use the language's\nidiomatic comment syntax. Return code + comment, nothing else.")
- ("shorten"
- . "Shorten the text while preserving meaning, technical accuracy, and\nthe author's voice. Remove rhetorical padding. Return only the\nshortened text."))
- "Named system-message directives for `cj/gptel-rewrite-with-directive'.
-Each entry is a (NAME . BODY) pair where NAME is the directive label
-presented in the completing-read prompt and BODY is the system
-message injected into the next `gptel-rewrite' call."
- :type '(alist :key-type string :value-type string)
- :group 'cj)
-
-(defvar-local cj/gptel-rewrite--last-region nil
- "Cons (BEG-MARKER . END-MARKER) of the last directive-driven rewrite.")
-
-(defvar-local cj/gptel-rewrite--last-directive nil
- "Name of the directive used in the last directive-driven rewrite.")
-
-(defun cj/gptel-rewrite--call-with-directive (directive-name beg end)
- "Run `gptel-rewrite' over BEG..END with DIRECTIVE-NAME's system message.
-Stores the region (as markers) and directive name on buffer-local
-variables so `cj/gptel-rewrite-redo-with-different-directive' can
-revisit them."
- (let ((body (alist-get directive-name cj/gptel-rewrite-directives
- nil nil #'equal)))
- (unless body
- (user-error "Unknown rewrite directive: %s" directive-name))
- (setq-local cj/gptel-rewrite--last-region
- (cons (copy-marker beg) (copy-marker end)))
- (setq-local cj/gptel-rewrite--last-directive directive-name)
- (let ((gptel-rewrite-directives-hook
- (cons (lambda () body) gptel-rewrite-directives-hook)))
- (save-excursion
- (goto-char beg)
- (push-mark end t t)
- (call-interactively #'gptel-rewrite)))))
-
-;;;###autoload
-(defun cj/gptel-rewrite-with-directive (directive-name)
- "Pick DIRECTIVE-NAME from `cj/gptel-rewrite-directives' and rewrite the region.
-Requires an active region. The directive is applied only to this
-call -- it does not modify global `gptel-directives'."
- (interactive
- (progn
- (unless (use-region-p)
- (user-error "No region selected"))
- (list (completing-read
- "Rewrite directive: "
- (mapcar #'car cj/gptel-rewrite-directives) nil t))))
- (cj/gptel-rewrite--call-with-directive
- directive-name (region-beginning) (region-end)))
-
-;;;###autoload
-(defun cj/gptel-rewrite-redo-with-different-directive ()
- "Re-run the previous directive-driven rewrite with a different directive.
-The region is restored from the markers captured at the last call;
-the user picks a new directive from the remaining choices."
- (interactive)
- (unless cj/gptel-rewrite--last-region
- (user-error "No previous rewrite to redo in this buffer"))
- (let* ((beg-mk (car cj/gptel-rewrite--last-region))
- (end-mk (cdr cj/gptel-rewrite--last-region))
- (current cj/gptel-rewrite--last-directive)
- (others (cl-remove
- current
- (mapcar #'car cj/gptel-rewrite-directives)
- :test #'equal))
- (chosen (completing-read
- (format "Re-rewrite with (was %s): " current)
- others nil t)))
- (cj/gptel-rewrite--call-with-directive
- chosen (marker-position beg-mk) (marker-position end-mk))))
-
-(provide 'ai-rewrite)
-;;; ai-rewrite.el ends here
diff --git a/modules/ai-term.el b/modules/ai-term.el
index 49d44d25e..b463da90b 100644
--- a/modules/ai-term.el
+++ b/modules/ai-term.el
@@ -52,15 +52,21 @@
;; picker, even when an agent buffer is currently displayed.
;; Used when the user wants to start a new project session
;; instead of toggling the current one.
+;; - s-F9 `cj/ai-term-next' -- step to the next active agent in the
+;; queue. The queue is every active agent in buffer-name order
+;; (a stable rotation): attached agents (a live buffer) and
+;; detached ones (a live tmux session with no Emacs buffer).
+;; Stepping onto a detached agent attaches it. When an agent
+;; window is on screen, swap it to the next agent and focus it,
+;; wrapping after the last; when none is shown but agents exist,
+;; show the first. This is the "switch among existing agents"
+;; surface F9 deliberately doesn't provide.
;; - M-F9 `cj/ai-term-close' -- gracefully close an agent: kill its
;; tmux session (stopping the agent process), then its terminal
;; buffer. Its window stays in the layout (swapped to the
;; working buffer), so closing never collapses a split. Confirms
;; first. Targets the current agent, the sole live agent, or
;; prompts among several.
-;; - C-S-F9 `cj/ai-term-close' -- same close command, second binding.
-;; (M-F9 is the primary; C-S-F9 may be swallowed by the
-;; Wayland/PGTK layer on some machines.)
;;
;; Existing windmove (Shift-arrows) handles code <-> agent focus
;; toggling. Buffer-move (C-M-arrows) handles side-swap. Neither
@@ -73,6 +79,7 @@
(require 'cj-window-geometry-lib)
(require 'cj-window-toggle-lib)
(require 'host-environment)
+(require 'keybindings) ;; provides cj/register-prefix-map (C-; a)
(declare-function ghostel "ghostel" (&optional arg))
(declare-function ghostel-send-string "ghostel" (string))
@@ -181,6 +188,40 @@ recently-selected first. Non-AI-term buffers are filtered out via
`cj/--ai-term-buffer-p'."
(seq-filter #'cj/--ai-term-buffer-p (buffer-list)))
+(defun cj/--ai-term-next-agent-dir (current dirs)
+ "Return the project dir after CURRENT in DIRS, wrapping to the first.
+
+DIRS is an ordered list of active-agent project dirs. When CURRENT is
+the last element, wrap to the first. When CURRENT is nil or not a member
+of DIRS, return the first dir. Returns nil when DIRS is empty. Matches
+with `member' (string equality) since dirs are paths.
+
+Pure decision helper (no buffer or window side effects) so the cycle
+order driving `cj/ai-term-next' is exercisable in tests."
+ (when dirs
+ (if (member current dirs)
+ (or (cadr (member current dirs))
+ (car dirs))
+ (car dirs))))
+
+(defun cj/--ai-term-active-agent-dirs ()
+ "Return project dirs that have a live agent buffer or a live tmux session.
+
+Sorted by the agent buffer name, so the rotation is stable and matches
+what the picker shows. This is the queue `cj/ai-term-next' steps through:
+it includes detached sessions (alive in tmux but with no Emacs buffer),
+which the step materializes by attaching."
+ (let* ((sessions (cj/--ai-term-live-tmux-sessions))
+ (live-names (mapcar #'buffer-name (cj/--ai-term-agent-buffers))))
+ (sort
+ (seq-filter
+ (lambda (dir)
+ (or (member (cj/--ai-term-buffer-name dir) live-names)
+ (cj/--ai-term-session-active-p dir sessions)))
+ (cj/--ai-term-candidates))
+ (lambda (a b)
+ (string< (cj/--ai-term-buffer-name a) (cj/--ai-term-buffer-name b))))))
+
(defun cj/--ai-term-most-recent-non-agent-buffer ()
"Return the most-recently-selected live non-agent buffer, or nil.
@@ -391,21 +432,17 @@ fallback when `cj/--ai-term-last-size' is nil."
:type 'number
:group 'ai-term)
-(defun cj/--ai-term-direction-for-aspect (pixel-width pixel-height)
- "Return the space-conserving dock direction for a frame of PIXEL-WIDTH by
-PIXEL-HEIGHT. `right' when the frame is wider than tall (dock from the right
-edge), `below' when it is square or taller (dock from the bottom)."
- (if (> pixel-width pixel-height) 'right 'below))
-
(defun cj/--ai-term-default-direction (&optional frame)
"Return the default split direction for the agent window.
-Chosen at display time from FRAME's pixel aspect ratio (FRAME defaults to the
-selected frame): `right' on a landscape frame, `below' on a square or portrait
-one -- whichever edge conserves more screen space."
+Chosen at display time from FRAME's column width (FRAME defaults to the
+selected frame): `right' when a side-by-side split would leave both the
+agent and the main window at least `cj/window-dock-min-columns' wide,
+`below' otherwise. The agent's share of the width is
+`cj/ai-term-desktop-width'. See `cj/preferred-dock-direction'."
(let ((frame (or frame (selected-frame))))
- (cj/--ai-term-direction-for-aspect (frame-pixel-width frame)
- (frame-pixel-height frame))))
+ (cj/preferred-dock-direction (frame-width frame)
+ cj/ai-term-desktop-width)))
(defun cj/--ai-term-default-size ()
"Return the default size fraction paired with the chosen direction.
@@ -437,6 +474,18 @@ without deleting), nil when the window was deleted. Consumed by
buried agent in the current window (the only one) or splitting per
the saved direction.")
+(defvar cj/--ai-term-last-toggle-deleted-split nil
+ "Non-nil when the last F9 toggle-off deleted the agent's own split window.
+
+Set t by `cj/--ai-term-toggle-off' only when it actually `delete-window's
+the agent (a multi-window layout where the agent had its own window);
+nil for a bury or a degenerate swap. Consumed by
+`cj/--ai-term-reuse-edge-window': when set, the next toggle-on re-splits a
+fresh agent window instead of reusing a window at the edge. Without this,
+toggling the agent off and on in a 3+ window layout would reuse the user's
+working window at the edge, displacing its buffer and collapsing the layout
+-- the toggle must be reversible (off then on returns the same windows).")
+
(defvar cj/--ai-term-last-hidden-buffer nil
"The agent buffer hidden by the most recent F9 toggle-off.
@@ -449,21 +498,28 @@ the \"the displayed buffer changes\" bug. Falls back to the buffer-list
MRU when nil or when the remembered buffer has been killed.")
(defvar cj/--ai-term-last-size nil
- "Last user-chosen body size for the AI-term display.
+ "Last user-chosen size for the AI-term display.
Positive integer: body-columns when `cj/--ai-term-last-direction'
-is right or left, body-lines when below or above. nil means use
+is right or left, total-lines when below or above. nil means use
the host-aware default from `cj/--ai-term-default-size' (a float
-fraction).
-
-Body size, not total size, because total-width includes the
-right-edge divider when the window has a right sibling but excludes
-it when the window is at the frame edge. Capturing total-width
-from a rightmost agent (no divider) and replaying into a middle
-position (with divider) leaves the body 1 column short -- visible
-as 1 col of the sibling buffer peeking through where agent should
-have ended. Body-width is divider-independent and matches what the
-user actually sees.
+fraction). See `cj/window-replay-size' for the per-axis capture.
+
+The axis choice is asymmetric. Width captures body-width, not
+total-width: total-width includes the right-edge divider when the
+window has a right sibling but excludes it at the frame edge, so
+capturing total-width from a rightmost agent (no divider) and
+replaying into a middle position (with divider) leaves the body 1
+column short. Body-width is divider-independent.
+
+Height captures total-height, not body-height: every window has
+exactly one mode line regardless of position, so total-height has
+no divider-position problem, and total-height is the same whether
+the window is active or inactive. Body-height would subtract the
+mode line's pixel height, which differs between an active and an
+inactive (theme-shrunk) mode line -- capturing body-height active
+and replaying it inactive then re-measuring active drifts the
+window down by ~1 line per toggle (the F9 shrink bug, 2026-06-20).
Absolute values rather than fractions because
`display-buffer-in-direction' interprets a float `window-width' /
@@ -531,14 +587,22 @@ displaced buffer and the agent, never changing the window count.
Runs after `cj/--ai-term-reuse-existing-agent', so an agent already on
screen has been handled already; the window reused here always holds a
-non-agent buffer, which is replaced (it stays alive, just unshown)."
- (let* ((direction (or cj/--ai-term-last-direction
- (cj/--ai-term-default-direction)))
- (win (cj/window-at-edge direction)))
- (when (and win (not (window-dedicated-p win)))
- (display-buffer-record-window 'reuse win buffer)
- (set-window-buffer win buffer)
- win)))
+non-agent buffer, which is replaced (it stays alive, just unshown).
+
+Skipped entirely when the prior toggle-off deleted the agent's own split
+window (`cj/--ai-term-last-toggle-deleted-split'): re-showing then reuses a
+working window at the edge and collapses the layout. Consume the flag and
+return nil so `cj/--ai-term-display-saved' re-splits a fresh agent window,
+keeping the toggle reversible."
+ (if cj/--ai-term-last-toggle-deleted-split
+ (progn (setq cj/--ai-term-last-toggle-deleted-split nil) nil)
+ (let* ((direction (or cj/--ai-term-last-direction
+ (cj/--ai-term-default-direction)))
+ (win (cj/window-at-edge direction)))
+ (when (and win (not (window-dedicated-p win)))
+ (display-buffer-record-window 'reuse win buffer)
+ (set-window-buffer win buffer)
+ win))))
(defun cj/--ai-term-display-saved (buffer alist)
"Display-buffer action: split per saved direction and size.
@@ -778,6 +842,72 @@ launches from either (only kitty inline-graphics degrade in a TTY)."
(when win (select-window win))))
buf))
+(defun cj/--ai-term-swap-to-working-buffer (win)
+ "In WIN, switch to the most-recent non-agent buffer (a working file).
+Falls back to `other-buffer' (excluding WIN's current agent buffer) when no
+non-agent buffer is on record. Used at toggle-off and close so dismissing an
+agent surfaces the file the user was working on rather than another agent or
+the agent itself."
+ (with-selected-window win
+ (switch-to-buffer
+ (or (cj/--ai-term-most-recent-non-agent-buffer)
+ (other-buffer (window-buffer win) t)))))
+
+(defun cj/--ai-term-toggle-off (win)
+ "Hide the agent shown in WIN for an F9 toggle-off. Always returns nil.
+
+Two cases, by window count:
+
+- Lone fullscreen agent (e.g. after `C-x 1' inside it): there is no prior
+ layout for the native undo to restore and deleting would leave the frame
+ empty. Bury and flag, so the next toggle-on (`cj/--ai-term-display-saved')
+ restores the agent in place at full frame rather than splitting. Capture
+ geometry for that restore. `bury-buffer' can no-op when the window's
+ prev-buffer history holds only the agent (common right after `C-x 1'), so
+ force a swap to a non-agent buffer to keep the toggle observable.
+
+- Multi-window: collapse the agent split outright by deleting its window, so
+ the working buffer (e.g. todo.org) reclaims the space. F9 is a pure
+ show/hide toggle of THE agent split -- it must never surface a different
+ agent. `quit-restore-window' can't guarantee that here: switching among
+ several agents reuses the one slot via `set-window-buffer' (see
+ `cj/--ai-term-reuse-existing-agent'), which leaves the window's
+ `quit-restore' parameter pointing at the FIRST agent shown. Once it's
+ stale, `quit-restore-window' falls back to `switch-to-prev-buffer' and
+ surfaces another agent instead of removing the window -- exactly the \"F9
+ shows another agent\" bug. `delete-window' is unconditional and
+ slot-history-independent. Capture geometry first so the next toggle-on
+ splits at the same size (the user's chosen split width is preserved)."
+ ;; Remember which agent we're hiding so the next toggle-on reopens this
+ ;; same one, not whichever agent is most-recent in `buffer-list'.
+ (setq cj/--ai-term-last-hidden-buffer (window-buffer win))
+ (cond
+ ((one-window-p)
+ (cj/--ai-term-capture-state win)
+ (setq cj/--ai-term-last-was-bury t)
+ (setq cj/--ai-term-last-toggle-deleted-split nil)
+ (bury-buffer (window-buffer win))
+ (when (and (window-live-p win)
+ (cj/--ai-term-buffer-p (window-buffer win)))
+ (cj/--ai-term-swap-to-working-buffer win)))
+ (t
+ (cj/--ai-term-capture-state win)
+ (setq cj/--ai-term-last-was-bury nil)
+ (if (and (window-live-p win)
+ (> (length (window-list (window-frame win) 'never)) 1))
+ (progn
+ (delete-window win)
+ ;; The agent had its own window in a multi-window layout, now gone:
+ ;; the next toggle-on must re-split it rather than reuse a working
+ ;; window at the edge (see `cj/--ai-term-reuse-edge-window').
+ (setq cj/--ai-term-last-toggle-deleted-split t))
+ ;; Degenerate fallback (window became sole between dispatch and
+ ;; here): swap to a non-agent buffer rather than leave the agent up.
+ (setq cj/--ai-term-last-toggle-deleted-split nil)
+ (when (window-live-p win)
+ (cj/--ai-term-swap-to-working-buffer win)))))
+ nil)
+
(defun cj/ai-term (&optional arg)
"Smart F9 dispatch for the AI-term launcher.
@@ -793,59 +923,11 @@ With prefix ARG, display the buffer without selecting its window
when a buffer is being shown (no effect on the toggle-off branch).
See `cj/ai-term-pick-project' (C-F9) to force the project picker.
-M-F9 (and C-S-F9) close an agent via `cj/ai-term-close'."
+M-F9 closes an agent via `cj/ai-term-close'."
(interactive "P")
(pcase (cj/--ai-term-dispatch)
(`(toggle-off . ,win)
- ;; Remember which agent we're hiding so the next toggle-on reopens this
- ;; same one, not whichever agent is most-recent in `buffer-list'.
- (setq cj/--ai-term-last-hidden-buffer (window-buffer win))
- (cond
- ;; Lone fullscreen agent (e.g. after `C-x 1' inside it): there is no
- ;; prior layout for the native undo to restore and deleting would
- ;; leave the frame empty. Bury and flag, so the next toggle-on
- ;; (`cj/--ai-term-display-saved') restores the agent in place at
- ;; full frame rather than splitting. Capture geometry for that
- ;; restore. `bury-buffer' can no-op when the window's prev-buffer
- ;; history holds only the agent (common right after `C-x 1'), so
- ;; force a swap to a non-agent buffer to keep the toggle observable.
- ((one-window-p)
- (cj/--ai-term-capture-state win)
- (setq cj/--ai-term-last-was-bury t)
- (bury-buffer (window-buffer win))
- (when (and (window-live-p win)
- (cj/--ai-term-buffer-p (window-buffer win)))
- (with-selected-window win
- (switch-to-buffer
- (or (cj/--ai-term-most-recent-non-agent-buffer)
- (other-buffer (window-buffer win) t))))))
- ;; Multi-window: collapse the agent split outright by deleting its
- ;; window, so the working buffer (e.g. todo.org) reclaims the space.
- ;; F9 is a pure show/hide toggle of THE agent split -- it must never
- ;; surface a different agent. `quit-restore-window' can't guarantee
- ;; that here: switching among several agents reuses the one slot via
- ;; `set-window-buffer' (see `cj/--ai-term-reuse-existing-agent'),
- ;; which leaves the window's `quit-restore' parameter pointing at the
- ;; FIRST agent shown. Once it's stale, `quit-restore-window' falls
- ;; back to `switch-to-prev-buffer' and surfaces another agent instead
- ;; of removing the window -- exactly the "F9 shows another agent"
- ;; bug. `delete-window' is unconditional and slot-history-independent.
- ;; Capture geometry first so the next toggle-on splits at the same
- ;; size (the user's chosen split width is preserved across the toggle).
- (t
- (cj/--ai-term-capture-state win)
- (setq cj/--ai-term-last-was-bury nil)
- (if (and (window-live-p win)
- (> (length (window-list (window-frame win) 'never)) 1))
- (delete-window win)
- ;; Degenerate fallback (window became sole between dispatch and
- ;; here): swap to a non-agent buffer rather than leave the agent up.
- (when (window-live-p win)
- (with-selected-window win
- (switch-to-buffer
- (or (cj/--ai-term-most-recent-non-agent-buffer)
- (other-buffer (window-buffer win) t))))))))
- nil)
+ (cj/--ai-term-toggle-off win))
(`(redisplay-recent . ,buf)
(display-buffer buf)
(unless arg
@@ -885,10 +967,7 @@ when BUFFER isn't an AI-term buffer."
(buffer-local-value 'default-directory buffer)))
(let ((win (get-buffer-window buffer)))
(when (window-live-p win)
- (with-selected-window win
- (switch-to-buffer
- (or (cj/--ai-term-most-recent-non-agent-buffer)
- (other-buffer buffer t))))))
+ (cj/--ai-term-swap-to-working-buffer win)))
(let ((kill-buffer-query-functions nil))
(kill-buffer buffer))))
@@ -914,7 +993,7 @@ buffers; nil when none are alive."
Targets the current agent buffer, the sole live agent, or prompts when
several are alive (see `cj/--ai-term-close-target'). Asks for
confirmation first -- this kills the running agent process, which can
-interrupt work in progress. Bound to M-<f9> (primary) and C-S-<f9>."
+interrupt work in progress. Bound to M-<f9>."
(interactive)
(let ((buffer (cj/--ai-term-close-target)))
(unless buffer
@@ -925,32 +1004,169 @@ interrupt work in progress. Bound to M-<f9> (primary) and C-S-<f9>."
(cj/--ai-term-close-buffer buffer)
(message "Closed agent %s." name)))))
-(keymap-global-set "<f9>" #'cj/ai-term)
-(keymap-global-set "C-<f9>" #'cj/ai-term-pick-project)
-(keymap-global-set "M-<f9>" #'cj/ai-term-close)
-(keymap-global-set "C-S-<f9>" #'cj/ai-term-close)
-
-;; ghostel's semi-char mode forwards keys not in `ghostel-keymap-exceptions' to
-;; the terminal program, so a plain <f9> typed while point is inside an agent
-;; buffer would be sent to the program instead of toggling the agent -- which
-;; bites hard when the agent buffer is the only window in the frame. Re-bind
-;; the F9 family in `ghostel-mode-map' so the toggle reaches Emacs from there
-;; too. (C-<f9> / M-<f9> are bound here as well so the behaviour is uniform.)
+;; ------------------------- Step to the next agent ----------------------------
+
+(defun cj/ai-term-next ()
+ "Step to the next open AI-term agent in the queue.
+
+The queue is every active agent ordered by buffer name -- a stable
+rotation, unaffected by which agent was most recently selected. Active
+means a live agent buffer (attached) OR a live tmux session with no Emacs
+buffer (detached); stepping onto a detached agent attaches it (recreates
+its terminal, which reattaches the session). When an agent window is on
+screen, swap it to the next agent (wrapping after the last) and select it.
+When no agent is displayed but agents exist, show the first. When none
+are open, open the project picker to launch the first agent rather than
+erroring.
+
+Bound to M-SPC. Unlike C-; a a (toggle the most-recent agent on/off), this
+is the \"switch among existing agents\" surface; C-; a s opens the project
+picker and C-; a k closes an agent."
+ (interactive)
+ (let* ((dirs (cj/--ai-term-active-agent-dirs))
+ (win (cj/--ai-term-displayed-agent-window))
+ (current-name (and win (buffer-name (window-buffer win))))
+ (current-dir (and current-name
+ (seq-find (lambda (d)
+ (equal (cj/--ai-term-buffer-name d) current-name))
+ dirs)))
+ (next-dir (cj/--ai-term-next-agent-dir current-dir dirs)))
+ (if (not next-dir)
+ ;; No agents open: launch the first via the project picker instead of
+ ;; erroring, so the swap key doubles as a "start an agent" key.
+ (cj/ai-term-pick-project)
+ (let* ((name (cj/--ai-term-buffer-name next-dir))
+ (existing (get-buffer name)))
+ ;; Live agent and an agent window is up: swap it into that window in
+ ;; place (faithful to the prior buffer-only behavior). Detached, or no
+ ;; window yet: show-or-create attaches the tmux session / displays it.
+ (if (and win existing (cj/--ai-term-process-live-p existing))
+ (progn (set-window-buffer win existing) (select-window win))
+ (cj/--ai-term-show-or-create next-dir name)
+ (let ((w (get-buffer-window name)))
+ (when w (select-window w))))
+ (message "Agent: %s" name)))))
+
+;; ai-term lives under the C-; a prefix (vacated when gptel was archived).
+;; The frequent "swap to the next agent" also gets M-SPC for a fast chord.
+(defvar-keymap cj/ai-term-keymap
+ :doc "Keymap for ai-term agent commands (C-; a)."
+ "a" #'cj/ai-term ;; toggle the most-recent agent on/off
+ "s" #'cj/ai-term-pick-project ;; select / launch via the project picker
+ "n" #'cj/ai-term-next ;; swap to the next open agent
+ "k" #'cj/ai-term-close) ;; kill the current agent
+(cj/register-prefix-map "a" cj/ai-term-keymap "ai-term")
+(keymap-global-set "M-SPC" #'cj/ai-term-next)
+
+(with-eval-after-load 'which-key
+ (which-key-add-key-based-replacements
+ "C-; a" "ai-term menu"
+ "C-; a a" "toggle agent"
+ "C-; a s" "select / launch"
+ "C-; a n" "next agent"
+ "C-; a k" "kill agent"
+ "M-SPC" "ai-term: next agent"))
+
+;; In ghostel's semi-char mode, keys not in `ghostel-keymap-exceptions' are
+;; forwarded to the pty, and `ghostel-semi-char-mode-map' outranks the major
+;; mode map. M-SPC (swap to the next agent) must reach Emacs from inside an
+;; agent buffer, so add it to the exceptions, rebuild the semi-char map, and
+;; bind it in `ghostel-mode-map'. C-; is already an exception (term-config),
+;; so the C-; a family resolves through the global prefix without extra wiring.
(with-eval-after-load 'ghostel
- (keymap-set ghostel-mode-map "<f9>" #'cj/ai-term)
- (keymap-set ghostel-mode-map "C-<f9>" #'cj/ai-term-pick-project)
- (keymap-set ghostel-mode-map "M-<f9>" #'cj/ai-term-close)
- (keymap-set ghostel-mode-map "C-S-<f9>" #'cj/ai-term-close)
- ;; The bindings above live in `ghostel-mode-map', but in semi-char mode
- ;; ghostel's own `ghostel-semi-char-mode-map' forwards every key not in
- ;; `ghostel-keymap-exceptions' to the pty -- and that map outranks the
- ;; major-mode map, so it would swallow the F9 family before the bindings
- ;; above fire. Add the family to the exceptions and rebuild the semi-char
- ;; map so the keys fall through to `ghostel-mode-map' inside agent buffers.
- (dolist (key '("<f9>" "C-<f9>" "M-<f9>" "C-S-<f9>"))
- (add-to-list 'ghostel-keymap-exceptions key))
+ (keymap-set ghostel-mode-map "M-SPC" #'cj/ai-term-next)
+ (add-to-list 'ghostel-keymap-exceptions "M-SPC")
(ghostel--rebuild-semi-char-keymap))
+;; ------------------- Wrap-it-up teardown + shutdown -------------------------
+;;
+;; Headless entry points the rulesets wrap-it-up workflow calls via
+;; `emacsclient -e' (its Stop hook ~/.claude/hooks/ai-wrap-teardown.sh). All
+;; three must work with no interactive frame guaranteed. rulesets owns the
+;; workflow + hook that call these; this module owns the aiv- session naming,
+;; the agent buffer, and the geometry restore, so the functions live here.
+;; See docs/design/2026-06-23-wrap-teardown-shutdown-proposal.org (rulesets).
+
+(defcustom cj/ai-term-shutdown-command "sudo shutdown now"
+ "Shell command run when the shutdown countdown completes uncancelled.
+A defcustom so development and tests can stub it instead of powering off
+\(sudo is NOPASSWD on Craig's machines, so the default really shuts down)."
+ :type 'string
+ :group 'cj)
+
+(defun cj/ai-term-quit (&optional project)
+ "Tear down PROJECT's AI-term: kill its tmux session, buffer, and restore layout.
+PROJECT is a project basename (as the rulesets Stop hook passes) or a directory;
+nil means the current project (`default-directory'). Kills the `aiv-<name>'
+tmux session (taking the agent process with it), then, when the agent buffer is
+live, swaps its window back to the working buffer and kills it. Idempotent and
+safe headless: a session or buffer already gone is a no-op, not an error."
+ (let* ((key (or project default-directory))
+ (session (cj/--ai-term-tmux-session-name key))
+ (buffer (get-buffer (cj/--ai-term-buffer-name key))))
+ (cj/--ai-term-kill-tmux-session session)
+ (when (cj/--ai-term-buffer-p buffer)
+ (let ((win (get-buffer-window buffer)))
+ (when (window-live-p win)
+ (cj/--ai-term-swap-to-working-buffer win)))
+ (let ((kill-buffer-query-functions nil))
+ (kill-buffer buffer)))
+ session))
+
+(defun cj/ai-term-live-count ()
+ "Return the integer count of live AI-term (aiv-*) tmux sessions.
+0 when tmux has no server or no AI-term sessions. The shutdown safety gate:
+`emacsclient -e (cj/ai-term-live-count)' prints the integer for the hook."
+ (length (cj/--ai-term-live-tmux-sessions)))
+
+(defvar cj/--ai-term-shutdown-timer nil
+ "The active shutdown-countdown repeating timer, or nil when none is running.")
+
+(defun cj/--ai-term-shutdown-clear-timer ()
+ "Cancel and forget the shutdown-countdown timer, if any."
+ (when (timerp cj/--ai-term-shutdown-timer)
+ (cancel-timer cj/--ai-term-shutdown-timer))
+ (setq cj/--ai-term-shutdown-timer nil))
+
+(defun cj/ai-term-shutdown-cancel ()
+ "Cancel an in-progress AI-term shutdown countdown."
+ (interactive)
+ (when cj/--ai-term-shutdown-timer
+ (cj/--ai-term-shutdown-clear-timer)
+ (message "Shutdown cancelled.")))
+
+(defun cj/ai-term-shutdown-countdown (&optional seconds)
+ "Count down SECONDS (default 10) in the echo area, then shut the machine down.
+Re-checks the safety gate first (a TOCTOU guard against the workflow's earlier
+check): aborts with a message when more than one `aiv-*' session is live. The
+countdown is an abort-able `run-at-time' timer -- `C-g' (while the countdown
+owns the keymap) or \\[cj/ai-term-shutdown-cancel] stops it. On reaching zero
+uncancelled it runs `cj/ai-term-shutdown-command'. Returns immediately so the
+Stop hook does not block; the daemon ticks the timer asynchronously."
+ (if (> (cj/ai-term-live-count) 1)
+ (progn
+ (message "Shutdown aborted: %d AI-term sessions still live."
+ (cj/ai-term-live-count))
+ nil)
+ (cj/--ai-term-shutdown-clear-timer)
+ (let ((remaining (or seconds 10)))
+ (set-transient-map
+ (let ((m (make-sparse-keymap)))
+ (define-key m (kbd "C-g") #'cj/ai-term-shutdown-cancel)
+ m)
+ (lambda () (and cj/--ai-term-shutdown-timer t)))
+ (setq cj/--ai-term-shutdown-timer
+ (run-at-time
+ 0 1
+ (lambda ()
+ (if (<= remaining 0)
+ (progn
+ (cj/--ai-term-shutdown-clear-timer)
+ (shell-command cj/ai-term-shutdown-command))
+ (message "Shutting down in %d… (C-g to cancel)" remaining)
+ (setq remaining (1- remaining))))))
+ nil)))
+
;; ---------- emacsclient: keep opened files off the agent terminal ----------
;;
;; `server-start' (in system-defaults.el) leaves `server-window' nil, so
diff --git a/modules/auth-config.el b/modules/auth-config.el
index f18c0c1fd..62d773057 100644
--- a/modules/auth-config.el
+++ b/modules/auth-config.el
@@ -35,6 +35,15 @@
(require 'system-lib)
(require 'user-constants) ;; defines authinfo-file, read at load time below
+;; Lazily-loaded oauth2-auto / plstore internals used by the cache-fix advice
+;; below. oauth2-auto is required at runtime inside the advised function; these
+;; declarations satisfy the byte-compiler without forcing an eager load.
+(declare-function oauth2-auto--compute-id "oauth2-auto")
+(declare-function plstore-get "plstore")
+(declare-function plstore-close "plstore")
+(defvar oauth2-auto--plstore-cache)
+(defvar oauth2-auto-plstore)
+
(defcustom cj/auth-source-debug-enabled nil
"Non-nil means enable verbose auth-source debug logging.
diff --git a/modules/browser-config.el b/modules/browser-config.el
index 4a2c54623..d596b9e9d 100644
--- a/modules/browser-config.el
+++ b/modules/browser-config.el
@@ -109,12 +109,6 @@ Returns: \\='success if applied successfully,
(set program-var (or path executable)))
'success))))
-(defun cj/apply-browser-choice (browser-plist)
- "Apply the browser settings from BROWSER-PLIST."
- (pcase (cj/--do-apply-browser-choice browser-plist)
- ('success (message "Default browser set to: %s" (plist-get browser-plist :name)))
- ('invalid-plist (message "Invalid browser configuration"))))
-
(defun cj/--do-choose-browser (browser-plist)
"Save and apply BROWSER-PLIST as the default browser.
Returns: \\='success if browser was saved and applied,
@@ -151,7 +145,8 @@ Persists the choice for future sessions."
(defun cj/--do-initialize-browser ()
"Initialize browser configuration.
Returns: (cons \\='loaded browser-plist) if saved choice was loaded,
- (cons \\='first-available browser-plist) if using first discovered browser,
+ (cons \\='first-available browser-plist) if using first
+ discovered browser,
(cons \\='no-browsers nil) if no browsers found."
(let ((saved-choice (cj/load-browser-choice)))
(if saved-choice
diff --git a/modules/calendar-sync.el b/modules/calendar-sync.el
index 13c74ca16..c0e0e935a 100644
--- a/modules/calendar-sync.el
+++ b/modules/calendar-sync.el
@@ -223,7 +223,7 @@ Example: -21600 for CST (UTC-6), -28800 for PST (UTC-8)."
(defun calendar-sync--format-timezone-offset (offset)
"Format timezone OFFSET (in seconds) as human-readable string.
-Example: -21600 → 'UTC-6' or 'UTC-6:00'."
+Example: -21600 → `UTC-6' or `UTC-6:00'."
(if (null offset)
"unknown"
(let* ((hours (/ offset 3600))
@@ -255,8 +255,10 @@ Example: -21600 → 'UTC-6' or 'UTC-6:00'."
(dir (file-name-directory calendar-sync--state-file)))
(unless (file-directory-p dir)
(make-directory dir t))
- (with-temp-file calendar-sync--state-file
- (prin1 state (current-buffer)))))
+ (let ((tmp (make-temp-file (expand-file-name ".calendar-sync-state-" dir))))
+ (with-temp-file tmp
+ (prin1 state (current-buffer)))
+ (rename-file tmp calendar-sync--state-file t))))
(defun calendar-sync--load-state ()
"Load sync state from disk."
@@ -289,7 +291,7 @@ Example: -21600 → 'UTC-6' or 'UTC-6:00'."
"Normalize line endings in CONTENT to Unix format (LF only).
Removes all carriage return characters (\\r) from CONTENT.
The iCalendar format (RFC 5545) uses CRLF line endings, but Emacs
-and 'org-mode' expect LF only. This function ensures consistent line
+and `org-mode' expect LF only. This function ensures consistent line
endings throughout the parsing pipeline.
Returns CONTENT with all \\r characters removed."
@@ -423,14 +425,16 @@ Handles both simple values and values with parameters like TZID."
(defun calendar-sync--get-recurrence-id-line (event-str)
"Extract full RECURRENCE-ID line from EVENT-STR, including parameters.
-Returns the complete line like 'RECURRENCE-ID;TZID=Europe/Tallinn:20260203T170000'.
+Returns the complete line like
+`RECURRENCE-ID;TZID=Europe/Tallinn:20260203T170000'.
Returns nil if not found."
(when (and event-str (stringp event-str))
(calendar-sync--get-property-line event-str "RECURRENCE-ID")))
(defun calendar-sync--parse-ics-datetime (value)
"Parse iCal datetime VALUE into (year month day hour minute) list.
-Returns nil for invalid input. For date-only values, returns (year month day nil nil).
+Returns nil for invalid input. For date-only values, returns
+(year month day nil nil).
Handles formats: 20260203T090000Z, 20260203T090000, 20260203."
(when (and value
(stringp value)
@@ -454,53 +458,56 @@ Handles formats: 20260203T090000Z, 20260203T090000, 20260203."
(defalias 'calendar-sync--parse-recurrence-id #'calendar-sync--parse-ics-datetime
"Parse RECURRENCE-ID value. See `calendar-sync--parse-ics-datetime'.")
+(defun calendar-sync--parse-exception-event (event-str)
+ "Parse a RECURRENCE-ID override EVENT-STR into an exception plist, or nil.
+Returns nil when EVENT-STR carries no RECURRENCE-ID, or its recurrence-id /
+start time fail to parse. The plist holds :recurrence-id (localized),
+:recurrence-id-raw, :start, :end, :summary, :description, :location."
+ (let ((recurrence-id (calendar-sync--get-recurrence-id event-str)))
+ (when recurrence-id
+ (let* ((recurrence-id-line (calendar-sync--get-recurrence-id-line event-str))
+ (recurrence-id-tzid (calendar-sync--extract-tzid recurrence-id-line))
+ (recurrence-id-is-utc (string-suffix-p "Z" recurrence-id))
+ (recurrence-id-parsed (calendar-sync--parse-recurrence-id recurrence-id))
+ ;; Parse the new times from the exception
+ (dtstart (calendar-sync--get-property event-str "DTSTART"))
+ (dtend (calendar-sync--get-property event-str "DTEND"))
+ (dtstart-line (calendar-sync--get-property-line event-str "DTSTART"))
+ (dtend-line (calendar-sync--get-property-line event-str "DTEND"))
+ (start-tzid (calendar-sync--extract-tzid dtstart-line))
+ (end-tzid (calendar-sync--extract-tzid dtend-line))
+ (start-parsed (calendar-sync--parse-timestamp dtstart start-tzid))
+ (end-parsed (and dtend (calendar-sync--parse-timestamp dtend end-tzid)))
+ (summary (calendar-sync--clean-text
+ (calendar-sync--get-property event-str "SUMMARY")))
+ (description (calendar-sync--clean-text
+ (calendar-sync--get-property event-str "DESCRIPTION")))
+ (location (calendar-sync--clean-text
+ (calendar-sync--get-property event-str "LOCATION"))))
+ (when (and recurrence-id-parsed start-parsed)
+ (list :recurrence-id (calendar-sync--localize-parsed-datetime
+ recurrence-id-parsed recurrence-id-is-utc recurrence-id-tzid)
+ :recurrence-id-raw recurrence-id
+ :start start-parsed
+ :end end-parsed
+ :summary summary
+ :description description
+ :location location))))))
+
(defun calendar-sync--collect-recurrence-exceptions (ics-content)
"Collect all RECURRENCE-ID events from ICS-CONTENT.
Returns hash table mapping UID to list of exception event plists.
-Each exception plist contains :recurrence-id (parsed), :start, :end, :summary, etc."
+Each exception plist contains :recurrence-id (parsed), :start, :end,
+:summary, etc."
(let ((exceptions (make-hash-table :test 'equal)))
(when (and ics-content (stringp ics-content))
- (let ((events (calendar-sync--split-events ics-content)))
- (dolist (event-str events)
- (let ((recurrence-id (calendar-sync--get-recurrence-id event-str))
- (uid (calendar-sync--get-property event-str "UID")))
- (when (and recurrence-id uid)
- ;; Parse the exception event
- (let* ((recurrence-id-line (calendar-sync--get-recurrence-id-line event-str))
- (recurrence-id-tzid (calendar-sync--extract-tzid recurrence-id-line))
- (recurrence-id-is-utc (and recurrence-id
- (string-suffix-p "Z" recurrence-id)))
- (recurrence-id-parsed (calendar-sync--parse-recurrence-id recurrence-id))
- ;; Parse the new times from the exception
- (dtstart (calendar-sync--get-property event-str "DTSTART"))
- (dtend (calendar-sync--get-property event-str "DTEND"))
- (dtstart-line (calendar-sync--get-property-line event-str "DTSTART"))
- (dtend-line (calendar-sync--get-property-line event-str "DTEND"))
- (start-tzid (calendar-sync--extract-tzid dtstart-line))
- (end-tzid (calendar-sync--extract-tzid dtend-line))
- (start-parsed (calendar-sync--parse-timestamp dtstart start-tzid))
- (end-parsed (and dtend (calendar-sync--parse-timestamp dtend end-tzid)))
- (summary (calendar-sync--clean-text
- (calendar-sync--get-property event-str "SUMMARY")))
- (description (calendar-sync--clean-text
- (calendar-sync--get-property event-str "DESCRIPTION")))
- (location (calendar-sync--clean-text
- (calendar-sync--get-property event-str "LOCATION"))))
- (when (and recurrence-id-parsed start-parsed)
- (let ((local-recurrence-id
- (calendar-sync--localize-parsed-datetime
- recurrence-id-parsed recurrence-id-is-utc recurrence-id-tzid)))
- (let ((exception-plist
- (list :recurrence-id local-recurrence-id
- :recurrence-id-raw recurrence-id
- :start start-parsed
- :end end-parsed
- :summary summary
- :description description
- :location location)))
- ;; Add to hash table
- (let ((existing (gethash uid exceptions)))
- (puthash uid (cons exception-plist existing) exceptions)))))))))))
+ (dolist (event-str (calendar-sync--split-events ics-content))
+ (let ((uid (calendar-sync--get-property event-str "UID"))
+ (exception-plist (calendar-sync--parse-exception-event event-str)))
+ (when (and uid exception-plist)
+ (puthash uid
+ (cons exception-plist (gethash uid exceptions))
+ exceptions)))))
exceptions))
(defun calendar-sync--occurrence-matches-exception-p (occurrence exception)
@@ -535,7 +542,15 @@ Compares year, month, day, hour, minute."
(plist-put result :location (plist-get exception :location)))
;; Pass through new fields if exception overrides them
(when (plist-get exception :attendees)
- (plist-put result :attendees (plist-get exception :attendees)))
+ (plist-put result :attendees (plist-get exception :attendees))
+ ;; Re-derive the user's status from the overridden attendees so a
+ ;; singly-declined occurrence drops its inherited series "accepted"
+ ;; (otherwise `calendar-sync--filter-declined' can't drop it). Leave the
+ ;; inherited status when the override doesn't name the user.
+ (let ((status (calendar-sync--find-user-status
+ (plist-get exception :attendees) calendar-sync-user-emails)))
+ (when status
+ (plist-put result :status status))))
(when (plist-get exception :organizer)
(plist-put result :organizer (plist-get exception :organizer)))
(when (plist-get exception :url)
@@ -569,7 +584,8 @@ Returns new list with matching occurrences replaced by exception times."
(defun calendar-sync--get-exdates (event-str)
"Extract all EXDATE values from EVENT-STR.
-Returns list of datetime strings (without TZID parameters), or nil if none found.
+Returns list of datetime strings (without TZID parameters), or nil if
+none found.
Handles both simple values and values with parameters like TZID."
(when (and event-str (stringp event-str) (not (string-empty-p event-str)))
(let ((exdates '())
@@ -582,7 +598,8 @@ Handles both simple values and values with parameters like TZID."
(defun calendar-sync--get-exdate-line (event-str exdate-value)
"Find the full EXDATE line containing EXDATE-VALUE from EVENT-STR.
-Returns the complete line like 'EXDATE;TZID=America/New_York:20260210T130000'.
+Returns the complete line like
+`EXDATE;TZID=America/New_York:20260210T130000'.
Returns nil if not found."
(when (and event-str (stringp event-str) exdate-value)
(let ((pattern (format "^\\(EXDATE[^:]*:%s\\)" (regexp-quote exdate-value))))
@@ -616,7 +633,8 @@ Converts TZID-qualified and UTC times to local time."
(defun calendar-sync--exdate-matches-p (occurrence-start exdate)
"Check if OCCURRENCE-START matches EXDATE.
OCCURRENCE-START is (year month day hour minute).
-EXDATE is (year month day hour minute) or (year month day nil nil) for date-only.
+EXDATE is (year month day hour minute) or (year month day nil nil) for
+date-only.
Date-only EXDATE matches any time on that day."
(and occurrence-start exdate
(= (nth 0 occurrence-start) (nth 0 exdate)) ; year
@@ -680,7 +698,8 @@ Returns nil if property not found."
(defun calendar-sync--get-property-line (event property)
"Extract full PROPERTY line from EVENT string, including parameters.
-Returns the complete line like 'DTSTART;TZID=Europe/Lisbon:20260202T190000'.
+Returns the complete line like
+`DTSTART;TZID=Europe/Lisbon:20260202T190000'.
Returns nil if property not found."
(when (string-match (format "^\\(%s[^\n]*\\)$" (regexp-quote property)) event)
(match-string 1 event)))
@@ -788,8 +807,8 @@ Returns URL string or nil."
(defun calendar-sync--extract-tzid (property-line)
"Extract TZID parameter value from PROPERTY-LINE.
-PROPERTY-LINE is like 'DTSTART;TZID=Europe/Lisbon:20260202T190000'.
-Returns timezone string like 'Europe/Lisbon', or nil if no TZID.
+PROPERTY-LINE is like `DTSTART;TZID=Europe/Lisbon:20260202T190000'.
+Returns timezone string like `Europe/Lisbon', or nil if no TZID.
Returns nil for malformed lines (missing colon separator)."
(when (and property-line
(stringp property-line)
@@ -811,7 +830,7 @@ Returns list (year month day hour minute) in local timezone."
(defun calendar-sync--convert-tz-to-local (year month day hour minute source-tz)
"Convert datetime from SOURCE-TZ timezone to local time.
-SOURCE-TZ is a timezone name like 'Europe/Lisbon' or 'Asia/Yerevan'.
+SOURCE-TZ is a timezone name like `Europe/Lisbon' or `Asia/Yerevan'.
Returns list (year month day hour minute) in local timezone, or nil on error.
Uses Emacs built-in timezone support (encode-time/decode-time with ZONE
@@ -835,8 +854,10 @@ TZ database as the `date' command."
"Convert PARSED datetime to local time using timezone info.
PARSED is (year month day hour minute) or (year month day nil nil).
IS-UTC non-nil means the value had a Z suffix.
+
TZID is a timezone string like \"Europe/Lisbon\", or nil.
-Returns PARSED converted to local time, or PARSED unchanged if no conversion needed."
+Returns PARSED converted to local time, or PARSED unchanged if no
+conversion needed."
(cond
(is-utc
(calendar-sync--convert-utc-to-local
@@ -854,7 +875,8 @@ Returns PARSED converted to local time, or PARSED unchanged if no conversion nee
"Parse iCal timestamp string TIMESTAMP-STR.
Returns (year month day hour minute) or (year month day) for all-day events.
Converts UTC times (ending in Z) to local time.
-If TZID is provided (e.g., 'Europe/Lisbon'), converts from that timezone to local.
+If TZID is provided (e.g., `Europe/Lisbon'), converts from that timezone
+to local.
Returns nil if parsing fails."
(cond
;; DateTime format: 20251116T140000Z or 20251116T140000
@@ -911,7 +933,8 @@ Returns string like '<2025-11-16 Sun 14:00-15:00>' or '<2025-11-16 Sun>'."
(defun calendar-sync--date-to-time (date)
"Convert DATE to time value for comparison.
DATE should be a list starting with (year month day ...).
-Only the first three elements are used; extra elements (hour, minute) are ignored."
+Only the first three elements are used; extra elements (hour, minute) are
+ignored."
(let ((day (nth 2 date))
(month (nth 1 date))
(year (nth 0 date)))
@@ -1080,7 +1103,8 @@ Returns nil if event lacks required fields (DTSTART, SUMMARY).
Skips events with RECURRENCE-ID (individual instances of recurring events
are handled separately via exception collection).
Handles TZID-qualified timestamps by converting to local time.
-Cleans text fields (description, location, summary) via `calendar-sync--clean-text'."
+Cleans text fields (description, location, summary) via
+`calendar-sync--clean-text'."
;; Skip individual instances of recurring events (they're collected as exceptions)
(unless (calendar-sync--get-property event-str "RECURRENCE-ID")
(let* ((uid (calendar-sync--get-property event-str "UID"))
@@ -1226,11 +1250,19 @@ RECURRENCE-ID exceptions are applied to override specific occurrences."
(time-less-p (calendar-sync--event-start-time a)
(calendar-sync--event-start-time b)))))
(org-entries (mapcar #'calendar-sync--event-to-org sorted-events)))
- (if org-entries
- (concat "# Calendar Events\n\n"
- (string-join org-entries "\n\n")
- "\n")
- nil)))
+ ;; Distinguish a healthy zero-event calendar from garbage: a real
+ ;; iCalendar (carries BEGIN:VCALENDAR) with no in-window events
+ ;; returns the header alone, so the caller writes an empty calendar
+ ;; and reports success. Non-iCalendar content (an HTML error page, a
+ ;; truncated download) has no VCALENDAR and returns nil -- a failure.
+ (cond
+ (org-entries
+ (concat "# Calendar Events\n\n"
+ (string-join org-entries "\n\n")
+ "\n"))
+ ((string-match-p "BEGIN:VCALENDAR" ics-content)
+ "# Calendar Events\n\n")
+ (t nil))))
(error
(calendar-sync--log-silently "calendar-sync: Parse error: %s" (error-message-string err))
nil)))
@@ -1249,7 +1281,7 @@ invoked when the fetch completes, either successfully or with an error."
(make-process
:name "calendar-sync-curl"
:buffer buffer
- :command (list "curl" "-s" "-L"
+ :command (list "curl" "-s" "-L" "--fail"
"--connect-timeout" "10"
"--max-time" (number-to-string calendar-sync-fetch-timeout)
url)
@@ -1281,7 +1313,7 @@ owns deleting the temp file after a successful callback."
(make-process
:name "calendar-sync-curl"
:buffer buffer
- :command (list "curl" "-s" "-L"
+ :command (list "curl" "-s" "-L" "--fail"
"--connect-timeout" "10"
"--max-time" (number-to-string calendar-sync-fetch-timeout)
"-o" temp-file
@@ -1307,13 +1339,17 @@ owns deleting the temp file after a successful callback."
(funcall callback nil))))
(defun calendar-sync--write-file (content file)
- "Write CONTENT to FILE.
-Creates parent directories if needed."
+ "Write CONTENT to FILE atomically.
+Creates parent directories if needed, then writes a temp file in the same
+directory and renames it into place, so org-agenda or chime reading mid-write
+never sees a half-written calendar."
(let ((dir (file-name-directory file)))
(unless (file-directory-p dir)
- (make-directory dir t)))
- (with-temp-file file
- (insert content)))
+ (make-directory dir t))
+ (let ((tmp (make-temp-file (expand-file-name ".calendar-sync-" dir))))
+ (with-temp-file tmp
+ (insert content))
+ (rename-file tmp file t))))
(defun calendar-sync--emacs-binary ()
"Return the Emacs executable to use for calendar conversion workers."
diff --git a/modules/calibredb-epub-config.el b/modules/calibredb-epub-config.el
index a17bf8c91..1e6437d26 100644
--- a/modules/calibredb-epub-config.el
+++ b/modules/calibredb-epub-config.el
@@ -77,6 +77,13 @@
(defvar calibredb-show-entry-switch) ; from calibredb-show.el
(defvar calibredb-sort-by) ; from calibredb-core.el
(defvar calibredb-search-filter) ; from calibredb-search.el
+;; calibredb filter-state vars (set by cj/calibredb-clear-filters and friends)
+(defvar calibredb-tag-filter-p) ; from calibredb-search.el
+(defvar calibredb-favorite-filter-p) ; from calibredb-search.el
+(defvar calibredb-author-filter-p) ; from calibredb-search.el
+(defvar calibredb-date-filter-p) ; from calibredb-search.el
+(defvar calibredb-format-filter-p) ; from calibredb-search.el
+(defvar calibredb-search-current-page) ; from calibredb-search.el
;; -------------------------- CalibreDB Ebook Manager --------------------------
@@ -241,6 +248,29 @@ layout passes -- each pass narrows the body width but not the natural width."
"Return the preferred EPUB text column count for WINDOW."
(cj/nov--text-width (cj/nov--natural-window-width window)))
+(defun cj/nov--rerender-preserving-position ()
+ "Re-render the nov document, restoring point's relative position.
+Capture point as a fraction of the buffer, re-render, then move point to the
+same fraction of the re-rendered buffer so the reading position is kept
+approximately."
+ (let ((frac (when (> (point-max) (point-min))
+ (/ (float (- (point) (point-min)))
+ (- (point-max) (point-min))))))
+ (nov-render-document)
+ (when frac
+ (goto-char (+ (point-min)
+ (round (* frac (- (point-max) (point-min)))))))))
+
+(defun cj/nov--center-in-window (win total width)
+ "Center a WIDTH-column text block in WIN, given its TOTAL natural width.
+Set equal left/right display margins and push the fringes to the window edge."
+ ;; floor: never let the margins squeeze the text area below WIDTH.
+ (let ((margin (max 0 (/ (- total width) 2))))
+ (set-window-margins win margin margin))
+ ;; Push the fringes out to the window's edge; otherwise they sit between the
+ ;; margin and the text and show as thin vertical lines beside it.
+ (set-window-fringes win nil nil t))
+
(defun cj/nov-update-layout (&optional _frame)
"Size the EPUB text column for this buffer and center it in its window.
`nov-text-width' is set so nov's `shr' fills the text to roughly 80% of the
@@ -256,20 +286,9 @@ command."
(width (cj/nov--text-width total)))
(unless (eql nov-text-width width)
(setq-local nov-text-width width)
- (let ((frac (when (> (point-max) (point-min))
- (/ (float (- (point) (point-min)))
- (- (point-max) (point-min))))))
- (nov-render-document)
- (when frac
- (goto-char (+ (point-min)
- (round (* frac (- (point-max) (point-min)))))))))
+ (cj/nov--rerender-preserving-position))
(when win
- ;; floor: never let the margins squeeze the text area below WIDTH.
- (let ((margin (max 0 (/ (- total width) 2))))
- (set-window-margins win margin margin))
- ;; Push the fringes out to the window's edge; otherwise they sit between
- ;; the margin and the text and show as thin vertical lines beside it.
- (set-window-fringes win nil nil t)))))
+ (cj/nov--center-in-window win total width)))))
(defun cj/--nov-adjust-margin (delta)
"Add DELTA to `cj/nov-margin-percent' (clamped 0..25), re-lay-out, and report.
@@ -293,11 +312,12 @@ A positive DELTA narrows the text column; a negative DELTA widens it."
(defun cj/nov-apply-preferences ()
"Apply preferences after nov-mode has launched."
(interactive)
- ;; Use Merriweather for comfortable reading with appropriate scaling
- ;; Darker sepia color (#E8DCC0) is easier on the eyes than pure white
- (face-remap-add-relative 'variable-pitch :family "Merriweather" :height 1.0 :foreground "#E8DCC0")
- (face-remap-add-relative 'default :family "Merriweather" :height 180 :foreground "#E8DCC0")
- (face-remap-add-relative 'fixed-pitch :height 180 :foreground "#E8DCC0")
+ ;; Use Merriweather for comfortable reading with appropriate scaling.
+ ;; (Reading fg color stripped; falls back to the theme default until a
+ ;; themeable reading face exists -- see todo.org.)
+ (face-remap-add-relative 'variable-pitch :family "Merriweather" :height 1.0)
+ (face-remap-add-relative 'default :family "Merriweather" :height 180)
+ (face-remap-add-relative 'fixed-pitch :height 180)
;; Enable visual-line-mode for proper text wrapping
(visual-line-mode 1)
;; Set fill-column as a fallback
diff --git a/modules/chrono-tools.el b/modules/chrono-tools.el
index 9ccba6676..744781268 100644
--- a/modules/chrono-tools.el
+++ b/modules/chrono-tools.el
@@ -22,6 +22,11 @@
(require 'user-constants)
+;; Declared by the lazily-loaded `tmr' package; quiet the byte-compiler
+;; without forcing the package to load.
+(defvar tmr-sound-file)
+(defvar tmr-descriptions-list)
+
;; -------------------------------- Time Zones ---------------------------------
(use-package time-zones
@@ -66,6 +71,19 @@ Returns nil if `sounds-dir' does not exist."
(message "Timer sound reset to default: %s"
(file-name-nondirectory notification-sound)))
+(defun cj/tmr--current-sound-name ()
+ "Return the basename of the current `tmr-sound-file' if it exists, else nil."
+ (when (and tmr-sound-file (file-exists-p tmr-sound-file))
+ (file-name-nondirectory tmr-sound-file)))
+
+(defun cj/tmr--apply-sound-file (selected-file)
+ "Set `tmr-sound-file' to SELECTED-FILE, a basename within `sounds-dir'.
+Return the confirmation message string (noting when it is the default sound)."
+ (setq tmr-sound-file (expand-file-name selected-file sounds-dir))
+ (if (equal tmr-sound-file notification-sound)
+ (format "Timer sound set to default: %s" selected-file)
+ (format "Timer sound set to: %s" selected-file)))
+
(defun cj/tmr-select-sound-file ()
"Select a sound file from `sounds-dir' to use for tmr timers.
@@ -80,13 +98,9 @@ Present all audio files in the sounds directory and set the chosen file as
(if (boundp 'sounds-dir) sounds-dir "<unset>")))
(t
(let ((sound-files (cj/tmr--available-sound-files)))
- (cond
- ((null sound-files)
- (message "No audio files found in %s" sounds-dir))
- (t
- (let* ((current-file (when (and tmr-sound-file
- (file-exists-p tmr-sound-file))
- (file-name-nondirectory tmr-sound-file)))
+ (if (null sound-files)
+ (message "No audio files found in %s" sounds-dir)
+ (let* ((current-file (cj/tmr--current-sound-name))
(selected-file
(completing-read
(format "Select timer sound%s: "
@@ -94,14 +108,9 @@ Present all audio files in the sounds directory and set the chosen file as
(format " (current: %s)" current-file)
""))
sound-files nil t nil nil current-file)))
- (cond
- ((or (null selected-file) (string-empty-p selected-file))
- (message "No file selected"))
- (t
- (setq tmr-sound-file (expand-file-name selected-file sounds-dir))
- (if (equal tmr-sound-file notification-sound)
- (message "Timer sound set to default: %s" selected-file)
- (message "Timer sound set to: %s" selected-file)))))))))))
+ (if (or (null selected-file) (string-empty-p selected-file))
+ (message "No file selected")
+ (message "%s" (cj/tmr--apply-sound-file selected-file)))))))))
(use-package tmr
:defer 0.5
diff --git a/modules/cj-window-geometry-lib.el b/modules/cj-window-geometry-lib.el
index 047fe7c45..4484a1d15 100644
--- a/modules/cj-window-geometry-lib.el
+++ b/modules/cj-window-geometry-lib.el
@@ -42,21 +42,34 @@ fails to span the full height."
((not spans-full-height) (if (= top root-top) 'above 'below))
(t (or default 'right)))))
-(defun cj/window-body-size (window direction)
- "Return WINDOW's body size on the axis matching DIRECTION.
+(defun cj/window-replay-size (window direction)
+ "Return WINDOW's size to capture for geometry replay, on DIRECTION's axis.
Returns body-width (columns) when DIRECTION is right or left.
-Returns body-height (lines) when DIRECTION is below or above.
-
-Body size, not total size, is the right thing to capture for
-geometry replay: total-width includes the right-side divider when
-the window has a right sibling but excludes it at the frame edge,
-so a captured rightmost window replayed into a middle position
-would leave the body 1 col short. Body size is divider-
-independent and matches what the user actually sees."
+Returns total-height (lines) when DIRECTION is below or above.
+
+The axis choice is deliberately asymmetric, for two different reasons:
+
+- Width: body-width, not total-width. Total-width includes the right-side
+ divider when the window has a right sibling but excludes it at the frame
+ edge, so a captured rightmost window replayed into a middle position would
+ leave the body 1 col short. Body-width is divider-independent and matches
+ what the user sees.
+
+- Height: total-height, not body-height. Every window carries exactly one
+ mode line regardless of position, so total-height has no analog of the
+ divider-position problem -- it is position-independent. Body-height does
+ NOT work here: it subtracts the mode line's *pixel* height, which differs
+ between an active (full-height) and an inactive (theme-shrunk) mode line.
+ Capturing body-height while the window is active and replaying it while the
+ window is displayed inactive then re-measuring active drifts the value down
+ by ~1 line per toggle whenever the inactive mode line is shorter than a text
+ line (e.g. a theme that sets `mode-line-inactive' to a sub-line height).
+ Total-height is identical active or inactive, so the capture/replay
+ round-trip is a fixed point."
(if (memq direction '(right left))
(window-body-width window)
- (window-body-height window)))
+ (window-total-height window)))
(defun cj/cardinal-to-edge-direction (direction)
"Map cardinal DIRECTION to its `display-buffer-in-direction' edge variant.
@@ -129,5 +142,39 @@ the fraction at toggle-off, replay it on the next toggle-on."
(hi (or max-frac 0.95)))
(max lo (min hi (/ (float window-size) frame-size))))))
+(defcustom cj/window-dock-min-columns 80
+ "Minimum body columns each pane must keep for a side-by-side dock.
+
+`cj/preferred-dock-direction' docks a companion panel as a side-by-side
+column only when both the panel and the main window would stay at least
+this wide; otherwise it stacks the panel below. 80 is the classic
+terminal/code width."
+ :type 'integer
+ :group 'windows)
+
+(defun cj/preferred-dock-direction (frame-cols fraction &optional min-cols)
+ "Return the dock direction for a companion panel beside the main window.
+
+Returns `right' (a side-by-side column) when a split that gives the panel
+FRACTION of FRAME-COLS would leave both panes at least MIN-COLS columns
+wide; otherwise `below' (a stacked panel). FRAME-COLS is the frame's
+total column count; FRACTION is the panel's share of the width, in the
+open interval (0, 1). MIN-COLS defaults to `cj/window-dock-min-columns'.
+
+The narrower of the two resulting panes governs: the panel takes
+round(FRACTION * FRAME-COLS) columns, the main window takes the rest less
+one divider column, and `right' is returned only when the smaller of the
+two clears MIN-COLS. Returns `below' for degenerate input (non-positive
+FRAME-COLS, or FRACTION outside (0, 1)) so a caller always gets a usable
+stacked fallback."
+ (let ((min-cols (or min-cols cj/window-dock-min-columns)))
+ (if (and (numberp frame-cols) (> frame-cols 0)
+ (numberp fraction) (< 0 fraction 1))
+ (let* ((panel (round (* fraction frame-cols)))
+ (main (- frame-cols panel 1))
+ (narrower (min panel main)))
+ (if (>= narrower min-cols) 'right 'below))
+ 'below)))
+
(provide 'cj-window-geometry-lib)
;;; cj-window-geometry-lib.el ends here
diff --git a/modules/cj-window-toggle-lib.el b/modules/cj-window-toggle-lib.el
index ba91f5a40..175a1d958 100644
--- a/modules/cj-window-toggle-lib.el
+++ b/modules/cj-window-toggle-lib.el
@@ -44,7 +44,7 @@ No-op when WINDOW is nil or not live."
(if (or (null allowed) (memq dir allowed))
(progn
(set direction-var dir)
- (set size-var (cj/window-body-size window dir)))
+ (set size-var (cj/window-replay-size window dir)))
(set direction-var default-direction)
(set size-var nil)))))
@@ -59,10 +59,12 @@ DEFAULT-SIZE when the stored values are nil. The cardinal direction
is mapped to its frame-edge variant via
`cj/cardinal-to-edge-direction' so the new buffer always lands at
the same frame edge regardless of the selected window. An integer
-size is wrapped in a `(body-columns . N)' / `(body-lines . N)' cons
-so `display-buffer-in-direction' sets the body explicitly,
-divider-independent. A float size passes through as a fraction of
-the new window's parent.
+size is wrapped per axis: a width size as a `(body-columns . N)'
+cons (divider-independent body width), a height size as a plain
+integer total-line count. Height uses total rather than body so the
+capture/replay round-trip is immune to the mode line's pixel height
+(see `cj/window-replay-size'). A float size passes through as a
+fraction of the new window's parent.
Caller-supplied ALIST entries for direction, window-width, or
window-height are stripped before delegating to
@@ -74,15 +76,15 @@ placement; the remaining alist entries are passed through."
(edge-direction (or (cj/cardinal-to-edge-direction direction)
(cj/cardinal-to-edge-direction default-direction)))
(size (or stored-size default-size))
- (size-key (if (memq direction '(right left))
- 'window-width
- 'window-height))
- (body-tag (if (memq direction '(right left))
- 'body-columns
- 'body-lines))
- (size-value (if (integerp size)
- (cons body-tag size)
- size))
+ (width-axis (memq direction '(right left)))
+ (size-key (if width-axis 'window-width 'window-height))
+ ;; A width integer is a body-column count (divider-independent); a
+ ;; height integer is a plain total-line count (mode-line-pixel-
+ ;; independent -- see `cj/window-replay-size'). Floats pass through.
+ (size-value (cond
+ ((not (integerp size)) size)
+ (width-axis (cons 'body-columns size))
+ (t size)))
(filtered (cl-remove-if
(lambda (cell)
(memq (car-safe cell)
diff --git a/modules/config-utilities.el b/modules/config-utilities.el
index b3eec5d3d..f448327c1 100644
--- a/modules/config-utilities.el
+++ b/modules/config-utilities.el
@@ -21,6 +21,19 @@
(require 'find-lisp)
(require 'profiler)
+;; External variables referenced at runtime only (org and the native
+;; compiler are loaded lazily; declare to quiet the byte-compiler).
+(defvar comp-async-report-warnings-errors)
+(defvar org-ts-regexp)
+(defvar org-agenda-files)
+
+;; External functions referenced at runtime only.
+(declare-function org-element-parse-buffer "org-element")
+(declare-function org-element-map "org-element")
+(declare-function org-element-property "org-element-ast")
+(declare-function org-time-string-to-absolute "org")
+(declare-function org-alert-check "org-alert")
+
;;; -------------------------------- Debug Keymap -------------------------------
(defvar-keymap cj/debug-config-keymap
@@ -65,13 +78,15 @@
(with-eval-after-load 'emacsql-sqlite-builtin
(cl-defmethod emacsql-close :around
((connection emacsql-sqlite-builtin-connection))
- (when (oref connection handle)
+ ;; The class is loaded lazily, so the slot is unknown at compile time.
+ (when (with-no-warnings (oref connection handle))
(cl-call-next-method))))
(with-eval-after-load 'emacsql-sqlite-module
(cl-defmethod emacsql-close :around
((connection emacsql-sqlite-module-connection))
- (when (oref connection handle)
+ ;; The class is loaded lazily, so the slot is unknown at compile time.
+ (when (with-no-warnings (oref connection handle))
(cl-call-next-method))))
;;; -------------------------------- Benchmarking -------------------------------
diff --git a/modules/coverage-core.el b/modules/coverage-core.el
index 687a042fe..e8f7a4740 100644
--- a/modules/coverage-core.el
+++ b/modules/coverage-core.el
@@ -25,6 +25,15 @@
(require 'subr-x)
(require 'system-lib)
+;; Make json.el's reader variables visible to the byte/native compiler so the
+;; `let' bindings of `json-object-type' / `json-array-type' / `json-key-type'
+;; in the parse helpers below bind dynamically. Without this the compiler
+;; treats them as lexical (this file is lexical-binding), the bindings never
+;; reach `json-read-file', and it returns json.el's default alist instead of
+;; the hash tables the parsers maphash over. The runtime `(require 'json)'
+;; inside each helper still keeps json off the load-time path.
+(eval-when-compile (require 'json))
+
(defvar cj/coverage-backends nil
"Registry of coverage backends in priority order.
Each entry is a plist with at least :name, :detect, :run, and :report-path.
@@ -249,6 +258,27 @@ Signals `user-error' for any other SCOPE."
(maphash (lambda (k _v) (push k keys)) table)
(sort keys #'<)))
+(defun cj/--coverage-relativize-keys (table root)
+ "Return a copy of TABLE with each file-path key made relative to ROOT.
+An absolute key is relativized against ROOT via `file-relative-name'; an
+already-relative key is kept as-is. Line-set values are shared, not copied.
+
+`cj/--coverage-parse-simplecov' emits absolute path keys (simplecov reports
+absolute source paths) while `cj/--coverage-parse-diff-output' emits
+repo-relative keys (git's \"+++ b/<path>\"). Both must be normalized to
+repo-relative before `cj/--coverage-intersect' joins them by key, or every
+diff-aware match misses and each changed file reads `:tracked nil'."
+ (let ((result (make-hash-table :test 'equal)))
+ (when table
+ (maphash
+ (lambda (path lines)
+ (let ((key (if (file-name-absolute-p path)
+ (file-relative-name path root)
+ path)))
+ (puthash key lines result)))
+ table))
+ result))
+
(defun cj/--coverage-intersect (covered changed)
"Combine COVERED (LCOV) with CHANGED (git diff) into per-file records.
COVERED and CHANGED are each hash tables from file path to a hash table
@@ -479,10 +509,14 @@ line in the simplecov data — the intersect then classifies each line
as covered or uncovered. For diff-aware scopes, the changed set
comes from `git diff' via `cj/--coverage-changed-lines'."
(let* ((report-path (funcall (plist-get backend :report-path)))
- (covered (cj/--coverage-parse-simplecov report-path))
- (changed (if (eq scope 'whole-project)
- (cj/--coverage-simplecov-executable-lines report-path)
- (cj/--coverage-changed-lines scope)))
+ (root (cj/--coverage-project-root))
+ (covered (cj/--coverage-relativize-keys
+ (cj/--coverage-parse-simplecov report-path) root))
+ (changed (cj/--coverage-relativize-keys
+ (if (eq scope 'whole-project)
+ (cj/--coverage-simplecov-executable-lines report-path)
+ (cj/--coverage-changed-lines scope))
+ root))
(records (cj/--coverage-intersect covered changed)))
(cj/--coverage-render-to-buffer records scope)))
diff --git a/modules/custom-case.el b/modules/custom-case.el
index d30ebf942..876226958 100644
--- a/modules/custom-case.el
+++ b/modules/custom-case.el
@@ -49,6 +49,18 @@
(downcase-region (car bounds) (cdr bounds))
(user-error "No symbol at point")))))
+(defun cj/--title-case-capitalize-word-p (word is-first prev-word-end word-skip chars-skip-reset)
+ "Return non-nil when WORD at point should be capitalized in title case.
+Point is at WORD's first character. WORD is capitalized when it is the first
+word (IS-FIRST), is not a minor skip word (in WORD-SKIP), or immediately follows
+a skip-reset character (one of CHARS-SKIP-RESET: : ! ?), reached by skipping
+blanks back to PREV-WORD-END."
+ (or is-first
+ (not (member word word-skip))
+ (save-excursion
+ (and (not (zerop (skip-chars-backward "[:blank:]" prev-word-end)))
+ (memq (char-before (point)) chars-skip-reset)))))
+
(defun cj/title-case-region ()
"Capitalize the region in title case format.
Title case is a capitalization convention where major words are capitalized,
@@ -58,67 +70,53 @@ considered major words. Short (i.e., three letters or fewer) conjunctions,
short prepositions, and all articles are considered minor words."
(interactive)
(let ((beg nil)
- (end nil)
- (prev-word-end nil)
- ;; Allow capitals for skip characters after this, so:
- ;; Warning: An Example
- ;; Capitalizes the `An'.
- (chars-skip-reset '(?: ?! ??))
- ;; Don't capitalize characters directly after these. e.g.
- ;; "Foo-bar" or "Foo\bar" or "Foo's".
-
- (chars-separator '(?\\ ?- ?' ?.))
-
- (word-chars "[:alnum:]")
- (word-skip
- (list "a" "an" "and" "as" "at" "but" "by"
- "for" "if" "in" "is" "nor" "of"
- "on" "or" "so" "the" "to" "yet"))
- (is-first t))
- (cond
- ((region-active-p)
- (setq beg (region-beginning))
- (setq end (region-end)))
- (t
- (setq beg (line-beginning-position))
- (setq end (line-end-position))))
- (save-excursion
- ;; work on uppercased text (e.g., headlines) by downcasing first
- (downcase-region beg end)
- (goto-char beg)
-
- (while (< (point) end)
- (setq prev-word-end (point))
- (skip-chars-forward (concat "^" word-chars) end)
- (when (>= (point) end) ;; no word chars remaining
- (goto-char end))
- (let ((word-end
- (save-excursion
- (skip-chars-forward word-chars end)
- (point))))
-
- (unless (or (>= (point) end)
- (memq (char-before (point)) chars-separator))
- (let* ((c-orig (char-to-string (char-after (point))))
- (c-up (capitalize c-orig)))
- (unless (string-equal c-orig c-up)
- (let ((word (buffer-substring-no-properties (point) word-end)))
- (when
- (or
- ;; Always allow capitalization.
- is-first
- ;; If it's not a skip word, allow.
- (not (member word word-skip))
- ;; Check the beginning of the previous word doesn't reset first.
- (save-excursion
- (and
- (not (zerop
- (skip-chars-backward "[:blank:]" prev-word-end)))
- (memq (char-before (point)) chars-skip-reset))))
- (delete-region (point) (1+ (point)))
- (insert c-up))))))
- (goto-char word-end)
- (setq is-first nil))))))
+ (end nil)
+ (prev-word-end nil)
+ ;; Allow capitals for skip characters after this, so:
+ ;; Warning: An Example
+ ;; Capitalizes the `An'.
+ (chars-skip-reset '(?: ?! ??))
+ ;; Don't capitalize characters directly after these. e.g.
+ ;; "Foo-bar" or "Foo\bar" or "Foo's".
+ (chars-separator '(?\\ ?- ?' ?.))
+ (word-chars "[:alnum:]")
+ (word-skip
+ (list "a" "an" "and" "as" "at" "but" "by"
+ "for" "if" "in" "is" "nor" "of"
+ "on" "or" "so" "the" "to" "yet"))
+ (is-first t))
+ (cond
+ ((region-active-p)
+ (setq beg (region-beginning))
+ (setq end (region-end)))
+ (t
+ (setq beg (line-beginning-position))
+ (setq end (line-end-position))))
+ (save-excursion
+ ;; work on uppercased text (e.g., headlines) by downcasing first
+ (downcase-region beg end)
+ (goto-char beg)
+ (while (< (point) end)
+ (setq prev-word-end (point))
+ (skip-chars-forward (concat "^" word-chars) end)
+ (when (>= (point) end) ;; no word chars remaining
+ (goto-char end))
+ (let ((word-end
+ (save-excursion
+ (skip-chars-forward word-chars end)
+ (point))))
+ (unless (or (>= (point) end)
+ (memq (char-before (point)) chars-separator))
+ (let* ((c-orig (char-to-string (char-after (point))))
+ (c-up (capitalize c-orig)))
+ (unless (string-equal c-orig c-up)
+ (let ((word (buffer-substring-no-properties (point) word-end)))
+ (when (cj/--title-case-capitalize-word-p
+ word is-first prev-word-end word-skip chars-skip-reset)
+ (delete-region (point) (1+ (point)))
+ (insert c-up))))))
+ (goto-char word-end)
+ (setq is-first nil))))))
;; replace the capitalize-region keybinding to call title-case
(keymap-global-set "<remap> <capitalize-region>" #'cj/title-case-region)
diff --git a/modules/custom-comments.el b/modules/custom-comments.el
index cae911061..231a03860 100644
--- a/modules/custom-comments.el
+++ b/modules/custom-comments.el
@@ -109,6 +109,14 @@ inputs. Used by all divider / border helpers below."
decoration-char))
decoration-char)
+(defun cj/--comment-emit-prefix (cmt-start)
+ "Insert CMT-START -- doubled when it is a lone semicolon -- and a trailing space.
+A bare =;= is doubled to =;;= so the line reads as an Emacs-Lisp comment. This
+is the line-opening prologue shared by the divider and inline-border emitters."
+ (insert cmt-start)
+ (when (equal cmt-start ";") (insert cmt-start))
+ (insert " "))
+
;; ----------------------------- Inline Border ---------------------------------
(defun cj/--comment-inline-border (cmt-start cmt-end decoration-char text length)
@@ -138,10 +146,7 @@ LENGTH is the total width of the line."
(error "Length %d is too small for text '%s' (need at least %d more chars)"
length text (- min-space space-on-each-side)))
;; Generate the line
- (insert cmt-start)
- (when (equal cmt-start ";")
- (insert cmt-start))
- (insert " ")
+ (cj/--comment-emit-prefix cmt-start)
;; Left decoration
(dotimes (_ space-on-each-side)
(insert decoration-char))
@@ -181,48 +186,11 @@ Uses the lesser of `fill-column\\=' or 80 for line length."
CMT-START and CMT-END are the comment syntax strings.
DECORATION-CHAR is the character to use for the divider lines.
TEXT is the comment text.
-LENGTH is the total width of each line."
- (cj/--validate-decoration-char decoration-char)
- (let* ((current-column-pos (current-column))
- (min-length (+ current-column-pos
- (length cmt-start)
- (if (equal cmt-start ";") 1 0) ; doubled semicolon
- 1 ; space after comment-start
- 3 ; minimum decoration chars
- (if (string-empty-p cmt-end) 0 (1+ (length cmt-end))))))
- (when (< length min-length)
- (error "Length %d is too small to generate comment (minimum %d)" length min-length))
- (let* ((available-width (- length current-column-pos
- (length cmt-start)
- (if (string-empty-p cmt-end) 0 (1+ (length cmt-end)))))
- (line (make-string available-width (string-to-char decoration-char))))
- ;; Top line
- (insert cmt-start)
- (when (equal cmt-start ";") (insert cmt-start))
- (insert " ")
- (insert line)
- (when (not (string-empty-p cmt-end))
- (insert " " cmt-end))
- (newline)
-
- ;; Text line
- (dotimes (_ current-column-pos) (insert " "))
- (insert cmt-start)
- (when (equal cmt-start ";") (insert cmt-start))
- (insert " " text)
- (when (not (string-empty-p cmt-end))
- (insert " " cmt-end))
- (newline)
+LENGTH is the total width of each line.
- ;; Bottom line
- (dotimes (_ current-column-pos) (insert " "))
- (insert cmt-start)
- (when (equal cmt-start ";") (insert cmt-start))
- (insert " ")
- (insert line)
- (when (not (string-empty-p cmt-end))
- (insert " " cmt-end))
- (newline))))
+A simple divider is a padded divider with no padding before the text, so it
+delegates to `cj/--comment-padded-divider' with PADDING 0."
+ (cj/--comment-padded-divider cmt-start cmt-end decoration-char text length 0))
(defun cj/comment-simple-divider ()
"Insert a simple divider comment banner.
@@ -276,9 +244,7 @@ PADDING is the number of spaces before the text."
(if (string-empty-p cmt-end) 0 (1+ (length cmt-end)))))
(line (make-string available-width (string-to-char decoration-char))))
;; Top line
- (insert cmt-start)
- (when (equal cmt-start ";") (insert cmt-start))
- (insert " ")
+ (cj/--comment-emit-prefix cmt-start)
(insert line)
(when (not (string-empty-p cmt-end))
(insert " " cmt-end))
@@ -286,9 +252,7 @@ PADDING is the number of spaces before the text."
;; Text line with padding
(dotimes (_ current-column-pos) (insert " "))
- (insert cmt-start)
- (when (equal cmt-start ";") (insert cmt-start))
- (insert " ")
+ (cj/--comment-emit-prefix cmt-start)
(dotimes (_ padding) (insert " "))
(insert text)
(when (not (string-empty-p cmt-end))
@@ -297,9 +261,7 @@ PADDING is the number of spaces before the text."
;; Bottom line
(dotimes (_ current-column-pos) (insert " "))
- (insert cmt-start)
- (when (equal cmt-start ";") (insert cmt-start))
- (insert " ")
+ (cj/--comment-emit-prefix cmt-start)
(insert line)
(when (not (string-empty-p cmt-end))
(insert " " cmt-end))
@@ -335,12 +297,12 @@ Prompts for decoration character, text, padding, and length option."
;; -------------------------------- Comment Box --------------------------------
-(defun cj/--comment-box (cmt-start cmt-end decoration-char text length)
- "Internal implementation: Generate a 3-line box comment with centered text.
-CMT-START and CMT-END are the comment syntax strings.
-DECORATION-CHAR is the character to use for borders.
-TEXT is the comment text (centered).
-LENGTH is the total width of each line."
+(defun cj/--comment-box-emit (cmt-start cmt-end decoration-char text length heavy)
+ "Emit a box comment with centered TEXT; the border/text/border skeleton.
+CMT-START and CMT-END are the comment syntax strings. DECORATION-CHAR borders
+the box. LENGTH is the total width of each line. When HEAVY is non-nil, an
+interior blank-bordered line is added above and below the text line (the only
+difference between the plain box and the heavy box)."
(cj/--validate-decoration-char decoration-char)
(let* ((current-column-pos (current-column))
(comment-char (if (equal cmt-start ";") ";;" cmt-start))
@@ -363,11 +325,22 @@ LENGTH is the total width of each line."
(padding-each-side (max 1 (/ (- text-available text-length) 2)))
(right-padding (if (= (% (- text-available text-length) 2) 0)
padding-each-side
- (1+ padding-each-side))))
+ (1+ padding-each-side)))
+ ;; Interior side-border line: repeats the comment prefix and suffix so
+ ;; the blank rows stay valid comments in line-comment languages (elisp,
+ ;; Python). Only inserted for the heavy box.
+ (empty-line (concat comment-char " " decoration-char
+ (make-string (- available-width 2) ?\s)
+ decoration-char " " comment-end-char)))
;; Top border
(insert comment-char " " border-line " " comment-end-char)
(newline)
+ (when heavy
+ (dotimes (_ current-column-pos) (insert " "))
+ (insert empty-line)
+ (newline))
+
;; Centered text line with side borders
(dotimes (_ current-column-pos) (insert " "))
(insert comment-char " " decoration-char " ")
@@ -377,11 +350,24 @@ LENGTH is the total width of each line."
(insert " " decoration-char " " comment-end-char)
(newline)
+ (when heavy
+ (dotimes (_ current-column-pos) (insert " "))
+ (insert empty-line)
+ (newline))
+
;; Bottom border
(dotimes (_ current-column-pos) (insert " "))
(insert comment-char " " border-line " " comment-end-char)
(newline))))
+(defun cj/--comment-box (cmt-start cmt-end decoration-char text length)
+ "Internal implementation: Generate a 3-line box comment with centered text.
+CMT-START and CMT-END are the comment syntax strings.
+DECORATION-CHAR is the character to use for borders.
+TEXT is the comment text (centered).
+LENGTH is the total width of each line."
+ (cj/--comment-box-emit cmt-start cmt-end decoration-char text length nil))
+
(defun cj/comment-box ()
"Insert a 3-line comment box with centered text.
Prompts for decoration character, text, and uses `fill-column' for length."
@@ -404,62 +390,11 @@ Prompts for decoration character, text, and uses `fill-column' for length."
CMT-START and CMT-END are the comment syntax strings.
DECORATION-CHAR is the character to use for borders.
TEXT is the comment text (centered).
-LENGTH is the total width of each line."
- (cj/--validate-decoration-char decoration-char)
- (let* ((current-column-pos (current-column))
- (comment-char (if (equal cmt-start ";") ";;" cmt-start))
- (comment-end-char (if (string-empty-p cmt-end) comment-char cmt-end))
- (min-length (+ current-column-pos
- (length comment-char)
- 2 ; spaces around content
- (length comment-end-char)
- 6))) ; 3 border chars + text space + 3 border chars
- (when (< length min-length)
- (error "Length %d is too small to generate comment (minimum %d)" length min-length))
- (let* ((available-width (- length current-column-pos
- (length comment-char)
- (length comment-end-char)
- 2)) ; spaces around content
- (border-line (make-string available-width (string-to-char decoration-char)))
- (text-available (- available-width 4)) ; 2 side decorations, 2 spaces
- (text-length (length text))
- (padding-each-side (max 1 (/ (- text-available text-length) 2)))
- (right-padding (if (= (% (- text-available text-length) 2) 0)
- padding-each-side
- (1+ padding-each-side)))
- ;; Interior side-border lines repeat the comment prefix and suffix so
- ;; the empty/text rows stay valid comments in line-comment languages
- ;; (elisp, Python). Previously they began with a bare decoration char.
- (empty-line (concat comment-char " " decoration-char
- (make-string (- available-width 2) ?\s)
- decoration-char " " comment-end-char)))
- ;; Top border
- (insert comment-char " " border-line " " comment-end-char)
- (newline)
-
- ;; Empty line with side borders
- (dotimes (_ current-column-pos) (insert " "))
- (insert empty-line)
- (newline)
-
- ;; Centered text line
- (dotimes (_ current-column-pos) (insert " "))
- (insert comment-char " " decoration-char " ")
- (dotimes (_ padding-each-side) (insert " "))
- (insert text)
- (dotimes (_ right-padding) (insert " "))
- (insert " " decoration-char " " comment-end-char)
- (newline)
-
- ;; Empty line with side borders
- (dotimes (_ current-column-pos) (insert " "))
- (insert empty-line)
- (newline)
+LENGTH is the total width of each line.
- ;; Bottom border
- (dotimes (_ current-column-pos) (insert " "))
- (insert comment-char " " border-line " " comment-end-char)
- (newline))))
+A heavy box is a box with an interior blank-bordered line above and below the
+text, so it delegates to `cj/--comment-box-emit' with HEAVY non-nil."
+ (cj/--comment-box-emit cmt-start cmt-end decoration-char text length t))
(defun cj/comment-heavy-box ()
"Insert a heavy box comment with blank lines around centered text.
diff --git a/modules/custom-datetime.el b/modules/custom-datetime.el
index 87b286de7..6bca494d8 100644
--- a/modules/custom-datetime.el
+++ b/modules/custom-datetime.el
@@ -22,15 +22,16 @@
;; - cj/insert-sortable-date
;; - cj/insert-readable-date
;;
-;; Each command uses a corresponding format variable:
+;; Each command is generated by `cj/--define-datetime-inserter' from a
+;; corresponding format variable:
;; readable-date-time-format, sortable-date-time-format,
;; sortable-time-format, readable-time-format,
;; sortable-date-format, readable-date-format.
-;; Customize these (see =format-time-string') to change output.
+;; Customize these (see `format-time-string') to change output.
;; Some defaults include a trailing space for convenient typing.
;;
;; Key bindings:
-;; A prefix map =cj/datetime-map' is installed on "d" under =cj/custom-keymap':
+;; A prefix map `cj/datetime-map' is installed on "d" under `cj/custom-keymap':
;; r → readable date+time
;; s → sortable date+time
;; t → sortable time
@@ -42,17 +43,26 @@
(require 'keybindings) ;; provides cj/custom-keymap
+(defmacro cj/--define-datetime-inserter (name format-var thing)
+ "Define interactive command NAME inserting the current THING at point.
+THING is a short noun phrase (\"date and time\", \"time\", \"date\") used in
+the docstring. The inserted text is `format-time-string' applied to
+FORMAT-VAR's value, so customizing FORMAT-VAR changes the output."
+ (declare (indent defun))
+ `(defun ,name ()
+ ,(format "Insert the current %s into the current buffer.\nUse `%s' for formatting."
+ thing format-var)
+ (interactive)
+ (insert (format-time-string ,format-var (current-time)))))
+
;; ----------------------------- Readable Date Time ----------------------------
(defvar readable-date-time-format "%A, %B %d, %Y at %I:%M:%S %p %Z "
"Format string used by `cj/insert-readable-date-time'.
See `format-time-string' for possible replacements.")
-(defun cj/insert-readable-date-time ()
- "Insert the current date and time into the current buffer.
-Use `readable-date-time-format' for formatting."
- (interactive)
- (insert (format-time-string readable-date-time-format (current-time))))
+(cj/--define-datetime-inserter cj/insert-readable-date-time
+ readable-date-time-format "date and time")
;; ----------------------------- Sortable Date Time ----------------------------
@@ -60,11 +70,8 @@ Use `readable-date-time-format' for formatting."
"Format string used by `cj/insert-sortable-date-time'.
See `format-time-string' for possible replacements.")
-(defun cj/insert-sortable-date-time ()
- "Insert the current date and time into the current buffer.
-Use `sortable-date-time-format' for formatting."
- (interactive)
- (insert (format-time-string sortable-date-time-format (current-time))))
+(cj/--define-datetime-inserter cj/insert-sortable-date-time
+ sortable-date-time-format "date and time")
;; ------------------------------- Sortable Time -------------------------------
@@ -72,11 +79,8 @@ Use `sortable-date-time-format' for formatting."
"Format string used by `cj/insert-sortable-time'.
See `format-time-string' for possible replacements.")
-(defun cj/insert-sortable-time ()
- "Insert the current time into the current buffer.
-Use `sortable-time-format' for formatting."
- (interactive)
- (insert (format-time-string sortable-time-format (current-time))))
+(cj/--define-datetime-inserter cj/insert-sortable-time
+ sortable-time-format "time")
;; ------------------------------- Readable Time -------------------------------
@@ -84,11 +88,8 @@ Use `sortable-time-format' for formatting."
"Format string used by `cj/insert-readable-time'.
See `format-time-string' for possible replacements.")
-(defun cj/insert-readable-time ()
- "Insert the current time into the current buffer.
-Use `readable-time-format' for formatting."
- (interactive)
- (insert (format-time-string readable-time-format (current-time))))
+(cj/--define-datetime-inserter cj/insert-readable-time
+ readable-time-format "time")
;; ------------------------------- Sortable Date -------------------------------
@@ -96,11 +97,8 @@ Use `readable-time-format' for formatting."
"Format string used by `cj/insert-sortable-date'.
See `format-time-string' for possible replacements.")
-(defun cj/insert-sortable-date ()
- "Insert the current date into the current buffer.
-Use `sortable-date-format' for formatting."
- (interactive)
- (insert (format-time-string sortable-date-format (current-time))))
+(cj/--define-datetime-inserter cj/insert-sortable-date
+ sortable-date-format "date")
;; ------------------------------- Readable Date -------------------------------
@@ -108,11 +106,8 @@ Use `sortable-date-format' for formatting."
"Format string used by `cj/insert-readable-date'.
See `format-time-string' for possible replacements.")
-(defun cj/insert-readable-date ()
- "Insert the current date into the current buffer.
-Use `readable-date-format' for formatting."
- (interactive)
- (insert (format-time-string readable-date-format (current-time))))
+(cj/--define-datetime-inserter cj/insert-readable-date
+ readable-date-format "date")
;; ------------------------------ Date Time Keymap -----------------------------
diff --git a/modules/custom-ordering.el b/modules/custom-ordering.el
index 578bede4b..0a499a35a 100644
--- a/modules/custom-ordering.el
+++ b/modules/custom-ordering.el
@@ -40,6 +40,23 @@
(defvar cj/ordering-map)
+(defun cj/--ordering-validate-region (start end)
+ "Signal an error when START is greater than END.
+Shared guard for the pure ordering helpers below, which all operate on a
+buffer region and must reject an inverted one before reading it."
+ (when (> start end)
+ (error "Invalid region: start (%d) is greater than end (%d)" start end)))
+
+(defun cj/--ordering-replace-region (start end insertion)
+ "Replace the buffer text between START and END with INSERTION.
+Point is left after the inserted text. Shared tail for the interactive
+ordering commands, which all compute a transformed string from the
+original region then swap it in. INSERTION is evaluated by the caller
+before this runs, so the transform reads the pre-deletion text."
+ (delete-region start end)
+ (goto-char start)
+ (insert insertion))
+
(defun cj/--arrayify (start end quote &optional prefix suffix)
"Internal implementation: Convert lines to quoted, comma-separated format.
START and END define the region to operate on.
@@ -50,8 +67,7 @@ SUFFIX is an optional string to append to the result (e.g., \"]\" or \")\").
Preserves a trailing newline if the input region ends with one, so
line-oriented operations on the result behave the same as before.
Returns the transformed string without modifying the buffer."
- (when (> start end)
- (error "Invalid region: start (%d) is greater than end (%d)" start end))
+ (cj/--ordering-validate-region start end)
(let* ((raw (buffer-substring start end))
(trailing-newline (string-suffix-p "\n" raw))
(result (mapconcat
@@ -65,36 +81,29 @@ Returns the transformed string without modifying the buffer."
START and END identify the active region.
QUOTE specifies the quotation characters to surround each element."
(interactive "r\nMQuotation character to use for array element: ")
- (let ((insertion (cj/--arrayify start end quote)))
- (delete-region start end)
- (insert insertion)))
+ (cj/--ordering-replace-region start end (cj/--arrayify start end quote)))
(defun cj/listify (start end)
"Convert lines between START and END into an unquoted, comma-separated list.
START and END identify the active region.
Example: `apple banana cherry' becomes `apple, banana, cherry'."
(interactive "r")
- (let ((insertion (cj/--arrayify start end "")))
- (delete-region start end)
- (insert insertion)))
+ (cj/--ordering-replace-region start end (cj/--arrayify start end "")))
(defun cj/arrayify-json (start end)
"Convert lines between START and END into a JSON-style array.
START and END identify the active region.
Example: `apple banana cherry' becomes `[\"apple\", \"banana\", \"cherry\"]'."
(interactive "r")
- (let ((insertion (cj/--arrayify start end "\"" "[" "]")))
- (delete-region start end)
- (insert insertion)))
+ (cj/--ordering-replace-region start end (cj/--arrayify start end "\"" "[" "]")))
-(defun cj/arrayify-python (start end)
- "Convert lines between START and END into a Python-style list.
-START and END identify the active region.
-Example: `apple banana cherry' becomes `[\"apple\", \"banana\", \"cherry\"]'."
- (interactive "r")
- (let ((insertion (cj/--arrayify start end "\"" "[" "]")))
- (delete-region start end)
- (insert insertion)))
+;; JSON arrays and Python lists coincide here (double-quoted, square-bracketed),
+;; so the Python command is an alias. Split it back into its own defun if the
+;; two formats ever need to differ (e.g. Python single quotes).
+(defalias 'cj/arrayify-python 'cj/arrayify-json
+ "Convert lines in the active region into a Python-style list.
+Example: `apple banana cherry' becomes `[\"apple\", \"banana\", \"cherry\"]'.
+Currently identical to `cj/arrayify-json'.")
(defun cj/--unarrayify (start end)
"Internal implementation: Convert comma-separated array to lines.
@@ -102,8 +111,7 @@ START and END define the region to operate on.
Removes quotes (both single and double) and splits by ', '.
Preserves a trailing newline if the input region ends with one.
Returns the transformed string without modifying the buffer."
- (when (> start end)
- (error "Invalid region: start (%d) is greater than end (%d)" start end))
+ (cj/--ordering-validate-region start end)
(let* ((raw (buffer-substring start end))
(trailing-newline (string-suffix-p "\n" raw))
(result (mapconcat
@@ -115,17 +123,14 @@ Returns the transformed string without modifying the buffer."
"Convert quoted comma-separated strings between START and END to separate lines.
START and END identify the active region."
(interactive "r")
- (let ((insertion (cj/--unarrayify start end)))
- (delete-region start end)
- (insert insertion)))
+ (cj/--ordering-replace-region start end (cj/--unarrayify start end)))
(defun cj/--toggle-quotes (start end)
"Internal implementation: Toggle between double and single quotes.
START and END define the region to operate on.
Swaps all double quotes with single quotes and vice versa.
Returns the transformed string without modifying the buffer."
- (when (> start end)
- (error "Invalid region: start (%d) is greater than end (%d)" start end))
+ (cj/--ordering-validate-region start end)
(let ((text (buffer-substring start end)))
(with-temp-buffer
(insert text)
@@ -145,16 +150,13 @@ Returns the transformed string without modifying the buffer."
"Toggle between double and single quotes in region between START and END.
START and END identify the active region."
(interactive "r")
- (let ((insertion (cj/--toggle-quotes start end)))
- (delete-region start end)
- (insert insertion)))
+ (cj/--ordering-replace-region start end (cj/--toggle-quotes start end)))
(defun cj/--reverse-lines (start end)
"Internal implementation: Reverse the order of lines in region.
START and END define the region to operate on.
Returns the transformed string without modifying the buffer."
- (when (> start end)
- (error "Invalid region: start (%d) is greater than end (%d)" start end))
+ (cj/--ordering-validate-region start end)
(let ((lines (split-string (buffer-substring start end) "\n")))
(mapconcat #'identity (nreverse lines) "\n")))
@@ -162,9 +164,7 @@ Returns the transformed string without modifying the buffer."
"Reverse the order of lines in region between START and END.
START and END identify the active region."
(interactive "r")
- (let ((insertion (cj/--reverse-lines start end)))
- (delete-region start end)
- (insert insertion)))
+ (cj/--ordering-replace-region start end (cj/--reverse-lines start end)))
(defun cj/--number-lines (start end format-string zero-pad)
"Internal implementation: Number lines in region with custom format.
@@ -175,8 +175,7 @@ FORMAT-STRING is the format for each line, with N as placeholder for number.
ZERO-PAD when non-nil pads numbers with zeros for alignment.
Example with 100 lines: \"001\", \"002\", ..., \"100\".
Returns the transformed string without modifying the buffer."
- (when (> start end)
- (error "Invalid region: start (%d) is greater than end (%d)" start end))
+ (cj/--ordering-validate-region start end)
(let* ((lines (split-string (buffer-substring start end) "\n"))
(line-count (length lines))
(width (if zero-pad (length (number-to-string line-count)) 1))
@@ -199,17 +198,15 @@ FORMAT-STRING is the format for each line, with N as placeholder for number.
Example: \"N. \" produces \"1. \", \"2. \", etc.
ZERO-PAD when non-nil (prefix argument) pads numbers with zeros."
(interactive "r\nMFormat string (use N for number): \nP")
- (let ((insertion (cj/--number-lines start end format-string zero-pad)))
- (delete-region start end)
- (insert insertion)))
+ (cj/--ordering-replace-region
+ start end (cj/--number-lines start end format-string zero-pad)))
(defun cj/--alphabetize-region (start end)
"Internal implementation: Alphabetize words in region.
START and END define the region to operate on.
Splits by whitespace and commas, sorts alphabetically, joins with ', '.
Returns the transformed string without modifying the buffer."
- (when (> start end)
- (error "Invalid region: start (%d) is greater than end (%d)" start end))
+ (cj/--ordering-validate-region start end)
(let ((string (buffer-substring-no-properties start end)))
(mapconcat #'identity
(sort (split-string string "[[:space:],]+" t)
@@ -221,21 +218,17 @@ Returns the transformed string without modifying the buffer."
Produce a comma-separated list as the result."
(interactive)
(unless (use-region-p)
- (user-error "No region selected"))
+ (user-error "No region selected"))
(let ((start (region-beginning))
- (end (region-end))
- (insertion (cj/--alphabetize-region (region-beginning) (region-end))))
- (delete-region start end)
- (goto-char start)
- (insert insertion)))
+ (end (region-end)))
+ (cj/--ordering-replace-region start end (cj/--alphabetize-region start end))))
(defun cj/--comma-separated-text-to-lines (start end)
"Internal implementation: Convert comma-separated text to lines.
START and END define the region to operate on.
Replaces commas with newlines and removes trailing whitespace from each line.
Returns the transformed string without modifying the buffer."
- (when (> start end)
- (error "Invalid region: start (%d) is greater than end (%d)" start end))
+ (cj/--ordering-validate-region start end)
(let ((text (buffer-substring-no-properties start end)))
(with-temp-buffer
(insert text)
@@ -249,14 +242,11 @@ Returns the transformed string without modifying the buffer."
"Break up comma-separated text in active region so each item is on own line."
(interactive)
(if (not (region-active-p))
- (error "No region selected"))
-
+ (error "No region selected"))
(let ((beg (region-beginning))
- (end (region-end))
- (text (cj/--comma-separated-text-to-lines (region-beginning) (region-end))))
- (delete-region beg end)
- (goto-char beg)
- (insert text)))
+ (end (region-end)))
+ (cj/--ordering-replace-region
+ beg end (cj/--comma-separated-text-to-lines beg end))))
diff --git a/modules/custom-text-enclose.el b/modules/custom-text-enclose.el
index fdfb92230..5b1b00a71 100644
--- a/modules/custom-text-enclose.el
+++ b/modules/custom-text-enclose.el
@@ -54,48 +54,42 @@ CLOSING is appended to TEXT.
Returns the wrapped text without modifying the buffer."
(concat opening text closing))
+(defun cj/--enclose-region-or-word (transform &optional no-target-message)
+ "Apply TRANSFORM to the active region or the word at point, in place.
+TRANSFORM is a function of one string (the target text) returning the
+replacement text. An active region is the target; otherwise the word at
+point is. With neither, show NO-TARGET-MESSAGE (or a default) and leave the
+buffer unchanged. Point is left after the inserted text."
+ (let ((bounds (cond ((use-region-p) (cons (region-beginning) (region-end)))
+ ((thing-at-point 'word) (bounds-of-thing-at-point 'word)))))
+ (if (null bounds)
+ (message "%s" (or no-target-message
+ "Can't do that. No word at point and no region selected."))
+ (let* ((beg (car bounds))
+ (end (cdr bounds))
+ (text (buffer-substring beg end)))
+ (delete-region beg end)
+ (goto-char beg)
+ (insert (funcall transform text))))))
+
(defun cj/surround-word-or-region ()
"Surround the word at point or active region with a string.
The surround string is read from the minibuffer."
(interactive)
- (let ((str (read-string "Surround with: "))
- (regionp (use-region-p)))
- (if regionp
- (let ((beg (region-beginning))
- (end (region-end))
- (text (buffer-substring (region-beginning) (region-end))))
- (delete-region beg end)
- (goto-char beg)
- (insert (cj/--surround text str)))
- (if (thing-at-point 'word)
- (let* ((bounds (bounds-of-thing-at-point 'word))
- (text (buffer-substring (car bounds) (cdr bounds))))
- (delete-region (car bounds) (cdr bounds))
- (goto-char (car bounds))
- (insert (cj/--surround text str)))
- (message "Can't insert around. No word at point and no region selected.")))))
+ (let ((str (read-string "Surround with: ")))
+ (cj/--enclose-region-or-word
+ (lambda (text) (cj/--surround text str))
+ "Can't insert around. No word at point and no region selected.")))
(defun cj/wrap-word-or-region ()
"Wrap the word at point or active region with different opening/closing strings.
The opening and closing strings are read from the minibuffer."
(interactive)
(let ((opening (read-string "Opening: "))
- (closing (read-string "Closing: "))
- (regionp (use-region-p)))
- (if regionp
- (let ((beg (region-beginning))
- (end (region-end))
- (text (buffer-substring (region-beginning) (region-end))))
- (delete-region beg end)
- (goto-char beg)
- (insert (cj/--wrap text opening closing)))
- (if (thing-at-point 'word)
- (let* ((bounds (bounds-of-thing-at-point 'word))
- (text (buffer-substring (car bounds) (cdr bounds))))
- (delete-region (car bounds) (cdr bounds))
- (goto-char (car bounds))
- (insert (cj/--wrap text opening closing)))
- (message "Can't wrap. No word at point and no region selected.")))))
+ (closing (read-string "Closing: ")))
+ (cj/--enclose-region-or-word
+ (lambda (text) (cj/--wrap text opening closing))
+ "Can't wrap. No word at point and no region selected.")))
(defun cj/--unwrap (text opening closing)
"Internal implementation: Remove OPENING and CLOSING from TEXT if present.
@@ -114,22 +108,10 @@ Returns the unwrapped text if both delimiters present, otherwise unchanged."
The opening and closing strings are read from the minibuffer."
(interactive)
(let ((opening (read-string "Opening to remove: "))
- (closing (read-string "Closing to remove: "))
- (regionp (use-region-p)))
- (if regionp
- (let ((beg (region-beginning))
- (end (region-end))
- (text (buffer-substring (region-beginning) (region-end))))
- (delete-region beg end)
- (goto-char beg)
- (insert (cj/--unwrap text opening closing)))
- (if (thing-at-point 'word)
- (let* ((bounds (bounds-of-thing-at-point 'word))
- (text (buffer-substring (car bounds) (cdr bounds))))
- (delete-region (car bounds) (cdr bounds))
- (goto-char (car bounds))
- (insert (cj/--unwrap text opening closing)))
- (message "Can't unwrap. No word at point and no region selected.")))))
+ (closing (read-string "Closing to remove: ")))
+ (cj/--enclose-region-or-word
+ (lambda (text) (cj/--unwrap text opening closing))
+ "Can't unwrap. No word at point and no region selected.")))
(defun cj/--append-to-lines (text suffix)
"Internal implementation: Append SUFFIX to each line in TEXT.
diff --git a/modules/dashboard-config.el b/modules/dashboard-config.el
index b92162932..96aaaf6a1 100644
--- a/modules/dashboard-config.el
+++ b/modules/dashboard-config.el
@@ -17,11 +17,63 @@
;;; Code:
+(require 'system-lib) ;; cj/exclude-from-global-font-lock
(eval-when-compile (require 'undead-buffers))
(declare-function cj/make-buffer-undead "undead-buffers" (string))
(autoload 'cj/make-buffer-undead "undead-buffers" nil t)
(declare-function ghostel "ghostel" (&optional arg))
+;; ------------------------------ Declarations -------------------------------
+;; These functions and variables belong to lazily-loaded packages or to other
+;; cj modules; declaring them keeps the byte-compiler quiet without forcing an
+;; eager require. Behavior is unchanged -- the symbols still resolve at runtime
+;; once their owning package/module loads.
+
+;; dashboard package internals used by the bookmark-insertion override.
+(declare-function dashboard-insert-section "dashboard")
+(declare-function dashboard-subseq "dashboard")
+(declare-function dashboard-get-shortcut "dashboard")
+(declare-function dashboard-shorten-path "dashboard")
+(declare-function dashboard--align-length-by-type "dashboard")
+(declare-function dashboard--generate-align-format "dashboard")
+(declare-function dashboard-refresh-buffer "dashboard")
+(declare-function dashboard-open "dashboard")
+(defvar dashboard-bookmarks-show-path)
+(defvar dashboard--bookmarks-cache-item-format)
+
+;; bookmark.el (required at runtime inside `dashboard-insert-bookmarks').
+(declare-function bookmark-all-names "bookmark")
+(declare-function bookmark-get-filename "bookmark")
+
+;; recentf.el (required at runtime inside the exclude helper).
+(defvar recentf-exclude)
+
+;; nerd-icons glyph functions used in the launcher table.
+(declare-function nerd-icons-faicon "nerd-icons")
+(declare-function nerd-icons-devicon "nerd-icons")
+(declare-function nerd-icons-mdicon "nerd-icons")
+(declare-function nerd-icons-codicon "nerd-icons")
+(declare-function nerd-icons-octicon "nerd-icons")
+
+;; user-constants.el provides the home-directory constant.
+(defvar user-home-dir)
+
+;; Launcher actions defined in other cj modules.
+(declare-function cj/main-agenda-display "org-agenda-config")
+(declare-function cj/elfeed-open "elfeed-config")
+(declare-function cj/drill-start "org-drill-config")
+(declare-function cj/music-playlist-toggle "music-config")
+(declare-function cj/music-playlist-load "music-config")
+(declare-function cj/erc-switch-to-buffer-with-completion "erc-config")
+(declare-function cj/telega "telega-config")
+(declare-function cj/slack-start "slack-config")
+(declare-function cj/signel-message "signal-config")
+(declare-function cj/kill-all-other-buffers-and-windows "undead-buffers")
+
+;; External package commands invoked by launchers.
+(declare-function mu4e "mu4e")
+(declare-function pearl-list-issues "pearl")
+
;; ------------------------ Dashboard Bookmarks Override -----------------------
;; overrides the bookmark insertion from the dashboard package to provide an
;; option that only shows the bookmark name, avoiding the path. Paths are often
@@ -34,8 +86,11 @@
;; `el' is bound dynamically by dashboard's section-insertion machinery, which the
;; override below plugs into. Declare it so the byte-compiler reads the
-;; references as that special variable rather than a free variable.
-(defvar el)
+;; references as that special variable rather than a free variable. The name is
+;; dashboard's, not ours, so the missing-prefix lint is suppressed rather than
+;; renamed (renaming would break the dynamic binding dashboard supplies).
+(with-suppressed-warnings ((lexical el))
+ (defvar el))
(defun dashboard-insert-bookmarks (list-size)
"Add the list of LIST-SIZE items of bookmarks."
@@ -85,7 +140,7 @@ Adjust this if the title doesn't appear centered under the banner image.")
(list "t" #'nerd-icons-devicon "nf-dev-terminal" "Terminal" "Launch Terminal" (lambda () (ghostel)))
(list "a" #'nerd-icons-mdicon "nf-md-calendar" "Agenda" "Main Org Agenda" (lambda () (cj/main-agenda-display)))
(list "r" #'nerd-icons-faicon "nf-fa-rss_square" "Feeds" "Elfeed Feed Reader" (lambda () (cj/elfeed-open)))
- (list "b" #'nerd-icons-faicon "nf-fae-book_open_o" "Books" "Calibre Ebook Reader" (lambda () (calibredb)))
+ (list "b" #'nerd-icons-codicon "nf-cod-library" "Books" "Calibre Ebook Reader" (lambda () (calibredb)))
(list "f" #'nerd-icons-mdicon "nf-md-school" "Flashcards" "Org-Drill" (lambda () (cj/drill-start)))
(list "m" #'nerd-icons-mdicon "nf-md-music" "Music" "EMMS Music Player" (lambda () (cj/music-playlist-toggle) (cj/music-playlist-load)))
(list "e" #'nerd-icons-faicon "nf-fa-envelope" "Email" "Mu4e Email Client" (lambda () (mu4e)))
@@ -168,7 +223,7 @@ system-defaults) are preserved rather than overwritten."
;; running the banner and headings fall back to the default face. Excluding
;; dashboard-mode lets those text-property faces survive. (Item and navigator
;; colors ride a `dashboard-items-face' overlay, which font-lock leaves alone.)
-(setq font-lock-global-modes '(not dashboard-mode))
+(cj/exclude-from-global-font-lock 'dashboard-mode)
(use-package dashboard
:demand t
@@ -218,6 +273,7 @@ system-defaults) are preserved rather than overwritten."
(setq dashboard-display-icons-p t) ;; display icons on both GUI and terminal
(setq dashboard-icon-type 'nerd-icons) ;; use `nerd-icons' package
(setq dashboard-set-file-icons t) ;; per-filetype icons on the list items (nerd-icons colors them by type)
+ (setq dashboard-set-heading-icons t) ;; nerd-icons on the section titles (Projects/Bookmarks/Recent)
(setq dashboard-center-content t) ;; horizontally center dashboard content
(setq dashboard-bookmarks-show-path nil) ;; don't show paths in bookmarks
(setq dashboard-recentf-show-base t) ;; show filename, not full path
diff --git a/modules/diff-config.el b/modules/diff-config.el
index 75869a73f..0c09b9516 100644
--- a/modules/diff-config.el
+++ b/modules/diff-config.el
@@ -28,6 +28,12 @@
;;; Code:
+(declare-function ediff-setup-keymap "ediff")
+(declare-function ediff-next-difference "ediff")
+(declare-function ediff-previous-difference "ediff")
+(declare-function cj/ediff-hook "diff-config")
+(declare-function winner-undo "winner")
+
(use-package ediff
:ensure nil ;; built-in
:defer t
diff --git a/modules/dirvish-config.el b/modules/dirvish-config.el
index 8b672764b..81d352dbd 100644
--- a/modules/dirvish-config.el
+++ b/modules/dirvish-config.el
@@ -41,6 +41,24 @@
(declare-function cj/drill-this-file "org-drill-config")
+;; Dirvish/Dired functions called from lazy-loaded packages.
+(declare-function dirvish-peek-mode "dirvish")
+(declare-function dirvish-side-follow-mode "dirvish")
+(declare-function dirvish-quit "dirvish")
+(declare-function dired-get-marked-files "dired")
+(declare-function dired-dwim-target-directory "dired-aux")
+(declare-function dired-get-file-for-visit "dired")
+(declare-function dired-get-filename "dired")
+(declare-function dired-mark "dired")
+(declare-function dired-current-directory "dired")
+(declare-function dired-file-name-at-point "dired-x")
+(declare-function dired-find-file "dired")
+(declare-function project-roots "project")
+
+;; External package variables referenced before their package loads.
+(defvar ediff-after-quit-hook-internal)
+(defvar dirvish-side-attributes)
+
;; mark files in dirvish, attach in mu4e
(add-hook 'dired-mode-hook 'turn-on-gnus-dired-mode)
@@ -119,6 +137,35 @@ through a `../' or absolute path. Pure helper."
(and (not (string-empty-p name))
(not (string-match-p "/" name))))
+(defun cj/--playlist-resolve-target ()
+ "Prompt for a playlist name and return the .m3u path to write under `music-dir'.
+Re-prompt until the name is a safe bare filename (no `/'). When the target
+already exists, ask whether to overwrite, cancel, or rename: overwrite returns
+the path, cancel signals a `user-error', rename re-prompts. Interactive
+prompting only -- the caller does the file write."
+ (let ((base-name nil)
+ (playlist-path nil)
+ (done nil))
+ (while (not done)
+ (setq base-name (cj/--playlist-sanitize-name
+ (read-string "Playlist name (without .m3u): ")))
+ (cond
+ ((not (cj/--playlist-name-safe-p base-name))
+ (message "Playlist name must be a bare filename, without '/'."))
+ (t
+ (setq playlist-path (expand-file-name (concat base-name ".m3u") music-dir))
+ (if (not (file-exists-p playlist-path))
+ (setq done t)
+ (let ((choice (read-char-choice
+ (format "Playlist '%s' exists. [o]verwrite, [c]ancel, [r]ename? "
+ (file-name-nondirectory playlist-path))
+ '(?o ?c ?r))))
+ (cl-case choice
+ (?o (setq done t))
+ (?c (user-error "Cancelled playlist creation"))
+ (?r (setq done nil))))))))
+ playlist-path))
+
(defun cj/dired-create-playlist-from-marked ()
"Create an .m3u playlist file from marked files in Dired (or Dirvish).
Filters for audio files, prompts for the playlist name, and saves the resulting
@@ -131,27 +178,7 @@ Filters for audio files, prompts for the playlist name, and saves the resulting
(if (zerop count)
(user-error "No audio files marked (extensions: %s)"
(string-join cj/audio-file-extensions ", "))
- (let ((base-name nil)
- (playlist-path nil)
- (done nil))
- (while (not done)
- (setq base-name (cj/--playlist-sanitize-name
- (read-string "Playlist name (without .m3u): ")))
- (cond
- ((not (cj/--playlist-name-safe-p base-name))
- (message "Playlist name must be a bare filename, without '/'."))
- (t
- (setq playlist-path (expand-file-name (concat base-name ".m3u") music-dir))
- (if (not (file-exists-p playlist-path))
- (setq done t)
- (let ((choice (read-char-choice
- (format "Playlist '%s' exists. [o]verwrite, [c]ancel, [r]ename? "
- (file-name-nondirectory playlist-path))
- '(?o ?c ?r))))
- (cl-case choice
- (?o (setq done t))
- (?c (user-error "Cancelled playlist creation"))
- (?r (setq done nil))))))))
+ (let ((playlist-path (cj/--playlist-resolve-target)))
(with-temp-file playlist-path
(dolist (af audio-files)
(insert af "\n")))
@@ -259,6 +286,37 @@ Examples:
(message "Duplicated: %s → %s"
(file-name-nondirectory file) new-name))))
+;;; ----------------------------- Dirvish Hard Delete ---------------------------
+
+(defun cj/--dirvish-hard-delete-command (files)
+ "Return the `sudo rm -rf' shell command that force-deletes FILES.
+Each path is shell-quoted and the list is preceded by `--' so a
+leading-dash filename can't be misread as an option. Pure helper used by
+`cj/dirvish-hard-delete'."
+ (concat "sudo rm -rf -- "
+ (mapconcat #'shell-quote-argument files " ")))
+
+(defun cj/dirvish-hard-delete ()
+ "Force-delete the marked files (or the file at point) via `sudo rm -rf'.
+This bypasses the trash and is IRREVERSIBLE. Prompts with the exact
+targets named before running."
+ (interactive)
+ (let ((files (dired-get-marked-files)))
+ (unless files
+ (user-error "No file at point"))
+ (let ((targets (mapconcat #'file-name-nondirectory files ", ")))
+ (when (yes-or-no-p
+ (format "Force-delete (sudo rm -rf, NO undo): %s? " targets))
+ (let ((status (shell-command (cj/--dirvish-hard-delete-command files))))
+ ;; Revert either way so the listing reflects whatever was removed,
+ ;; but only claim success when `rm' actually exited 0 -- a failed or
+ ;; cancelled `sudo' must not report files gone that are still there.
+ (revert-buffer)
+ (if (zerop status)
+ (message "Force-deleted: %s" targets)
+ (message "Hard delete failed (exit %d) -- see *Shell Command Output*"
+ status)))))))
+
;;; ------------------------------ Dirvish Print File ---------------------------
(defvar cj/dirvish-print-extensions
@@ -309,7 +367,8 @@ Shadows dired's `P' (`dired-do-print') with this type-aware version."
(defun cj/dirvish-drill-file ()
"Open the Org file at point and start an `org-drill' session on it.
-Bound to `S' (\"study\") in `dirvish-mode-map'; refuses anything but a `.org' file."
+Bound to `S' (\"study\") in `dirvish-mode-map'; refuses anything but
+a `.org' file."
(interactive)
(let ((file (dired-get-filename nil t)))
(unless (and file (not (file-directory-p file)) (string-suffix-p ".org" file t))
@@ -341,18 +400,19 @@ regardless of what file or subdirectory the point is on."
"Return the (PROGRAM PRE-FILE-ARG...) list for setting wallpaper under ENV.
ENV is a display-server symbol: `x11' picks feh with --bg-fill, `wayland'
-picks swww with the img subcommand. Any other value returns nil so the
-caller can surface an \"unknown display server\" error.
+picks the `set-wallpaper' script (on PATH from dotfiles; it wraps the awww
+backend and persists the choice to waypaper's config). Any other value
+returns nil so the caller can surface an \"unknown display server\" error.
Pure helper used by `cj/set-wallpaper'."
(pcase env
('x11 '("feh" "--bg-fill"))
- ('wayland '("swww" "img"))
+ ('wayland '("set-wallpaper"))
(_ nil)))
(defun cj/set-wallpaper ()
"Set the image at point as the desktop wallpaper.
-Uses feh on X11, swww on Wayland."
+Uses feh on X11, the `set-wallpaper' script on Wayland."
(interactive)
(let* ((raw (dired-file-name-at-point))
(file (and raw (expand-file-name raw)))
@@ -371,6 +431,117 @@ Uses feh on X11, swww on Wayland."
(message "Wallpaper set: %s (%s)"
(file-name-nondirectory file) (car cmd))))))
+;;; ------------------------- Dirvish Hyprland Popup ----------------------------
+
+;; The Hyprland Super+F popup opens an emacsclient frame named "dirvish" (window
+;; rules float/size/center it by that name) and runs `cj/dirvish-popup', rooted
+;; at home. `q' in that frame runs `cj/dirvish-popup-quit', which quits Dirvish
+;; and deletes the popup frame so a stray launch never orphans it; `q' in any
+;; other frame quits Dirvish normally. The launcher script calls this command
+;; instead of plain `dirvish'. This mirrors the Super+Shift+N quick-capture
+;; popup (see `cj/quick-capture' in org-capture-config.el).
+
+(defun cj/--dirvish-popup-frame ()
+ "Return a live frame named \"dirvish\" (the Hyprland popup), or nil."
+ (seq-find (lambda (f)
+ (and (frame-live-p f)
+ (equal (frame-parameter f 'name) "dirvish")))
+ (frame-list)))
+
+(defun cj/dirvish-popup ()
+ "Open Dirvish in the Hyprland popup frame (frame \"dirvish\"), rooted at home.
+The launcher script calls this through =emacsclient -c -e=. `q'
+(`cj/dirvish-popup-quit') closes the frame.
+
+Selects the \"dirvish\" frame by name before opening rather than trusting the
+ambient selected frame: the launching =emacsclient -c -e= runs before Hyprland
+settles focus on the new float, so =(selected-frame)= is still the daemon's main
+frame and Dirvish would otherwise open there."
+ (interactive)
+ (let ((frame (cj/--dirvish-popup-frame)))
+ (when frame (select-frame-set-input-focus frame))
+ (dirvish (expand-file-name "~/"))))
+
+(defun cj/dirvish-popup-focus-existing ()
+ "Raise and focus the live dirvish popup frame, returning t; nil if none.
+The launcher script calls this before creating a frame, so a second Super+F
+re-uses the open popup instead of spawning a second one (the popup is a
+single-instance, transient launcher -- use =C-x d= for several independent
+Dirvish sessions)."
+ (let ((popup (cj/--dirvish-popup-frame)))
+ (when popup
+ (select-frame-set-input-focus popup)
+ t)))
+
+(defun cj/dirvish-popup-quit ()
+ "Quit Dirvish. In the Hyprland popup frame (\"dirvish\"), delete the frame too.
+Bound to `q' in `dirvish-mode-map'. A normal Dirvish session (any other frame)
+quits as usual; only the popup frame is torn down, so the Super+F launch never
+leaves an empty frame behind."
+ (interactive)
+ (let ((popup (cj/--dirvish-popup-frame)))
+ (if (and popup (eq popup (selected-frame)))
+ (progn
+ (ignore-errors (dirvish-quit))
+ (when (frame-live-p popup) (delete-frame popup)))
+ (dirvish-quit))))
+
+(defun cj/--dirvish-popup-reap-on-delete (frame)
+ "Quit the Dirvish session when the Super+F popup FRAME is closed any way.
+`q' runs `cj/dirvish-popup-quit', but closing the Hyprland float directly (or
+letting it lose focus) bypasses that and orphans the session's dired buffers --
+the \"leaves a load of buffers around\" symptom. As a `delete-frame-functions'
+hook this fires on every close path; `dirvish-quit' reaps the session's buffers
+(verified: a navigated session drops back to baseline on quit). Scoped to the
+popup frame so ordinary `C-x d' sessions -- where multiple dired buffers are
+wanted for mark-and-move -- are untouched."
+ (when (and (frame-live-p frame)
+ (equal (frame-parameter frame 'name) "dirvish"))
+ (with-selected-frame frame
+ (ignore-errors (dirvish-quit)))))
+
+(add-hook 'delete-frame-functions #'cj/--dirvish-popup-reap-on-delete)
+
+(defun cj/--dirvish-popup-selected-p ()
+ "Return non-nil when the selected frame is the dirvish popup frame."
+ (let ((popup (cj/--dirvish-popup-frame)))
+ (and popup (eq popup (selected-frame)))))
+
+(defun cj/dirvish-popup-find-file ()
+ "Open the file at point.
+In the Hyprland popup frame the popup is a context-free launcher: files open
+through the OS handler (`cj/xdg-open' -> xdg-open), so nothing lands inside the
+throwaway frame and the launch is independent of the running Emacs session (a
+text/code file opens its own new emacsclient frame, not your working session --
+use =C-x d= when you want a file in the session you're in). Directories are
+entered normally so you can keep browsing. The popup then dismisses itself on
+focus loss. Outside the popup this is exactly `dired-find-file'."
+ (interactive)
+ (if (cj/--dirvish-popup-selected-p)
+ (let ((file (dired-get-file-for-visit)))
+ (if (file-directory-p file)
+ (dired-find-file)
+ (cj/xdg-open file)))
+ (dired-find-file)))
+
+(defun cj/--dirvish-popup-focus-watch (&rest _)
+ "Dismiss the dirvish popup frame once it loses focus.
+Armed only after the popup has actually held focus (a per-frame flag), so the
+frame is never torn down during its own creation, before Hyprland settles focus
+on the new float. Installed on `after-focus-change-function'; a no-op whenever
+no popup frame is live."
+ (let ((popup (cj/--dirvish-popup-frame)))
+ (when popup
+ (if (frame-focus-state popup)
+ (set-frame-parameter popup 'cj-dirvish-popup-had-focus t)
+ (when (frame-parameter popup 'cj-dirvish-popup-had-focus)
+ (delete-frame popup))))))
+
+;; Install idempotently: remove any prior copy before adding, so re-loading the
+;; module updates the watch rather than stacking duplicate copies.
+(remove-function after-focus-change-function #'cj/--dirvish-popup-focus-watch)
+(add-function :after after-focus-change-function #'cj/--dirvish-popup-focus-watch)
+
;;; ---------------------------------- Dirvish ----------------------------------
(use-package dirvish
@@ -475,7 +646,8 @@ Uses feh on X11, swww on Wayland."
("bg" . cj/set-wallpaper)
("/" . dirvish-narrow)
("<left>" . dired-up-directory)
- ("<right>" . dired-find-file)
+ ("RET" . cj/dirvish-popup-find-file) ; popup: launch file externally; else normal
+ ("<right>" . cj/dirvish-popup-find-file)
("C-," . dirvish-history-go-backward)
("C-." . dirvish-history-go-forward)
("F" . dirvish-file-info-menu)
@@ -489,14 +661,15 @@ Uses feh on X11, swww on Wayland."
("M-p" . dirvish-peek-toggle)
("M-s" . dirvish-setup-menu)
("TAB" . dirvish-subtree-toggle)
- ("d" . dired-do-delete)
- ("D" . cj/dirvish-duplicate-file)
+ ("d" . cj/dirvish-duplicate-file)
+ ("D" . cj/dirvish-hard-delete)
("f" . cj/dirvish-open-file-manager-here)
("g" . dirvish-quick-access)
("o" . cj/xdg-open)
("O" . cj/open-file-with-command) ; Prompts for command to run
("p" . (lambda () (interactive) (cj/dired-copy-path-as-kill nil t)))
("P" . cj/dirvish-print-file)
+ ("q" . cj/dirvish-popup-quit) ; quit; in the Hyprland popup frame, close it
("r" . dirvish-rsync)
("S" . cj/dirvish-drill-file) ; Study: org-drill the .org file at point
("s" . dirvish-quicksort)
diff --git a/modules/dwim-shell-config.el b/modules/dwim-shell-config.el
index ad17ea913..014194c7b 100644
--- a/modules/dwim-shell-config.el
+++ b/modules/dwim-shell-config.el
@@ -100,6 +100,16 @@
(require 'cl-lib)
(require 'system-lib) ;; cj/confirm-strong (permanent file destruction confirm)
+;; Function declarations (lazily-loaded packages and sibling modules).
+(declare-function dwim-shell-command-on-marked-files "dwim-shell-command")
+(declare-function dwim-shell-command-read-file-name "dwim-shell-command")
+(declare-function dwim-shell-command--files "dwim-shell-command")
+(declare-function cj/xdg-open "external-open")
+(declare-function dwim-shell-commands-menu "dwim-shell-config")
+
+;; Forward declaration: external variable provided by the dirvish package.
+(defvar dirvish-mode-map)
+
;; --------------------------- Password-file helpers ---------------------------
(defun cj/dwim-shell--password-cleanup-callback (temp-file)
@@ -210,6 +220,41 @@ The timestamp is interpolated here with `format-time-string' so it can't sit
dead inside the shell's single quotes the way a literal =$(date ...)= did."
(format "cp -p '<<f>>' '<<f>>.%s.bak'" (format-time-string "%Y%m%d_%H%M%S")))
+(defun cj/dwim-shell--tar-gzip-command (single-p)
+ "Return the tar-gzip command template.
+SINGLE-P non-nil names the archive after the lone file (=<fne>.tar.gz=);
+otherwise a shared =archive.tar.gz= over all marked files."
+ (if single-p
+ "tar czf '<<fne>>.tar.gz' '<<f>>'"
+ "tar czf '<<archive.tar.gz(u)>>' '<<*>>'"))
+
+(defun cj/dwim-shell--text-to-speech-command (system voice)
+ "Return the text-to-speech command template for SYSTEM using VOICE.
+SYSTEM is a `system-type' symbol: `darwin' synthesizes with `say' and VOICE;
+any other system uses `espeak' (VOICE unused)."
+ (if (eq system 'darwin)
+ (format "say -v %s -o '<<fne>>.aiff' -f '<<f>>'" voice)
+ "espeak -f '<<f>>' -w '<<fne>>.wav'"))
+
+(defun cj/dwim-shell--video-trim-command (trim-type start end)
+ "Return the ffmpeg video-trim command template for TRIM-TYPE.
+TRIM-TYPE is \"Beginning\", \"End\", or \"Both\". START trims that many
+seconds off the front, END off the back (each ignored for the side it does
+not apply to). Signals a `user-error' when a used second count is negative."
+ (pcase trim-type
+ ("Beginning"
+ (when (< start 0) (user-error "Seconds must be non-negative"))
+ (format "ffmpeg -i '<<f>>' -y -ss %d -c:v copy -c:a copy '<<fne>>_trimmed.<<e>>'"
+ start))
+ ("End"
+ (when (< end 0) (user-error "Seconds must be non-negative"))
+ (format "ffmpeg -sseof -%d -i '<<f>>' -y -c:v copy -c:a copy '<<fne>>_trimmed.<<e>>'"
+ end))
+ ("Both"
+ (when (or (< start 0) (< end 0)) (user-error "Seconds must be non-negative"))
+ (format "ffmpeg -i '<<f>>' -y -ss %d -sseof -%d -c:v copy -c:a copy '<<fne>>_trimmed.<<e>>'"
+ start end))))
+
;; ----------------------------- Dwim Shell Command ----------------------------
(use-package dwim-shell-command
@@ -357,9 +402,8 @@ Otherwise, unzip it to an appropriately named subdirectory "
"Tar gzip all marked files into archive.tar.gz."
(interactive)
(dwim-shell-command-on-marked-files
- "Tar gzip" (if (eq 1 (seq-length (dwim-shell-command--files)))
- "tar czf '<<fne>>.tar.gz' '<<f>>'"
- "tar czf '<<archive.tar.gz(u)>>' '<<*>>'")
+ "Tar gzip" (cj/dwim-shell--tar-gzip-command
+ (eq 1 (seq-length (dwim-shell-command--files))))
:utils "tar"))
(defun cj/dwim-shell-commands-epub-to-org ()
@@ -448,34 +492,18 @@ process list, and the file is removed only after the spawned process exits."
"Trim video with options for beginning, end, or both."
(interactive)
(let* ((trim-type (completing-read "Trim from: "
- '("Beginning" "End" "Both")
- nil t))
- (command (pcase trim-type
- ("Beginning"
- (let ((seconds (read-number "Seconds to trim from beginning: " 5)))
- (when (< seconds 0)
- (user-error "Seconds must be non-negative"))
- (format "ffmpeg -i '<<f>>' -y -ss %d -c:v copy -c:a copy '<<fne>>_trimmed.<<e>>'"
- seconds)))
- ("End"
- (let ((seconds (read-number "Seconds to trim from end: " 5)))
- (when (< seconds 0)
- (user-error "Seconds must be non-negative"))
- (format "ffmpeg -sseof -%d -i '<<f>>' -y -c:v copy -c:a copy '<<fne>>_trimmed.<<e>>'"
- seconds)))
- ("Both"
- (let ((start (read-number "Seconds to trim from beginning: " 5))
- (end (read-number "Seconds to trim from end: " 5)))
- (when (or (< start 0) (< end 0))
- (user-error "Seconds must be non-negative"))
- (format "ffmpeg -i '<<f>>' -y -ss %d -sseof -%d -c:v copy -c:a copy '<<fne>>_trimmed.<<e>>'"
- start end))))))
- (dwim-shell-command-on-marked-files
+ '("Beginning" "End" "Both")
+ nil t))
+ (start (if (member trim-type '("Beginning" "Both"))
+ (read-number "Seconds to trim from beginning: " 5) 0))
+ (end (if (member trim-type '("End" "Both"))
+ (read-number "Seconds to trim from end: " 5) 0))
+ (command (cj/dwim-shell--video-trim-command trim-type start end)))
+ (dwim-shell-command-on-marked-files
(format "Trim video (%s)" trim-type)
command
:silent-success t
:utils "ffmpeg")))
-
(defun cj/dwim-shell-commands-drop-audio-from-video ()
"Drop audio from all marked videos."
(interactive)
@@ -694,9 +722,7 @@ all marked files rather than once per file."
"en")))
(dwim-shell-command-on-marked-files
"Text to speech"
- (if (eq system-type 'darwin)
- (format "say -v %s -o '<<fne>>.aiff' -f '<<f>>'" voice)
- "espeak -f '<<f>>' -w '<<fne>>.wav'")
+ (cj/dwim-shell--text-to-speech-command system-type voice)
:utils (if (eq system-type 'darwin) "say" "espeak"))))
(defun cj/dwim-shell-commands-remove-empty-directories ()
diff --git a/modules/elfeed-config.el b/modules/elfeed-config.el
index ad7bda83a..7b4d7d745 100644
--- a/modules/elfeed-config.el
+++ b/modules/elfeed-config.el
@@ -29,21 +29,26 @@
(require 'system-lib)
(require 'media-utils)
+(declare-function elfeed "elfeed")
+(declare-function elfeed-update "elfeed")
+(declare-function elfeed-entry-link "elfeed")
+(declare-function elfeed-untag "elfeed")
+(declare-function elfeed-search-selected "elfeed")
+(declare-function elfeed-search-tag-all "elfeed")
+(declare-function elfeed-search-update-entry "elfeed")
+(declare-function elfeed-search-update--force "elfeed")
+(declare-function elfeed-search-untag-all-unread "elfeed")
+(declare-function eww-browse-url "eww")
+(declare-function eww-readable "eww")
+
;; ------------------------------- Elfeed Config -------------------------------
(use-package elfeed
:bind
- ("M-S-r" . cj/elfeed-open) ;; was M-R
(:map elfeed-show-mode-map
("w" . eww-open-in-new-buffer))
(:map elfeed-search-mode-map
- ("w" . cj/elfeed-eww-open) ;; opens in eww
- ("b" . cj/elfeed-browser-open) ;; opens in external browser
- ("d" . cj/elfeed-youtube-dl) ;; async download with yt-dlp and tsp
- ("v" . cj/play-with-video-player)) ;; async play with mpv
- ("V" . cj/select-media-player) ;; Capital V to select player
- ("R" . cj/elfeed-mark-all-as-read) ;; capital marks all as read, since upper case marks one as read
- ("U" . cj/elfeed-mark-all-as-unread) ;; capital marks all as unread, since lower case marks one as unread
+ ("V" . cj/select-media-player)) ;; Capital V to select player
:config
(setq elfeed-db-directory (concat user-emacs-directory ".elfeed-db"))
(setq-default elfeed-search-title-max-width 150)
@@ -90,19 +95,22 @@
(elfeed)
(elfeed-update)
(elfeed-search-update--force))
+(keymap-global-set "M-S-r" #'cj/elfeed-open) ;; was M-R
;; -------------------------- Elfeed Filter Functions --------------------------
(defun cj/elfeed-mark-all-as-read ()
"Remove the \='unread\=' tag from all visible entries in search buffer."
(interactive)
- (mark-whole-buffer)
+ (goto-char (point-min))
+ (push-mark (point-max) nil t)
(elfeed-search-untag-all-unread))
(defun cj/elfeed-mark-all-as-unread ()
"Add the \='unread\=' tag from all visible entries in the search buffer."
(interactive)
- (mark-whole-buffer)
+ (goto-char (point-min))
+ (push-mark (point-max) nil t)
(elfeed-search-tag-all 'unread))
(defun cj/elfeed-set-filter-and-update (filterstring)
@@ -126,23 +134,13 @@ Returns the stream URL or nil on failure."
(cmd-args (append '("yt-dlp" "-q" "-g")
format-args
(list url)))
- ;; DEBUG: Log the command
- (_ (cj/log-silently "DEBUG: Extracting with command: %s"
- (mapconcat #'shell-quote-argument cmd-args " ")))
(output (with-temp-buffer
(let ((exit-code (apply #'call-process
(car cmd-args) nil t nil
(cdr cmd-args))))
(if (zerop exit-code)
(string-trim (buffer-string))
- (progn
- ;; DEBUG: Log failure
- (cj/log-silently "DEBUG: yt-dlp failed with exit code %d" exit-code)
- (cj/log-silently "DEBUG: Error output: %s" (buffer-string))
- nil))))))
- ;; DEBUG: Log the result
- (cj/log-silently "DEBUG: Extracted URL: %s"
- (if output (truncate-string-to-width output 100) "nil"))
+ nil)))))
(when (and output (string-match-p "^https?://" output))
output)))
@@ -223,6 +221,15 @@ Note: Function name kept for backwards compatibility."
"Seconds to wait for a synchronous YouTube page fetch before giving up.
Without a timeout a hung request would block Emacs indefinitely.")
+(defun cj/--decode-html-entities (text)
+ "Decode the common HTML entities in TEXT.
+Handles &amp; &lt; &gt; &quot; &#39; and &#x27; -- the entities YouTube's
+og:title meta tag emits. Decoded left-to-right, &amp; first."
+ (let ((entities '(("&amp;" . "&") ("&lt;" . "<") ("&gt;" . ">")
+ ("&quot;" . "\"") ("&#39;" . "'") ("&#x27;" . "'"))))
+ (dolist (pair entities text)
+ (setq text (replace-regexp-in-string (car pair) (cdr pair) text)))))
+
(defun cj/youtube-to-elfeed-feed-format (url type)
"Convert YouTube URL to elfeed-feeds format.
@@ -274,13 +281,8 @@ TYPE should be either \='channel or \='playlist."
(goto-char (point-min))
(when (re-search-forward "<meta property=\"og:title\" content=\"\\([^\"]+\\)\"" nil t)
(setq title (match-string 1))
- ;; Simple HTML entity decoding
- (setq title (replace-regexp-in-string "&amp;" "&" title))
- (setq title (replace-regexp-in-string "&lt;" "<" title))
- (setq title (replace-regexp-in-string "&gt;" ">" title))
- (setq title (replace-regexp-in-string "&quot;" "\"" title))
- (setq title (replace-regexp-in-string "&#39;" "'" title))
- (setq title (replace-regexp-in-string "&#x27;" "'" title))))))
+ ;; Decode HTML entities in the extracted title
+ (setq title (cj/--decode-html-entities title))))))
;; Always kill the temporary URL buffer, even when extraction failed --
;; the old code only killed it when an ID was found, leaking it otherwise.
(when (buffer-live-p buffer)
@@ -308,5 +310,18 @@ TYPE should be either \='channel or \='playlist."
(insert result))
result))
+;; --------------------------- Search-Mode Keybindings -------------------------
+;; Bound here (not in use-package :bind) because these commands are defined in
+;; this file; a :bind autoload stub plus the defun triggers a "defined multiple
+;; times" byte-compile warning.
+
+(with-eval-after-load 'elfeed
+ (keymap-set elfeed-search-mode-map "w" #'cj/elfeed-eww-open) ;; opens in eww
+ (keymap-set elfeed-search-mode-map "b" #'cj/elfeed-browser-open) ;; opens in external browser
+ (keymap-set elfeed-search-mode-map "d" #'cj/elfeed-youtube-dl) ;; async download with yt-dlp and tsp
+ (keymap-set elfeed-search-mode-map "v" #'cj/play-with-video-player) ;; async play with mpv
+ (keymap-set elfeed-search-mode-map "R" #'cj/elfeed-mark-all-as-read) ;; capital R marks all read (lower case marks one)
+ (keymap-set elfeed-search-mode-map "U" #'cj/elfeed-mark-all-as-unread)) ;; capital U marks all unread (lower case marks one)
+
(provide 'elfeed-config)
;;; elfeed-config.el ends here.
diff --git a/modules/erc-config.el b/modules/erc-config.el
index 067b1e577..3e98a66a3 100644
--- a/modules/erc-config.el
+++ b/modules/erc-config.el
@@ -33,6 +33,33 @@
;; is read at load time below (erc-user-full-name), so a standalone .elc needs it.
(require 'user-constants)
+;; ERC loads lazily (use-package :commands), so these symbols aren't bound at
+;; this file's compile time. Declare them to keep the byte-compiler quiet
+;; without forcing an eager require.
+
+;; Functions provided by the erc package.
+(declare-function erc-buffer-list "erc")
+(declare-function erc-server-process-alive "erc")
+(declare-function erc-server-or-unjoined-channel-buffer-p "erc")
+(declare-function erc-current-nick "erc")
+(declare-function erc-join-channel "erc")
+(declare-function erc-part-from-channel "erc")
+(declare-function erc-quit-server "erc")
+
+;; Variables read/set in the use-package :config block below.
+(defvar erc-log-channels-directory)
+(defvar erc-track-exclude-types)
+(defvar erc-track-exclude-server-buffer)
+(defvar erc-track-visibility)
+(defvar erc-track-switch-direction)
+(defvar erc-track-showcount)
+;; NOTE: erc-unique-buffers and erc-generate-buffer-name-function are not ERC
+;; variables in Emacs 30.x (no defcustom/defvar in the package); the setq below
+;; only creates inert globals. Declared here to silence the warning without
+;; changing the existing (no-op) behavior -- see the SUSPICIOUS note.
+(defvar erc-unique-buffers)
+(defvar erc-generate-buffer-name-function)
+
;; ------------------------------------ ERC ------------------------------------
;; Server definitions and connection settings
@@ -99,7 +126,7 @@ Change this value to use a different nickname.")
(let ((server-buffers '()))
(dolist (buf (erc-buffer-list))
(with-current-buffer buf
- (when (and (erc-server-buffer-p) (erc-server-process-alive))
+ (when (and (erc-server-or-unjoined-channel-buffer-p) (erc-server-process-alive))
(unless (member (buffer-name) server-buffers)
(push (buffer-name) server-buffers)))))
@@ -132,7 +159,7 @@ Buffer names are shown with server context for clarity."
"Return t if the current buffer is an active ERC server buffer."
(and (derived-mode-p 'erc-mode)
(erc-server-process-alive)
- (erc-server-buffer-p)))
+ (erc-server-or-unjoined-channel-buffer-p)))
(defun cj/erc-get-channels-for-current-server ()
@@ -158,7 +185,7 @@ Auto-adds # prefix if missing. Offers completion from configured channels."
(let ((server-buffers (cl-remove-if-not
(lambda (buf)
(with-current-buffer buf
- (and (erc-server-buffer-p)
+ (and (erc-server-or-unjoined-channel-buffer-p)
(erc-server-process-alive))))
(erc-buffer-list))))
(if server-buffers
@@ -184,6 +211,14 @@ Auto-adds # prefix if missing. Offers completion from configured channels."
(erc-join-channel channel)))
(message "Failed to establish an active ERC connection")))
+(defun cj/erc-generate-buffer-name (parms)
+ "Generate buffer name in the format SERVER-CHANNEL."
+ (let ((network (plist-get parms :server))
+ (target (plist-get parms :target)))
+ (if target
+ (concat (or network "") "-" (or target ""))
+ (or network ""))))
+
;; Keymap for ERC commands (must be defined before use-package erc)
(defvar-keymap cj/erc-keymap
:doc "Keymap for ERC-related commands"
@@ -259,15 +294,7 @@ Auto-adds # prefix if missing. Offers completion from configured channels."
;; Note: erc-rename-buffers is obsolete as of Emacs 29.1 (old behavior is now permanent)
(setq erc-unique-buffers t)
- ;; Custom buffer naming function
- (defun cj/erc-generate-buffer-name (parms)
- "Generate buffer name in the format SERVER-CHANNEL."
- (let ((network (plist-get parms :server))
- (target (plist-get parms :target)))
- (if target
- (concat (or network "") "-" (or target ""))
- (or network ""))))
-
+ ;; Custom buffer naming (cj/erc-generate-buffer-name is defined at top level)
(setq erc-generate-buffer-name-function 'cj/erc-generate-buffer-name)
;; Configure erc-track (show channel activity in modeline)
@@ -338,16 +365,15 @@ NICK is the sender and MESSAGE is the message text."
:after erc
:hook (erc-mode . erc-nicks-mode))
-;; ------------------------------ ERC Yank To Gist -----------------------------
-;; automatically create a Gist if pasting more than 5 lines
-;; this module requires https://github.com/defunkt/gist
-;; via ruby: 'gem install gist' via the aur: yay -S gist
-
-(use-package erc-yank
- :after erc
- :bind
- (:map erc-mode-map
- ("C-y" . erc-yank)))
+;; -------------------------------- ERC Yank ----------------------------------
+;; The erc-yank package was dropped 2026-06-20: a paste over 5 lines became a
+;; PUBLIC gist (it called `gist -P', the clipboard paste flag, with no
+;; `--private'), behind only a single y-or-n-p and with no guard if the `gist'
+;; binary was absent -- a one-keystroke path to publishing whatever sat on the
+;; system clipboard. No replacement binding is needed: erc-mode-map defines no
+;; C-y of its own, so with erc-yank gone C-y falls through to the ordinary
+;; global `yank' and a paste stays local. Gist a large snippet by hand when
+;; that's actually wanted.
(provide 'erc-config)
;;; erc-config.el ends here
diff --git a/modules/eshell-config.el b/modules/eshell-config.el
index d3c8ccdfd..c2ec6d152 100644
--- a/modules/eshell-config.el
+++ b/modules/eshell-config.el
@@ -26,6 +26,32 @@
(require 'system-utils)
+;; Eshell is loaded lazily (:commands eshell), so its vars and functions are
+;; not defined when this file is byte-compiled standalone. Declare them to
+;; silence compile-time free-variable / undefined-function warnings.
+(defvar eshell-banner-message)
+(defvar eshell-scroll-to-bottom-on-input)
+(defvar eshell-error-if-no-glob)
+(defvar eshell-hist-ignoredups)
+(defvar eshell-save-history-on-exit)
+(defvar eshell-prefer-lisp-functions)
+(defvar eshell-destroy-buffer-when-process-dies)
+(defvar eshell-prompt-function)
+(defvar eshell-cmpl-cycle-completions)
+(defvar eshell-modules-list)
+(defvar eshell-hist-mode-map)
+(defvar eshell-visual-commands)
+(defvar eshell-visual-subcommands)
+(defvar eshell-visual-options)
+(defvar eshell-history-ring)
+(defvar eshell-preoutput-filter-functions)
+(defvar eshell-output-filter-functions)
+
+(declare-function ring-elements "ring")
+(declare-function eshell-send-input "esh-mode")
+(declare-function eshell/pwd "em-dirs")
+(declare-function eshell/alias "em-alias")
+
(defgroup cj/eshell nil
"Personal Eshell configuration."
:group 'eshell)
@@ -75,15 +101,15 @@ pairs where COMMAND is the `cd' string `eshell/alias' should run."
(setq eshell-prompt-function
(lambda ()
(concat
- (propertize (format-time-string "[%d-%m-%y %T]") 'face '(:foreground "gray"))
+ (propertize (format-time-string "[%d-%m-%y %T]") 'face 'default)
" "
- (propertize (user-login-name) 'face '(:foreground "gray"))
+ (propertize (user-login-name) 'face 'default)
" "
- (propertize (system-name) 'face '(:foreground "gray"))
+ (propertize (system-name) 'face 'default)
":"
- (propertize (abbreviate-file-name (eshell/pwd)) 'face '(:foreground "gray"))
+ (propertize (abbreviate-file-name (eshell/pwd)) 'face 'default)
"\n"
- (propertize "%" 'face '(:foreground "white"))
+ (propertize "%" 'face 'default)
" ")))
(add-hook
diff --git a/modules/eww-config.el b/modules/eww-config.el
index a41a9a76e..ff7ddc211 100644
--- a/modules/eww-config.el
+++ b/modules/eww-config.el
@@ -32,6 +32,8 @@
(require 'cl-lib)
+(declare-function eww-add-bookmark "eww")
+
(defgroup my-eww-user-agent nil
"EWW-only User-Agent management."
:group 'eww)
@@ -42,6 +44,13 @@
:type 'string
:group 'my-eww-user-agent)
+;; This file is lexical-binding, so `let'-binding url.el's special var below
+;; needs it declared special at compile time. Without this the byte-compiled
+;; advice binds `url-request-extra-headers' lexically and the injected
+;; User-Agent never reaches `url-retrieve' (it reads the dynamic value) -- the
+;; UA injection silently no-ops in compiled production, and the test sees nil.
+(defvar url-request-extra-headers)
+
(defun my-eww--inject-user-agent (orig-fun &rest args)
"Set a User-Agent only when making requests from an EWW buffer."
(if (derived-mode-p 'eww-mode)
diff --git a/modules/face-diagnostic.el b/modules/face-diagnostic.el
index 6b1b547f1..a2bfe2483 100644
--- a/modules/face-diagnostic.el
+++ b/modules/face-diagnostic.el
@@ -298,6 +298,18 @@ mutation."
;; ------------------------------- Rendering -----------------------------------
+(defun cj/--face-diag-face-button (face)
+ "Render FACE as a button that runs `describe-face' on it.
+A real, named face becomes a `buttonize'd string (RET or mouse opens its
+`describe-face' help); anything else -- an anonymous (:attr val ...) spec or a
+symbol that is not a face -- is returned as a plain string so the report still
+reads cleanly."
+ (let ((label (format "%s" face)))
+ (if (and (symbolp face) (facep face))
+ (buttonize label (lambda (f) (describe-face f)) face
+ (format "describe-face: %s" face))
+ label)))
+
(defun cj/--face-diag-render-banner (classification)
"Return a one-line banner for an out-of-scope CLASSIFICATION, or \"\"."
(pcase classification
@@ -320,8 +332,9 @@ mutation."
(or (plist-get char :script) "none"))))
(defun cj/--face-diag-render-faces (faces)
- "Render a list of FACES (symbols or specs) comma-separated, or \"(none)\"."
- (if faces (mapconcat (lambda (f) (format "%s" f)) faces ", ") "(none)"))
+ "Render a list of FACES (symbols or specs) comma-separated, or \"(none)\".
+Real faces render as `describe-face' buttons (see `cj/--face-diag-face-button')."
+ (if faces (mapconcat #'cj/--face-diag-face-button faces ", ") "(none)"))
(defun cj/--face-diag-render-stack (stack)
"Render the STACK plist (faces by source) as a block."
@@ -329,18 +342,21 @@ mutation."
"Face stack (highest priority first):\n"
(format " text properties: %s\n"
(cj/--face-diag-render-faces (plist-get stack :text-property)))
- (format " overlays: %s\n"
- (let ((ov (plist-get stack :overlays)))
- (if ov
- (mapconcat (lambda (e)
- (format "%s (priority %s)"
- (plist-get e :face)
- (or (plist-get e :priority) "nil")))
- ov ", ")
- "(none)")))
- (format " active remaps: %s\n"
- (let ((rm (plist-get stack :remaps)))
- (if rm (mapconcat (lambda (e) (format "%s" (car e))) rm ", ") "(none)")))
+ " overlays: "
+ (let ((ov (plist-get stack :overlays)))
+ (if ov
+ (mapconcat (lambda (e)
+ (concat (cj/--face-diag-face-button (plist-get e :face))
+ (format " (priority %s)"
+ (or (plist-get e :priority) "nil"))))
+ ov ", ")
+ "(none)"))
+ "\n"
+ " active remaps: "
+ (let ((rm (plist-get stack :remaps)))
+ (if rm (mapconcat (lambda (e) (cj/--face-diag-face-button (car e))) rm ", ")
+ "(none)"))
+ "\n"
" default: default\n\n"))
(defun cj/--face-diag-render-attributes (attrs)
@@ -372,13 +388,15 @@ mutation."
(if prov
(mapconcat
(lambda (p)
- (format (concat " %s\n themes: %s\n config: %s\n"
- " inherits: %s\n unspecified (-> default): %s")
- (plist-get p :face)
- (or (plist-get p :themes) "(none)")
- (or (plist-get p :config) "(none)")
- (or (plist-get p :inherit-chain) "(none)")
- (or (plist-get p :unspecified) "(none)")))
+ (concat
+ " "
+ (cj/--face-diag-face-button (plist-get p :face))
+ (format (concat "\n themes: %s\n config: %s\n"
+ " inherits: %s\n unspecified (-> default): %s")
+ (or (plist-get p :themes) "(none)")
+ (or (plist-get p :config) "(none)")
+ (or (plist-get p :inherit-chain) "(none)")
+ (or (plist-get p :unspecified) "(none)"))))
prov "\n")
" (no named faces)")
"\n"))
diff --git a/modules/flycheck-config.el b/modules/flycheck-config.el
index 5626095c5..1afd3ae6c 100644
--- a/modules/flycheck-config.el
+++ b/modules/flycheck-config.el
@@ -45,6 +45,14 @@
(require 'keybindings) ;; provides cj/custom-keymap (use-package :map below)
+;; ------------------------------- Declarations --------------------------------
+
+(declare-function flycheck-mode "flycheck")
+(declare-function flycheck-list-errors "flycheck")
+(declare-function flycheck-add-mode "flycheck")
+(declare-function flycheck-buffer "flycheck")
+(declare-function cj/flycheck-prose-on-demand "flycheck-config")
+
(defun cj/prose-helpers-on ()
"Ensure that `abbrev-mode' and `flycheck-mode' are on in the current buffer."
(interactive)
diff --git a/modules/font-config.el b/modules/font-config.el
index 39d21364c..3272a946e 100644
--- a/modules/font-config.el
+++ b/modules/font-config.el
@@ -56,6 +56,9 @@
(require 'host-environment)
(require 'keybindings) ;; establishes the C-z prefix used for "C-z F" below
+(defvar text-scale-mode-step)
+(declare-function cj/disable-emojify-mode "font-config")
+
;; ---------------------- HarfBuzz Font Cache Crash Fix -----------------------
;; Prevents Emacs from compacting font caches during GC. Without this, GC can
;; free font cache entries that HarfBuzz still references, causing SIGSEGV
@@ -153,36 +156,38 @@
:italic-slant italic
:line-spacing nil))))
-(with-eval-after-load 'fontaine
- ;; Track which frames have had fonts applied
- (defvar cj/fontaine-configured-frames nil
- "List of frames that have had fontaine configuration applied.")
+;; Track which frames have had fonts applied
+(defvar cj/fontaine-configured-frames nil
+ "List of frames that have had fontaine configuration applied.")
- (defun cj/apply-font-settings-to-frame (&optional frame)
- "Apply font settings to FRAME if not already configured.
+(declare-function fontaine-set-preset "fontaine")
+
+(defun cj/apply-font-settings-to-frame (&optional frame)
+ "Apply font settings to FRAME if not already configured.
If FRAME is nil, uses the selected frame."
- (let ((target-frame (or frame (selected-frame))))
- (unless (member target-frame cj/fontaine-configured-frames)
- (with-selected-frame target-frame
- (when (env-gui-p)
- (fontaine-set-preset 'default)
- (push target-frame cj/fontaine-configured-frames))))))
-
- (defun cj/cleanup-frame-list (frame)
- "Remove FRAME from the configured frames list when deleted."
- (setq cj/fontaine-configured-frames
- (delq frame cj/fontaine-configured-frames)))
+ (let ((target-frame (or frame (selected-frame))))
+ (unless (member target-frame cj/fontaine-configured-frames)
+ (with-selected-frame target-frame
+ (when (env-gui-p)
+ (fontaine-set-preset 'default)
+ (push target-frame cj/fontaine-configured-frames))))))
+
+(defun cj/cleanup-frame-list (frame)
+ "Remove FRAME from the configured frames list when deleted."
+ (setq cj/fontaine-configured-frames
+ (delq frame cj/fontaine-configured-frames)))
+(with-eval-after-load 'fontaine
;; Handle daemon mode and regular mode
(if (daemonp)
- (progn
- ;; Apply to each new frame in daemon mode
- (add-hook 'server-after-make-frame-hook #'cj/apply-font-settings-to-frame)
- ;; Clean up deleted frames from tracking list
- (add-hook 'delete-frame-functions #'cj/cleanup-frame-list))
- ;; Apply immediately in non-daemon mode
- (when (env-gui-p)
- (cj/apply-font-settings-to-frame))))
+ (progn
+ ;; Apply to each new frame in daemon mode
+ (add-hook 'server-after-make-frame-hook #'cj/apply-font-settings-to-frame)
+ ;; Clean up deleted frames from tracking list
+ (add-hook 'delete-frame-functions #'cj/cleanup-frame-list))
+ ;; Apply immediately in non-daemon mode
+ (when (env-gui-p)
+ (cj/apply-font-settings-to-frame))))
;; ----------------------------- Font Install Check ----------------------------
;; convenience function to indicate whether a font is available by name.
@@ -196,22 +201,23 @@ If FRAME is nil, uses the selected frame."
;; ------------------------------- All The Icons -------------------------------
;; icons made available through fonts
+(declare-function all-the-icons-install-fonts "all-the-icons")
+
+(defun cj/maybe-install-all-the-icons-fonts (&optional _frame)
+ "Install all-the-icons fonts if needed and we have a GUI."
+ (when (and (env-gui-p)
+ (not (cj/font-installed-p "all-the-icons")))
+ (all-the-icons-install-fonts t)
+ ;; Remove this hook after successful installation
+ (remove-hook 'server-after-make-frame-hook #'cj/maybe-install-all-the-icons-fonts)))
+
(use-package all-the-icons
:demand t
:config
- ;; Check for font installation after frame creation
- (defun cj/maybe-install-all-the-icons-fonts (&optional _frame)
- "Install all-the-icons fonts if needed and we have a GUI."
- (when (and (env-gui-p)
- (not (cj/font-installed-p "all-the-icons")))
- (all-the-icons-install-fonts t)
- ;; Remove this hook after successful installation
- (remove-hook 'server-after-make-frame-hook #'cj/maybe-install-all-the-icons-fonts)))
-
;; Handle both daemon and non-daemon modes
(if (daemonp)
- (add-hook 'server-after-make-frame-hook #'cj/maybe-install-all-the-icons-fonts)
- (cj/maybe-install-all-the-icons-fonts)))
+ (add-hook 'server-after-make-frame-hook #'cj/maybe-install-all-the-icons-fonts)
+ (cj/maybe-install-all-the-icons-fonts)))
(use-package all-the-icons-nerd-fonts
:after all-the-icons
@@ -262,13 +268,12 @@ the fontset repeatedly is harmless, so it can be called from
(setq emojify-display-style (if (env-gui-p) 'image 'unicode))
(setq emojify-emoji-styles '(ascii unicode github))
- ;; Disable emojify in programming and gptel modes
+ ;; Disable emojify in programming modes
(defun cj/disable-emojify-mode ()
"Disable emojify-mode in the current buffer."
(emojify-mode -1))
- (add-hook 'prog-mode-hook #'cj/disable-emojify-mode)
- (add-hook 'gptel-mode-hook #'cj/disable-emojify-mode))
+ (add-hook 'prog-mode-hook #'cj/disable-emojify-mode))
;; -------------------------- Display Available Fonts --------------------------
;; display all available fonts on the system in a side panel
diff --git a/modules/games-config.el b/modules/games-config.el
index 9aa598168..0ff01c809 100644
--- a/modules/games-config.el
+++ b/modules/games-config.el
@@ -5,32 +5,30 @@
;;
;; Layer: 4 (Optional).
;; Category: O.
-;; Load shape: eager.
-;; Eager reason: none; optional games, a command-loaded deferral candidate.
-;; Top-level side effects: package configuration via use-package.
-;; Runtime requires: none.
+;; Load shape: command (deferred).
+;; Eager reason: none; loaded by init.el when malyon loads.
+;; Top-level side effects: sets malyon-stories-directory after malyon loads.
+;; Runtime requires: user-constants.
;; Direct test load: yes.
;;
;; Configuration for game packages.
;;
-;; - Malyon for playing interactive fiction and text adventures in Z-machine format
-;; (stories directory: ~/sync/org/text.games/)
-;; - 2048 number-tile puzzle game
+;; - Malyon: interactive fiction / Z-machine player (stories under ~/sync/org/text.games/).
+;; - 2048: number-tile puzzle.
+;;
+;; malyon and 2048-game autoload their own commands via package.el, so this
+;; module owns neither command -- it only supplies malyon's stories directory.
+;; init.el loads it via `with-eval-after-load 'malyon', so it loads on first
+;; use rather than at startup.
;;
;;; Code:
-;; ----------------------------------- Malyon ----------------------------------
-;; text based adventure player
+(require 'user-constants) ;; org-dir
-(use-package malyon
- :defer 1
- :config
- (setq malyon-stories-directory (concat org-dir "text.games/")))
+(defvar malyon-stories-directory)
-;; ------------------------------------ 2048 -----------------------------------
-;; combine numbered tiles to create the elusive number 2048.
-(use-package 2048-game
- :defer 1)
+(with-eval-after-load 'malyon
+ (setq malyon-stories-directory (concat org-dir "text.games/")))
(provide 'games-config)
;;; games-config.el ends here.
diff --git a/modules/gcmh-config.el b/modules/gcmh-config.el
new file mode 100644
index 000000000..beceb1a01
--- /dev/null
+++ b/modules/gcmh-config.el
@@ -0,0 +1,30 @@
+;;; gcmh-config.el --- Garbage collection strategy via gcmh -*- lexical-binding: t -*-
+
+;;; Commentary:
+;; gcmh (the Garbage Collector Magic Hack) owns `gc-cons-threshold' for the
+;; session. It keeps the threshold very high while you are active so GC never
+;; pauses mid-edit, then drops it and collects on idle, when a pause is
+;; invisible. This replaces the old hand-rolled scheme -- a stock-800KB restore
+;; in early-init.el plus a minibuffer setup/exit bump -- which pinned GC at
+;; 800000 (Emacs's bare-editor default), far too low for a config this size and
+;; the cause of frequent GC pauses during completion, agenda builds, and LSP/AI
+;; activity.
+;;
+;; Kept in its own module, not system-defaults.el: that module is pre-loaded by
+;; the comp-errors test harness, which has no package system, so an `:ensure'
+;; package there errors at load time. early-init.el bumps the threshold to
+;; `most-positive-fixnum' for startup and deliberately does not restore it;
+;; `gcmh-mode' takes ownership from here on.
+
+;;; Code:
+
+(use-package gcmh
+ :ensure t
+ :demand t
+ :config
+ (setq gcmh-idle-delay 'auto ; scale the idle GC delay to GC cost
+ gcmh-high-cons-threshold (* 1 1024 1024 1024)) ; 1 GB during activity
+ (gcmh-mode 1))
+
+(provide 'gcmh-config)
+;;; gcmh-config.el ends here
diff --git a/modules/google-keep-config.el b/modules/google-keep-config.el
new file mode 100644
index 000000000..1738fa6e0
--- /dev/null
+++ b/modules/google-keep-config.el
@@ -0,0 +1,210 @@
+;;; google-keep-config.el --- Google Keep -> org integration -*- lexical-binding: t; coding: utf-8; -*-
+;; author Craig Jennings <c@cjennings.net>
+
+;;; Commentary:
+;; A read-only view of Google Keep notes as an org page. `cj/keep-refresh'
+;; runs a Python gkeepapi bridge (scripts/google-keep/keep-bridge.py), parses
+;; its JSON, and regenerates `keep-file' with one org header per note. Editing
+;; the file does NOT sync back to Keep -- that is v2.
+;;
+;; The pure JSON-to-org core (the cj/keep--render* / --note-* helpers) is kept
+;; free of .emacs.d specifics so it can later extract to a standalone package;
+;; the IO layer and this module supply paths, auth, and keys.
+;;
+;; One-time setup: install the client (pip install gkeepapi), obtain a Google
+;; master token, set `cj/keep-email', and store the token in authinfo.gpg as
+;; machine google-keep login <you@gmail.com> password <master-token>
+;; See docs/specs/google-keep-emacs-integration-spec.org.
+
+;;; Code:
+
+(require 'json)
+(require 'subr-x)
+(require 'system-lib) ;; cj/auth-source-secret-value, cj/executable-find-or-warn
+(require 'user-constants) ;; keep-file
+
+;; ------------------------------ Configuration --------------------------------
+
+(defgroup cj/keep nil
+ "Google Keep to org integration."
+ :group 'applications
+ :prefix "cj/keep-")
+
+(defcustom cj/keep-email nil
+ "Google account email for the Keep bridge, also the authinfo login.
+Unset until the one-time setup is done; `cj/keep-refresh' warns when nil."
+ :type '(choice (const :tag "Unset" nil) string)
+ :group 'cj/keep)
+
+(defcustom cj/keep-auth-host "google-keep"
+ "The authinfo.gpg machine entry holding the Keep master token."
+ :type 'string
+ :group 'cj/keep)
+
+(defcustom cj/keep-python "python3"
+ "Python interpreter used to run the Keep bridge."
+ :type 'string
+ :group 'cj/keep)
+
+(defvar cj/keep--bridge-script
+ (expand-file-name "scripts/google-keep/keep-bridge.py" user-emacs-directory)
+ "Path to the gkeepapi bridge script.")
+
+(defconst cj/keep--web-base "https://keep.google.com/#NOTE/"
+ "Base URL for a Keep note back-link.")
+
+;; --------------------------- Pure core: JSON -> org --------------------------
+;; These take plain data and return strings -- no IO, no .emacs.d paths -- so
+;; they unit-test directly and lift out to a package unchanged.
+
+(defun cj/keep--parse-json (json-string)
+ "Parse the bridge JSON-STRING into a list of note alists."
+ (json-parse-string json-string
+ :object-type 'alist :array-type 'list
+ :false-object nil :null-object nil))
+
+(defun cj/keep--label-to-tag (label)
+ "Sanitize LABEL into a valid org tag (alphanumerics / _ / @ / # / %)."
+ (replace-regexp-in-string "[^[:alnum:]_@#%]" "_" label))
+
+(defun cj/keep--note-tags (note)
+ "Return the trailing org-tag string for NOTE (labels + archived), or \"\"."
+ (let ((tags (append (mapcar #'cj/keep--label-to-tag (alist-get 'labels note))
+ (and (alist-get 'archived note) '("archived")))))
+ (if tags (concat " :" (string-join tags ":") ":") "")))
+
+(defun cj/keep--note-heading (note)
+ "Render NOTE (an alist) as one org subtree string."
+ (let* ((id (alist-get 'id note))
+ (title (alist-get 'title note))
+ (text (alist-get 'text note))
+ (heading (if (and title (> (length title) 0)) title "(untitled)")))
+ (concat
+ "* " heading (cj/keep--note-tags note) "\n"
+ ":PROPERTIES:\n"
+ ":KEEP_ID: " (or id "") "\n"
+ ":PINNED: " (if (alist-get 'pinned note) "t" "nil") "\n"
+ ":COLOR: " (or (alist-get 'color note) "") "\n"
+ ":ARCHIVED: " (if (alist-get 'archived note) "t" "nil") "\n"
+ ":UPDATED: " (or (alist-get 'updated note) "") "\n"
+ ":END:\n"
+ (if (and id (> (length id) 0))
+ (concat "[[" cj/keep--web-base id "][open in Keep]]\n")
+ "")
+ "\n"
+ (if (and text (> (length text) 0)) (concat text "\n") ""))))
+
+(defun cj/keep--sort-pinned-first (notes)
+ "Return NOTES with pinned ones first, original order otherwise preserved."
+ (let (pinned rest)
+ (dolist (n notes)
+ (if (alist-get 'pinned n) (push n pinned) (push n rest)))
+ (append (nreverse pinned) (nreverse rest))))
+
+(defun cj/keep--render (notes &optional generated-at)
+ "Render NOTES (a list of alists) into the full org page string.
+GENERATED-AT is an optional last-refresh timestamp string for the header."
+ (concat
+ "# Generated by cj/keep-refresh -- read-only view; edits here do NOT sync to Keep.\n"
+ "#+TITLE: Google Keep\n"
+ (if generated-at (concat "# Last refresh: " generated-at "\n") "")
+ "\n"
+ (mapconcat #'cj/keep--note-heading (cj/keep--sort-pinned-first notes) "")))
+
+;; ------------------------------- IO: run + write -----------------------------
+
+(defun cj/keep--write-atomically (content file)
+ "Write CONTENT to FILE via a temp file in FILE's directory + atomic rename."
+ (let ((tmp (make-temp-file
+ (expand-file-name (concat "." (file-name-nondirectory file) ".")
+ (file-name-directory file))
+ nil nil content)))
+ (rename-file tmp file t)))
+
+(defun cj/keep--warn (token)
+ "Surface a Keep bridge failure TOKEN as a `display-warning'."
+ (display-warning
+ 'cj/keep
+ (pcase token
+ ("no-gkeepapi" "Keep bridge: gkeepapi is not installed (pip install gkeepapi).")
+ ("no-token" "Keep bridge: no master token in authinfo.gpg, or `cj/keep-email' is unset.")
+ ("auth-failed" "Keep bridge: Google rejected the credentials (token expired or revoked?).")
+ ("network" "Keep bridge: network error reaching Google Keep.")
+ (_ (format "Keep bridge failed: %s" (if (string-empty-p token) "unknown error" token))))
+ :error))
+
+(defun cj/keep--write-notes (json)
+ "Parse bridge JSON, render, and write `keep-file' atomically.
+Returns the note count."
+ (let* ((notes (cj/keep--parse-json json))
+ (org (cj/keep--render notes (format-time-string "%Y-%m-%d %H:%M"))))
+ (cj/keep--write-atomically org keep-file)
+ (length notes)))
+
+;;;###autoload
+(defun cj/keep-refresh ()
+ "Fetch Google Keep notes and regenerate `keep-file' (a read-only view)."
+ (interactive)
+ (let ((token (and cj/keep-email
+ (cj/auth-source-secret-value cj/keep-auth-host cj/keep-email))))
+ (cond
+ ((not (file-exists-p cj/keep--bridge-script))
+ (user-error "Keep bridge script not found: %s" cj/keep--bridge-script))
+ ((or (not cj/keep-email) (not token))
+ (cj/keep--warn "no-token"))
+ (t
+ (let* ((out (generate-new-buffer " *keep-bridge-out*"))
+ (err (generate-new-buffer " *keep-bridge-err*"))
+ (process-environment
+ (append (list (concat "KEEP_EMAIL=" cj/keep-email)
+ (concat "KEEP_MASTER_TOKEN=" token))
+ process-environment)))
+ (message "Keep: fetching...")
+ (make-process
+ :name "keep-bridge"
+ :buffer out
+ :stderr err
+ :command (list cj/keep-python cj/keep--bridge-script)
+ :sentinel
+ (lambda (proc _event)
+ (when (memq (process-status proc) '(exit signal))
+ (unwind-protect
+ (if (and (eq (process-status proc) 'exit)
+ (= (process-exit-status proc) 0))
+ (let ((n (cj/keep--write-notes
+ (with-current-buffer out (buffer-string)))))
+ (message "Keep: wrote %d notes to %s" n keep-file))
+ (cj/keep--warn
+ (string-trim (if (buffer-live-p err)
+ (with-current-buffer err (buffer-string))
+ ""))))
+ (when (buffer-live-p out) (kill-buffer out))
+ (when (buffer-live-p err) (kill-buffer err)))))))))))
+
+;;;###autoload
+(defun cj/keep-open ()
+ "Open the generated Keep org file, offering to refresh when it's absent."
+ (interactive)
+ (if (file-exists-p keep-file)
+ (find-file keep-file)
+ (if (y-or-n-p "Keep file doesn't exist yet. Refresh now? ")
+ (cj/keep-refresh)
+ (message "Run M-x cj/keep-refresh to generate it"))))
+
+;; --------------------------------- Glue / keys -------------------------------
+
+(defvar cj/keep-prefix-map
+ (let ((map (make-sparse-keymap)))
+ (define-key map "r" #'cj/keep-refresh)
+ (define-key map "o" #'cj/keep-open)
+ map)
+ "Prefix keymap for Google Keep commands (bound to \\=`C-c k').")
+
+(keymap-global-set "C-c k" cj/keep-prefix-map)
+
+;; Warn at load if the interpreter is missing; gkeepapi/token failures surface
+;; at refresh time via the bridge's stderr reason token.
+(cj/executable-find-or-warn cj/keep-python "Google Keep bridge" 'google-keep-config)
+
+(provide 'google-keep-config)
+;;; google-keep-config.el ends here
diff --git a/modules/help-config.el b/modules/help-config.el
index df27cbea9..f8431aef2 100644
--- a/modules/help-config.el
+++ b/modules/help-config.el
@@ -105,15 +105,7 @@ Preserves any unsaved changes and checks if the file exists."
:bind
(:map Info-mode-map
("m" . bookmark-set) ;; Rebind 'm' from Info-menu to bookmark-set
- ("M" . Info-menu)) ;; Move Info-menu to 'M' instead
- :init
- ;; Add personal info files BEFORE Info mode initializes
- ;; (let ((personal-info-dir (expand-file-name "assets/info" user-emacs-directory)))
- ;; (when (file-directory-p personal-info-dir)
- ;; (setq Info-directory-list (list personal-info-dir))))
- ;; the above makes the directory the info list. the below adds it to the default list
- ;; (add-to-list 'Info-default-directory-list personal-info-dir)))
- )
+ ("M" . Info-menu))) ;; Move Info-menu to 'M' instead
(provide 'help-config)
;;; help-config.el ends here.
diff --git a/modules/help-utils.el b/modules/help-utils.el
index f9f5d1427..3e31efffe 100644
--- a/modules/help-utils.el
+++ b/modules/help-utils.el
@@ -32,6 +32,10 @@
;;
;;; Code:
+;; Lazily-loaded functions referenced below.
+(declare-function devdocs-go-back "devdocs")
+(declare-function devdocs-go-forward "devdocs")
+
;; ---------------------------------- Devdocs ----------------------------------
(use-package devdocs
diff --git a/modules/httpd-config.el b/modules/httpd-config.el
index c90399425..60baf7e82 100644
--- a/modules/httpd-config.el
+++ b/modules/httpd-config.el
@@ -19,13 +19,13 @@
(use-package simple-httpd
:defer 1
:preface
- (defconst wwwdir (concat user-emacs-directory "www"))
- (defun check-or-create-wwwdir ()
- (unless (file-exists-p wwwdir)
- (make-directory wwwdir)))
- :init (check-or-create-wwwdir)
+ (defconst cj/httpd-wwwdir (concat user-emacs-directory "www"))
+ (defun cj/httpd-check-or-create-wwwdir ()
+ (unless (file-exists-p cj/httpd-wwwdir)
+ (make-directory cj/httpd-wwwdir)))
+ :init (cj/httpd-check-or-create-wwwdir)
:config
- (setq httpd-root wwwdir)
+ (setq httpd-root cj/httpd-wwwdir)
(setq httpd-show-backtrace-when-error t)
(setq httpd-serve-files t))
diff --git a/modules/jumper.el b/modules/jumper.el
index 8941d5087..3dc00aa18 100644
--- a/modules/jumper.el
+++ b/modules/jumper.el
@@ -106,20 +106,30 @@ Note that using M-SPC will override the default binding to just-one-space.")
(line-number-at-pos)
(current-column)))
+(defun jumper--with-marker-at (index fn)
+ "Call FN with point at the marker stored for register INDEX.
+Resolve register INDEX's marker; when it is a live marker, run FN in that
+marker's buffer with point at the marker (within `save-current-buffer' and
+`save-excursion') and return FN's value. Return nil when INDEX has no valid
+marker."
+ (let* ((reg (aref jumper--registers index))
+ (marker (get-register reg)))
+ (when (and marker (markerp marker)
+ (buffer-live-p (marker-buffer marker)))
+ (save-current-buffer
+ (set-buffer (marker-buffer marker))
+ (save-excursion
+ (goto-char marker)
+ (funcall fn))))))
+
(defun jumper--location-exists-p ()
"Check if current location is already stored."
(let ((key (jumper--location-key))
- (found nil))
- (dotimes (i jumper--next-index found)
- (let* ((reg (aref jumper--registers i))
- (marker (get-register reg)))
- (when (and marker (markerp marker))
- (save-current-buffer
- (set-buffer (marker-buffer marker))
- (save-excursion
- (goto-char marker)
- (when (string= key (jumper--location-key))
- (setq found t)))))))))
+ (found nil))
+ (dotimes (i jumper--next-index found)
+ (when (jumper--with-marker-at
+ i (lambda () (string= key (jumper--location-key))))
+ (setq found t)))))
(defun jumper--register-available-p ()
"Check if there are registers available."
@@ -127,21 +137,39 @@ Note that using M-SPC will override the default binding to just-one-space.")
(defun jumper--format-location (index)
"Format location at INDEX for display."
- (let* ((reg (aref jumper--registers index))
- (marker (get-register reg)))
- (when (and marker (markerp marker))
- (save-current-buffer
- (set-buffer (marker-buffer marker))
- (save-excursion
- (goto-char marker)
- (format "[%d] %s:%d - %s"
- index
- (buffer-name)
- (line-number-at-pos)
- (buffer-substring-no-properties
- (line-beginning-position)
- (min (+ (line-beginning-position) 40)
- (line-end-position)))))))))
+ (jumper--with-marker-at
+ index
+ (lambda ()
+ (format "[%d] %s:%d - %s"
+ index
+ (buffer-name)
+ (line-number-at-pos)
+ (buffer-substring-no-properties
+ (line-beginning-position)
+ (min (+ (line-beginning-position) 40)
+ (line-end-position)))))))
+
+(defun jumper--location-candidates ()
+ "Return an alist of (DISPLAY . INDEX) for all stored locations.
+Indices whose marker is no longer valid are skipped (their
+`jumper--format-location' returns nil)."
+ (cl-loop for i from 0 below jumper--next-index
+ for fmt = (jumper--format-location i)
+ when fmt collect (cons fmt i)))
+
+(defun jumper--first-free-register ()
+ "Return the lowest register char in 0..N-1 not held by a live slot.
+N is `jumper-max-locations'. Only the live slice (indices 0 through
+`jumper--next-index' minus 1) is consulted, so a char freed by a removal is
+reused on the next store instead of colliding with a surviving slot's
+register and silently overwriting its marker."
+ (let ((used (make-hash-table :test 'eql)))
+ (dotimes (i jumper--next-index)
+ (let ((r (aref jumper--registers i)))
+ (when r (puthash r t used))))
+ (cl-loop for c from ?0 below (+ ?0 jumper-max-locations)
+ unless (gethash c used)
+ return c)))
(defun jumper--do-store-location ()
"Store current location in the next free register.
@@ -152,7 +180,7 @@ Returns: \\='already-exists if location is already stored,
((jumper--location-exists-p) 'already-exists)
((not (jumper--register-available-p)) 'no-space)
(t
- (let ((reg (+ ?0 jumper--next-index)))
+ (let ((reg (jumper--first-free-register)))
(point-to-register reg)
(aset jumper--registers jumper--next-index reg)
(setq jumper--next-index (1+ jumper--next-index))
@@ -177,7 +205,13 @@ Returns: \\='no-locations if no locations stored,
;; Toggle behavior when target-idx is nil and only 1 location
((and (null target-idx) (= jumper--next-index 1))
(if (jumper--location-exists-p)
- 'already-there
+ ;; Already at the only location: toggle back to where we came from
+ ;; when a last-location is recorded, otherwise report no movement.
+ (if (get-register jumper--last-location-register)
+ (progn
+ (jump-to-register jumper--last-location-register)
+ 'jumped-back)
+ 'already-there)
(let ((reg (aref jumper--registers 0)))
(point-to-register jumper--last-location-register)
(jump-to-register reg)
@@ -204,13 +238,12 @@ Returns: \\='no-locations if no locations stored,
((= jumper--next-index 1)
(pcase (jumper--do-jump-to-location nil)
('already-there (message "You're already at the stored location"))
+ ('jumped-back (message "Jumped back to previous location"))
('jumped (message "Jumped to location"))))
;; Multiple locations - prompt user
(t
(let* ((locations
- (cl-loop for i from 0 below jumper--next-index
- for fmt = (jumper--format-location i)
- when fmt collect (cons fmt i)))
+ (jumper--location-candidates))
;; Add last location if available
(last-pos (get-register jumper--last-location-register))
(locations (if last-pos
@@ -222,13 +255,16 @@ Returns: \\='no-locations if no locations stored,
(message "Jumped to location")))))
(defun jumper--reorder-registers (removed-idx)
- "Reorder registers after removing the one at REMOVED-IDX."
- (when (< removed-idx (1- jumper--next-index))
- ;; Shift all higher registers down
- (cl-loop for i from removed-idx below (1- jumper--next-index)
- do (let ((next-reg (aref jumper--registers (1+ i))))
- (aset jumper--registers i next-reg))))
- (setq jumper--next-index (1- jumper--next-index)))
+ "Reorder registers after removing the one at REMOVED-IDX.
+Shift the higher registers down and clear the freed register so its marker
+no longer pins its buffer."
+ (let ((freed (aref jumper--registers removed-idx)))
+ (when (< removed-idx (1- jumper--next-index))
+ ;; Shift all higher registers down
+ (cl-loop for i from removed-idx below (1- jumper--next-index)
+ do (aset jumper--registers i (aref jumper--registers (1+ i)))))
+ (setq jumper--next-index (1- jumper--next-index))
+ (when freed (set-register freed nil))))
(defun jumper--do-remove-location (index)
"Remove location at INDEX.
@@ -248,9 +284,7 @@ Returns: \\='no-locations if no locations stored,
(if (= jumper--next-index 0)
(message "No locations stored")
(let* ((locations
- (cl-loop for i from 0 below jumper--next-index
- for fmt = (jumper--format-location i)
- when fmt collect (cons fmt i)))
+ (jumper--location-candidates))
(locations (cons (cons "Cancel" -1) locations))
(choice (completing-read "Remove location: " locations nil t))
(idx (cdr (assoc choice locations))))
@@ -269,16 +303,12 @@ Returns: \\='no-locations if no locations stored,
(interactive)
(keymap-global-set jumper-prefix-key jumper-map))
-;; Call jumper-setup-keys when the package is loaded
-(jumper-setup-keys)
-
-;; which-key integration
-(with-eval-after-load 'which-key
- (which-key-add-key-based-replacements
- "M-SPC" "jumper menu"
- "M-SPC SPC" "store location"
- "M-SPC j" "jump to location"
- "M-SPC d" "remove location"))
+;; Jumper's M-SPC prefix was removed 2026-06-23 so M-SPC could go to
+;; `cj/ai-term-next'. A cleverer home for jumper (numbers or F-keys) is
+;; pending review; until then its commands are reachable via M-x
+;; (jumper-store-location / jumper-jump-to-location / jumper-remove-location).
+;; To re-home: set `jumper-prefix-key' to the new prefix and call
+;; `jumper-setup-keys' (and restore the which-key labels for that prefix).
(provide 'jumper)
;;; jumper.el ends here.
diff --git a/modules/keybindings.el b/modules/keybindings.el
index db4800876..b61c3f2b3 100644
--- a/modules/keybindings.el
+++ b/modules/keybindings.el
@@ -35,6 +35,10 @@
(defvar-keymap cj/custom-keymap
:doc "User custom prefix keymap base for nested keymaps.")
(keymap-global-set "C-;" cj/custom-keymap)
+;; C-; is GUI-only; terminals can't encode Control-semicolon. Mirror the same
+;; keymap under C-c ; (the standard user prefix, always TTY-encodable) so the
+;; whole command family works in a terminal frame with no leaf-key relearning.
+(keymap-global-set "C-c ;" cj/custom-keymap)
;; ------------------------ Custom Keymap Registration -------------------------
diff --git a/modules/latex-config.el b/modules/latex-config.el
index 0db21f2f2..f2a586704 100644
--- a/modules/latex-config.el
+++ b/modules/latex-config.el
@@ -63,7 +63,10 @@ single entry."
:ensure auctex
:defer t
:hook
- (TeX-mode-hook . (lambda () (setq TeX-command-default "latexmk"))) ; use latexmk by default
+ ;; Name the mode, not the hook: use-package appends "-hook" to any symbol not
+ ;; ending in "-mode", so `TeX-mode' becomes `TeX-mode-hook' while the literal
+ ;; `TeX-mode-hook' would expand to the unbound `TeX-mode-hook-hook'.
+ (TeX-mode . (lambda () (setq TeX-command-default "latexmk"))) ; use latexmk by default
(LaTeX-mode . (lambda () (TeX-fold-mode 1))) ; automatically activate TeX-fold-mode.
(LaTeX-mode . flyspell-mode) ; turn on flyspell-mode by default
(LaTeX-mode . TeX-PDF-mode)
@@ -78,7 +81,9 @@ single entry."
(setq-default TeX-master t)) ; Assume the file is the master file itself
(use-package auctex-latexmk
- :defer t
+ ;; Load with AUCTeX, not deferred: `:defer t' has no autoload trigger here, so
+ ;; `auctex-latexmk-setup' never runs and "latexmk" never joins TeX-command-list.
+ :after tex
:config
(auctex-latexmk-setup)
(setq auctex-latexmk-inherit-TeX-PDF-mode t))
diff --git a/modules/ledger-config.el b/modules/ledger-config.el
index c268fa368..018601043 100644
--- a/modules/ledger-config.el
+++ b/modules/ledger-config.el
@@ -2,6 +2,24 @@
;; author Craig Jennings <c@cjennings.net>
;;; Commentary:
+;; Editing support for ledger-format plain-text accounting files: ledger-mode,
+;; flycheck linting, company completion, clean-on-save, and a small report set.
+;; The reports and reconcile shell out to the `ledger' CLI; a load-time check
+;; warns when it is missing rather than letting a report fail cryptically.
+
+;;; Code:
+
+;; ------------------------------- Declarations --------------------------------
+
+(declare-function ledger-mode-clean-buffer "ledger-mode")
+(declare-function cj/executable-find-or-warn "system-lib")
+(defvar ledger-mode-map)
+(defvar company-backends)
+
+(defcustom cj/ledger-clean-on-save t
+ "When non-nil, tidy a ledger buffer with `ledger-mode-clean-buffer' before save."
+ :type 'boolean
+ :group 'ledger)
;; -------------------------------- Ledger Mode --------------------------------
;; edit files in ledger format
@@ -11,35 +29,38 @@
"\\.ledger\\'"
"\\.journal\\'")
:preface
- (defun cj/ledger-save ()
- "Automatically clean the ledger buffer at each save."
- (interactive)
- (save-excursion
- (when (buffer-modified-p)
- (with-demoted-errors (ledger-mode-clean-buffer))
- (save-buffer))))
- :bind
- (:map ledger-mode-map
- ("C-x C-s" . cj/ledger-save))
+ (defun cj/ledger--clean-before-save ()
+ "Tidy the ledger buffer before save when `cj/ledger-clean-on-save' is set.
+Errors are demoted so a malformed buffer still saves."
+ (when cj/ledger-clean-on-save
+ (with-demoted-errors "Error cleaning ledger buffer: %S"
+ (ledger-mode-clean-buffer))))
+ (defun cj/ledger--enable-clean-on-save ()
+ "Install the clean-on-save hook buffer-locally so it fires on every save path."
+ (add-hook 'before-save-hook #'cj/ledger--clean-before-save nil t))
+ :hook (ledger-mode . cj/ledger--enable-clean-on-save)
:custom
(ledger-clear-whole-transactions t)
(ledger-reconcile-default-commodity "$")
(ledger-report-use-header-line nil)
+ (ledger-highlight-xact-under-point t)
(ledger-reports
'(("bal" "%(binary) --strict -f %(ledger-file) bal")
("bal this month" "%(binary) --strict -f %(ledger-file) bal -p %(month) -S amount")
("bal this year" "%(binary) --strict -f %(ledger-file) bal -p 'this year'")
("net worth" "%(binary) --strict -f %(ledger-file) bal Assets Liabilities")
- ("account" "%(binary) --strict -f %(ledger-file) reg %(account)"))))
+ ("account" "%(binary) --strict -f %(ledger-file) reg %(account)")))
+ :config
+ (cj/executable-find-or-warn "ledger" 'ledger-mode))
;; ------------------------------ Flycheck Ledger ------------------------------
-;; syntax and unbalanced transaction linting
+;; syntax and unbalanced-transaction linting
(use-package flycheck-ledger
:after ledger-mode)
;; ------------------------------- Company Ledger ------------------------------
-;; autocompletion for ledger
+;; account/payee autocompletion for ledger
(use-package company-ledger
:after (company ledger-mode)
diff --git a/modules/local-repository.el b/modules/local-repository.el
index b97b74f41..6376d9f73 100644
--- a/modules/local-repository.el
+++ b/modules/local-repository.el
@@ -25,23 +25,33 @@
;; ------------------------------- Customizations ------------------------------
+(defgroup localrepo nil
+ "Local last-known-good package repository."
+ :group 'package)
+
(defcustom localrepo-repository-id "localrepo"
"The name used to identify the local repository internally.
-Used for the package-archive and package-archive-priorities lists.")
+Used for the package-archive and package-archive-priorities lists."
+ :type 'string
+ :group 'localrepo)
(defcustom localrepo-repository-priority 100
"The value for the local repository in the package-archive-priority list.
A higher value means higher priority. If you want your local packages to be
-preferred, this must be a higher number than any other repositories.")
+preferred, this must be a higher number than any other repositories."
+ :type 'integer
+ :group 'localrepo)
(defcustom localrepo-repository-location
(concat user-emacs-directory "/.localrepo")
"The location of the local repository.
It's a good idea to keep this with the rest of your configuration files and
-keep them in source control.")
+keep them in source control."
+ :type 'directory
+ :group 'localrepo)
(defun cj/update-localrepo-repository ()
"Update the local repository with currently installed packages."
diff --git a/modules/mail-config.el b/modules/mail-config.el
index dfc0c4e0c..1d8a98c97 100644
--- a/modules/mail-config.el
+++ b/modules/mail-config.el
@@ -50,6 +50,31 @@
(declare-function mu4e-message-field "mu4e-message")
+;; ----------------------------- Declarations ----------------------------------
+;; mu4e/org-msg load lazily, so the byte-compiler can't see these package
+;; functions and variables when this module is compiled standalone. Declare
+;; them to silence free-variable / undefined-function warnings without forcing
+;; an eager require (which would defeat lazy loading). The cj/... entries are
+;; forward references: defined later in this file's `:config' block, or in
+;; mu4e-org-contacts-integration (required at load time inside that block).
+
+(declare-function mu4e-headers-mark-for-each-if "mu4e-mark")
+(declare-function mu4e-search "mu4e-search")
+(declare-function mu4e-view-refresh "mu4e-view")
+(declare-function message-add-header "message")
+(declare-function org-msg-edit-mode "org-msg")
+(declare-function no-auto-fill "mail-config")
+(declare-function cj/disable-company-in-mu4e-compose "mail-config")
+(declare-function cj/disable-ispell-in-email-headers "mail-config")
+(declare-function cj/activate-mu4e-org-contacts-integration
+ "mu4e-org-contacts-integration")
+
+;; Package variables assigned in the lazy `:config' blocks below.
+(defvar mu4e-compose-keep-self-cc)
+(defvar mu4e-root-maildir)
+(defvar mu4e-show-images)
+(defvar org-msg-extra-css)
+
;; Refile (archive) target dispatch. A per-context `mu4e-refile-folder' string
;; is unsafe: mu4e context :vars are sticky, so a value set when one context is
;; active leaks into a later context that doesn't set its own -- archiving one
@@ -161,6 +186,12 @@ Prompts user for the action when executing."
(display-buffer-reuse-window display-buffer-same-window)
(inhibit-same-window . nil)))
+;; Keep global font-lock out of the mu4e buffers. mu4e paints header lines, the
+;; main menu, and view headers with manual `face' text properties; global
+;; font-lock strips them (the same failure the dashboard hit), leaving the
+;; buffers unthemed. Excluding these modes keeps mu4e's faces.
+(cj/exclude-from-global-font-lock 'mu4e-headers-mode 'mu4e-main-mode 'mu4e-view-mode)
+
(use-package mu4e
:ensure nil ;; mu4e gets installed by installing 'mu' via the system package manager
:load-path "/usr/share/emacs/site-lisp/mu4e/"
@@ -191,12 +222,16 @@ Prompts user for the action when executing."
;; (setq mu4e-compose-format-flowed t) ;; plain text mails must flow correctly for recipients
(setq mu4e-compose-keep-self-cc t) ;; keep me in the cc list
- (setq mu4e-compose-signature-auto-include nil) ;; don't include signature by default
+ (with-suppressed-warnings ((obsolete mu4e-compose-signature-auto-include)
+ (free-vars mu4e-compose-signature-auto-include))
+ (setq mu4e-compose-signature-auto-include nil)) ;; don't include signature by default
(setq mu4e-confirm-quit nil) ;; don't ask when quitting
(setq mu4e-context-policy 'pick-first) ;; start with the first (default) context
(setq mu4e-headers-auto-update nil) ;; updating headers buffer on email is too jarring
(setq mu4e-root-maildir mail-dir) ;; root directory for all email accounts
- (setq mu4e-maildir mail-dir) ;; same as above (for newer mu4e)
+ (with-suppressed-warnings ((obsolete mu4e-maildir)
+ (free-vars mu4e-maildir))
+ (setq mu4e-maildir mail-dir)) ;; same as above (for newer mu4e)
(setq mu4e-sent-messages-behavior 'delete) ;; don't save to "Sent", IMAP does this already
(setq mu4e-show-images t) ;; show embedded images
;; (setq mu4e-update-interval 600) ;; check for new mail every 10 minutes (600 seconds)
@@ -208,12 +243,16 @@ Prompts user for the action when executing."
;; This will be automatically disabled when org-msg is active
(setq mu4e-compose-format-flowed t)
- (setq mu4e-html2text-command 'mu4e-shr2text) ;; email conversion to html via shr2text
+ (with-suppressed-warnings ((obsolete mu4e-html2text-command)
+ (free-vars mu4e-html2text-command))
+ (setq mu4e-html2text-command 'mu4e-shr2text)) ;; email conversion to html via shr2text
(setq mu4e-mu-binary (executable-find "mu"))
(setq mu4e-get-mail-command (cj/mail--mbsync-command)) ;; command to sync mail
- (setq mu4e-user-mail-address-list '("c@cjennings.net"
- "craigmartinjennings@gmail.com"
- "craig.jennings@deepsat.com"))
+ (with-suppressed-warnings ((obsolete mu4e-user-mail-address-list)
+ (free-vars mu4e-user-mail-address-list))
+ (setq mu4e-user-mail-address-list '("c@cjennings.net"
+ "craigmartinjennings@gmail.com"
+ "craig.jennings@deepsat.com")))
(setq mu4e-index-update-error-warning nil) ;; don't warn me about spurious sync issues
;; ------------------------------ Mu4e Contexts ------------------------------
@@ -289,7 +328,7 @@ Prompts user for the action when executing."
:key ?d)))
(defun no-auto-fill ()
- "Turn off \'auto-fill-mode\'."
+ "Turn off `auto-fill-mode'."
(auto-fill-mode -1))
(add-hook 'mu4e-compose-mode-hook #'no-auto-fill)
@@ -311,19 +350,23 @@ Prompts user for the action when executing."
;; also see org-msg below
;; Prefer HTML over plain text when both are available
- (setq mu4e-view-prefer-html t)
+ (with-suppressed-warnings ((obsolete mu4e-view-prefer-html)
+ (free-vars mu4e-view-prefer-html))
+ (setq mu4e-view-prefer-html t))
;; Use a better HTML renderer with more control
- (setq mu4e-html2text-command
- (cond
- ;; Best option: pandoc (if available)
- ((executable-find "pandoc")
- "pandoc -f html -t plain --reference-links")
- ;; Good option: w3m (better tables/formatting)
- ((executable-find "w3m")
- "w3m -dump -T text/html -cols 72 -o display_link_number=true")
- ;; Fallback: built-in shr
- (t 'mu4e-shr2text)))
+ (with-suppressed-warnings ((obsolete mu4e-html2text-command)
+ (free-vars mu4e-html2text-command))
+ (setq mu4e-html2text-command
+ (cond
+ ;; Best option: pandoc (if available)
+ ((executable-find "pandoc")
+ "pandoc -f html -t plain --reference-links")
+ ;; Good option: w3m (better tables/formatting)
+ ((executable-find "w3m")
+ "w3m -dump -T text/html -cols 72 -o display_link_number=true")
+ ;; Fallback: built-in shr
+ (t 'mu4e-shr2text))))
;; Configure shr (built-in HTML renderer) for better display
(setq shr-use-colors nil) ; Don't use colors in terminal
@@ -333,8 +376,10 @@ Prompts user for the action when executing."
(setq shr-bullet "• ") ; Nice bullet points
;; Block remote images by default (privacy/security)
- (setq mu4e-view-show-images t)
- (setq mu4e-view-image-max-width 800)
+ (with-suppressed-warnings ((obsolete mu4e-view-show-images mu4e-view-image-max-width)
+ (free-vars mu4e-view-show-images mu4e-view-image-max-width))
+ (setq mu4e-view-show-images t)
+ (setq mu4e-view-image-max-width 800))
;; ------------------------------- View Actions ------------------------------
;; define view and article menus
@@ -411,6 +456,34 @@ Prompts user for the action when executing."
(cj/activate-mu4e-org-contacts-integration)) ;; end use-package mu4e
+;; ----------------------- Account Navigation Keymaps --------------------------
+;; The C-; e c/d/g submaps jump to each account's inbox views. Built from one
+;; template so the maildir prefix is the only per-account difference.
+
+;; eval-and-compile so the builder is defined when org-msg's :preface (below)
+;; calls it during byte-compilation, not only at load.
+(eval-and-compile
+ (defun cj/--mail-account-search-queries (account)
+ "Return an alist of (KEY . QUERY) mu4e searches for ACCOUNT's inbox.
+ACCOUNT is the maildir account name (\"cmail\", \"dmail\", \"gmail\"). The four
+entries scope inbox / unread / flagged / large searches to that account's
+INBOX maildir."
+ (let ((base (format "maildir:/%s/INBOX" account)))
+ (list (cons "i" base)
+ (cons "u" (concat base " AND flag:unread AND NOT flag:trashed"))
+ (cons "s" (concat base " AND flag:flagged"))
+ (cons "l" (concat base " AND size:5M..999M")))))
+
+ (defun cj/--mail-make-account-map (account)
+ "Build a mu4e navigation keymap for ACCOUNT (a maildir account name).
+Keys i/u/s/l run the inbox/unread/flagged/large searches from
+`cj/--mail-account-search-queries', each scoped to ACCOUNT."
+ (let ((map (make-sparse-keymap)))
+ (dolist (entry (cj/--mail-account-search-queries account) map)
+ (let ((query (cdr entry)))
+ (keymap-set map (car entry)
+ (lambda () (interactive) (mu4e-search query))))))))
+
;; ---------------------------------- Org-Msg ----------------------------------
;; user composes org mode; recipient receives html
@@ -419,24 +492,12 @@ Prompts user for the action when executing."
:defer 1
:after (org mu4e)
:preface
- (defvar-keymap cj/mail-cmail-map
- :doc "cmail account navigation"
- "i" (lambda () (interactive) (mu4e-search "maildir:/cmail/INBOX"))
- "u" (lambda () (interactive) (mu4e-search "maildir:/cmail/INBOX AND flag:unread AND NOT flag:trashed"))
- "s" (lambda () (interactive) (mu4e-search "maildir:/cmail/INBOX AND flag:flagged"))
- "l" (lambda () (interactive) (mu4e-search "maildir:/cmail/INBOX AND size:5M..999M")))
- (defvar-keymap cj/mail-dmail-map
- :doc "deepsat account navigation"
- "i" (lambda () (interactive) (mu4e-search "maildir:/dmail/INBOX"))
- "u" (lambda () (interactive) (mu4e-search "maildir:/dmail/INBOX AND flag:unread AND NOT flag:trashed"))
- "s" (lambda () (interactive) (mu4e-search "maildir:/dmail/INBOX AND flag:flagged"))
- "l" (lambda () (interactive) (mu4e-search "maildir:/dmail/INBOX AND size:5M..999M")))
- (defvar-keymap cj/mail-gmail-map
- :doc "gmail account navigation"
- "i" (lambda () (interactive) (mu4e-search "maildir:/gmail/INBOX"))
- "u" (lambda () (interactive) (mu4e-search "maildir:/gmail/INBOX AND flag:unread AND NOT flag:trashed"))
- "s" (lambda () (interactive) (mu4e-search "maildir:/gmail/INBOX AND flag:flagged"))
- "l" (lambda () (interactive) (mu4e-search "maildir:/gmail/INBOX AND size:5M..999M")))
+ (defvar cj/mail-cmail-map (cj/--mail-make-account-map "cmail")
+ "cmail account navigation.")
+ (defvar cj/mail-dmail-map (cj/--mail-make-account-map "dmail")
+ "deepsat account navigation.")
+ (defvar cj/mail-gmail-map (cj/--mail-make-account-map "gmail")
+ "gmail account navigation.")
(defvar-keymap cj/email-map
:doc "Email operations and account navigation"
"A" #'org-msg-attach-attach
diff --git a/modules/markdown-config.el b/modules/markdown-config.el
index 16935425d..424c09cc8 100644
--- a/modules/markdown-config.el
+++ b/modules/markdown-config.el
@@ -20,14 +20,13 @@
:mode (("README\\.md\\'" . gfm-mode)
("\\.md\\'" . markdown-mode)
("\\.markdown\\'" . markdown-mode))
- :bind (:map markdown-mode-map
- ("<f2>" . cj/markdown-preview)) ;; use same key as compile for consistency
:init (setq markdown-command "multimarkdown"))
;; Register markdown as a known org-src-block language so `org-lint'
;; stops warning on `#+begin_src markdown ... #+end_src' and `C-c ''
;; inside such a block opens it in `markdown-mode' instead of falling
;; back to fundamental-mode.
+(defvar org-src-lang-modes)
(with-eval-after-load 'org
(add-to-list 'org-src-lang-modes '("markdown" . markdown)))
@@ -40,6 +39,8 @@
;;;; --------------------- WIP: Markdown-Preview ---------------------
+(declare-function imp--notify-clients "impatient-mode")
+
(defun cj/markdown-preview-server-start ()
"Start the simple-httpd listener that serves the live markdown preview.
Idempotent: re-running while the server is already up is a no-op."
@@ -75,5 +76,12 @@ lives in a separate command."
(buffer-substring-no-properties (point-min) (point-max))))
(current-buffer)))
+;; Bind the preview key after the defun so use-package's `:bind' autoload
+;; stub doesn't collide with this file's own definition of the command
+;; (that collision is the "defined multiple times" byte-compile warning).
+;; Same key as compile, for consistency.
+(with-eval-after-load 'markdown-mode
+ (keymap-set markdown-mode-map "<f2>" #'cj/markdown-preview))
+
(provide 'markdown-config)
;;; markdown-config.el ends here
diff --git a/modules/modeline-config.el b/modules/modeline-config.el
index f6b8ef4eb..61dcb69c6 100644
--- a/modules/modeline-config.el
+++ b/modules/modeline-config.el
@@ -15,7 +15,6 @@
;; No external packages = no buffer issues, no native-comp errors.
;; Features:
-;; - Buffer status (modified, read-only)
;; - Buffer name
;; - Major mode
;; - Version control status
@@ -72,25 +71,29 @@ Example: `my-very-long-name.el' → `my-ver...me.el'"
(concat (substring str 0 half) "..." (substring str (- half))))
str))
+(defun cj/--modeline-click-map (mouse-1 &optional mouse-3)
+ "Return a mode-line `local-map' binding mouse clicks to commands.
+\[mode-line mouse-1] runs MOUSE-1; when MOUSE-3 is non-nil, [mode-line mouse-3]
+runs it too. Shared builder for the clickable modeline segments."
+ (let ((map (make-sparse-keymap)))
+ (define-key map [mode-line mouse-1] mouse-1)
+ (when mouse-3
+ (define-key map [mode-line mouse-3] mouse-3))
+ map))
+
;; -------------------------- Modeline Segments --------------------------------
(defvar-local cj/modeline-buffer-name
- '(:eval (let* ((color (cj/buffer-status-color (cj/buffer-status-state)))
- (name (buffer-name))
+ '(:eval (let* ((name (buffer-name))
(truncated-name (cj/modeline-string-cut-middle name)))
(propertize truncated-name
- 'face `(:foreground ,color)
'mouse-face 'mode-line-highlight
'help-echo (concat
name "\n"
(or (buffer-file-name)
(format "No file. Directory: %s" default-directory)))
- 'local-map (let ((map (make-sparse-keymap)))
- (define-key map [mode-line mouse-1] 'previous-buffer)
- (define-key map [mode-line mouse-3] 'next-buffer)
- map))))
- "Buffer name colored by modification and read-only status.
-White = unmodified, Green = modified, Red = read-only, Gold = overwrite.
+ 'local-map (cj/--modeline-click-map 'previous-buffer 'next-buffer))))
+ "Buffer name in the mode line.
Truncates in narrow windows. Click to switch buffers.")
(defvar-local cj/modeline-position
@@ -199,10 +202,7 @@ break it. Caching nil degrades to \"no VC info\" instead."
'face face
'mouse-face 'mode-line-highlight
'help-echo (format "Branch: %s\nState: %s\nmouse-1: vc-diff\nmouse-3: vc-root-diff" branch state)
- 'local-map (let ((map (make-sparse-keymap)))
- (define-key map [mode-line mouse-1] 'vc-diff)
- (define-key map [mode-line mouse-3] 'vc-root-diff)
- map))))))
+ 'local-map (cj/--modeline-click-map 'vc-diff 'vc-root-diff))))))
(defvar-local cj/modeline-vc-branch
'(:eval (when (mode-line-window-selected-p) ; Only show in active window
@@ -219,9 +219,7 @@ Click to show diffs with `vc-diff' or `vc-root-diff'.")
'help-echo (if-let* ((parent (get mode-sym 'derived-mode-parent)))
(format "Major mode: %s\nDerived from: %s\nmouse-1: describe-mode" mode-sym parent)
(format "Major mode: %s\nmouse-1: describe-mode" mode-sym))
- 'local-map (let ((map (make-sparse-keymap)))
- (define-key map [mode-line mouse-1] 'describe-mode)
- map))))
+ 'local-map (cj/--modeline-click-map 'describe-mode))))
"Major mode name only (no minor modes).
Click to show help with `describe-mode'.")
diff --git a/modules/mousetrap-mode.el b/modules/mousetrap-mode.el
index 4444716ce..3817e0081 100644
--- a/modules/mousetrap-mode.el
+++ b/modules/mousetrap-mode.el
@@ -67,7 +67,8 @@ Categories can be combined in profiles to allow specific interaction patterns.")
"Mouse interaction profiles for different use cases.
Each profile specifies which event categories are allowed.
-Available categories: primary-click, secondary-click, drags, multi-clicks, scroll.
+Available categories: primary-click, secondary-click, drags,
+multi-clicks, scroll.
Profiles:
- disabled: Block all mouse events
@@ -88,7 +89,7 @@ Modes not listed here will use `mouse-trap-default-profile'.
When checking, the mode hierarchy is respected via `derived-mode-p'.")
(defvar mouse-trap-default-profile 'disabled
- "Default profile to use when current major mode is not in `mouse-trap-mode-profiles'.")
+ "Default profile when the major mode is not in `mouse-trap-mode-profiles'.")
;;; Keymap Builder
@@ -144,30 +145,34 @@ the mode is toggled, allowing dynamic behavior without reloading config."
(push (cons cache-key map) mouse-trap--keymap-cache)
map))))
+(defun mouse-trap--bind-events-to-ignore (spec prefixes map)
+ "Bind every event in SPEC, across every PREFIXES variant, to `ignore' in MAP.
+SPEC is one category's event description: wheel events under \\='wheel, or
+click/drag events as \\='types x \\='buttons. Used to disable a category that
+the active profile disallows."
+ (cond
+ ;; Scroll events (wheel)
+ ((alist-get 'wheel spec)
+ (dolist (evt (alist-get 'wheel spec))
+ (dolist (pref prefixes)
+ (define-key map (kbd (format "<%s%s>" pref evt)) #'ignore))))
+
+ ;; Click/drag events (types + buttons)
+ ((and (alist-get 'types spec) (alist-get 'buttons spec))
+ (dolist (type (alist-get 'types spec))
+ (dolist (button (alist-get 'buttons spec))
+ (dolist (pref prefixes)
+ (define-key map (kbd (format "<%s%s-%d>" pref type button)) #'ignore)))))))
+
(defun mouse-trap--build-keymap-1 (allowed-categories)
"Build a fresh keymap binding events not in ALLOWED-CATEGORIES to `ignore'."
(let ((prefixes '("" "C-" "M-" "S-" "C-M-" "C-S-" "M-S-" "C-M-S-"))
(map (make-sparse-keymap)))
-
- ;; For each event category, disable it if not in allowed list
(dolist (category-entry mouse-trap--event-categories)
(let ((category (car category-entry))
(spec (cdr category-entry)))
(unless (memq category allowed-categories)
- ;; This category is NOT allowed - bind its events to ignore
- (cond
- ;; Scroll events (wheel)
- ((alist-get 'wheel spec)
- (dolist (evt (alist-get 'wheel spec))
- (dolist (pref prefixes)
- (define-key map (kbd (format "<%s%s>" pref evt)) #'ignore))))
-
- ;; Click/drag events (types + buttons)
- ((and (alist-get 'types spec) (alist-get 'buttons spec))
- (dolist (type (alist-get 'types spec))
- (dolist (button (alist-get 'buttons spec))
- (dolist (pref prefixes)
- (define-key map (kbd (format "<%s%s-%d>" pref type button)) #'ignore)))))))))
+ (mouse-trap--bind-events-to-ignore spec prefixes map))))
map))
;;; Buffer-local keymap via emulation-mode-map-alists
@@ -183,6 +188,11 @@ Used via `emulation-mode-map-alists' so each buffer gets its own keymap.")
;;; Minor Mode Definition
+;; Forward declaration: the minor-mode variable is defined by the
+;; `define-minor-mode' form below, but referenced earlier in the lighter
+;; keymap and lighter-string helpers.
+(defvar mouse-trap-mode)
+
(defvar mouse-trap--lighter-keymap
(let ((map (make-sparse-keymap)))
(define-key map [mode-line mouse-1]
diff --git a/modules/mu4e-org-contacts-integration.el b/modules/mu4e-org-contacts-integration.el
index 6aed3d4cf..daa12701a 100644
--- a/modules/mu4e-org-contacts-integration.el
+++ b/modules/mu4e-org-contacts-integration.el
@@ -32,7 +32,6 @@ This function is designed to work with mu4e's compose buffers."
(re-search-backward "\\(\\`\\|[\n:,]\\)[ \t]*" nil t)
(goto-char (match-end 0))
(point)))
- (initial (buffer-substring-no-properties start end))
(contacts (cj/get-all-contact-emails)))
(when contacts
(list start end
diff --git a/modules/mu4e-org-contacts-setup.el b/modules/mu4e-org-contacts-setup.el
index 034e74574..64e9a611f 100644
--- a/modules/mu4e-org-contacts-setup.el
+++ b/modules/mu4e-org-contacts-setup.el
@@ -7,6 +7,10 @@
;;; Code:
+(defvar mu4e-compose-complete-only-personal)
+(defvar mu4e-compose-complete-only-after)
+(declare-function cj/activate-mu4e-org-contacts-integration "mu4e-org-contacts-integration")
+
;; Load the integration module. Activation only runs when the module loaded
;; cleanly AND mu4e is present; otherwise this file is a no-op so the rest
;; of the config can load without mu4e installed.
diff --git a/modules/music-config.el b/modules/music-config.el
index be836429b..76fff283b 100644
--- a/modules/music-config.el
+++ b/modules/music-config.el
@@ -94,9 +94,47 @@
(require 'subr-x)
(require 'user-constants)
(require 'keybindings) ;; provides cj/custom-keymap
+(require 'cj-window-geometry-lib) ;; cj/preferred-dock-direction (F10 dock side)
(require 'cj-window-toggle-lib) ;; side-window size memory (F10 toggle)
(require 'system-lib) ;; cj/confirm-strong (overwrite confirms)
+;; Declare these foreign package vars special so `let'-binding them below
+;; compiles as a dynamic bind, not a dead lexical local -- otherwise emms /
+;; orderless never see the binding (the lexical-binding foreign-special-var trap).
+(defvar orderless-smart-case)
+(defvar emms-source-playlist-ask-before-overwrite)
+(defvar emms-playlist-buffer-p)
+(defvar emms-playlist-buffer)
+(defvar emms-random-playlist)
+(defvar emms-playlist-selected-marker)
+(defvar emms-source-file-default-directory)
+(defvar emms-player-mpv-parameters)
+(defvar emms-player-mpv-regexp)
+(defvar emms-player-playing-p)
+(defvar emms-player-paused-p)
+(defvar emms-playlist-mode-map)
+(defvar dirvish-mode-map)
+
+;; Foreign functions used lazily after their packages load.
+(declare-function emms-playlist-mode "emms-playlist-mode")
+(declare-function emms-playlist-track-at "emms-playlist-mode")
+(declare-function emms-playlist-mode-kill-track "emms-playlist-mode")
+(declare-function emms-track-name "emms")
+(declare-function emms-track-type "emms")
+(declare-function emms-track-get "emms")
+(declare-function emms-track-simple-description "emms")
+(declare-function emms-playlist-current-selected-track "emms")
+(declare-function emms-playlist-select "emms")
+(declare-function emms-playlist-clear "emms")
+(declare-function emms-playlist-save "emms-source-playlist")
+(declare-function emms-start "emms")
+(declare-function emms-random "emms")
+(declare-function emms-next "emms")
+(declare-function emms-previous "emms")
+(declare-function dired-get-marked-files "dired")
+(declare-function dired-get-file-for-visit "dired")
+(declare-function face-remap-remove-relative "face-remap")
+
;;; Settings (no Customize)
(defvar cj/music-root music-dir
@@ -517,14 +555,38 @@ Intended for use on `emms-player-finished-hook'."
(defvar cj/music-playlist-window-height 0.3
"Default fraction of frame height for the F10 music playlist side window.
-Used until the playlist is resized and toggled off this session; after that,
-the toggled-off height is remembered in `cj/--music-playlist-height'.")
+Used when the playlist docks at the bottom and hasn't been resized and
+toggled off this session; after that, the toggled-off height is remembered
+in `cj/--music-playlist-height'.")
+
+(defvar cj/music-playlist-window-width 0.4
+ "Default fraction of frame width for the F10 music playlist side window.
+Used when the playlist docks as a right-side column (see
+`cj/--music-playlist-side') and hasn't been resized this session; after
+that the toggled-off width is remembered in `cj/--music-playlist-width'.")
(defvar cj/--music-playlist-height nil
- "Last height fraction the playlist side window was toggled off at.
+ "Last height fraction the playlist was toggled off at while docked bottom.
nil means fall back to `cj/music-playlist-window-height'. In-memory only --
resets each Emacs session.")
+(defvar cj/--music-playlist-width nil
+ "Last width fraction the playlist was toggled off at while docked right.
+nil means fall back to `cj/music-playlist-window-width'. In-memory only --
+resets each Emacs session.")
+
+(defun cj/--music-playlist-side ()
+ "Return the side the F10 playlist should dock on: `right' or `bottom'.
+Docks as a right-side column only when a side-by-side split would leave
+both panes at least `cj/window-dock-min-columns' wide (the playlist's
+share is `cj/music-playlist-window-width'); otherwise docks at the bottom.
+See `cj/preferred-dock-direction'."
+ (if (eq (cj/preferred-dock-direction (frame-width)
+ cj/music-playlist-window-width)
+ 'right)
+ 'right
+ 'bottom))
+
(defun cj/music-playlist-toggle ()
"Toggle the EMMS playlist buffer in a bottom side window.
The window opens at `cj/music-playlist-window-height'; if it has been
@@ -535,15 +597,28 @@ resized and toggled off this session, it reopens at that remembered height."
(win (and buffer (get-buffer-window buffer))))
(if win
(progn
- (cj/side-window-capture-size win 'bottom 'cj/--music-playlist-height)
+ ;; Capture the resized size into the var matching the window's
+ ;; actual side, so width and height memories stay independent.
+ ;; Guard the parameter lookup: a dead or non-window WIN (the
+ ;; capture helpers tolerate one) must not error here.
+ (let ((side (if (window-live-p win)
+ (or (window-parameter win 'window-side) 'bottom)
+ 'bottom)))
+ (if (memq side '(left right))
+ (cj/side-window-capture-size win side 'cj/--music-playlist-width)
+ (cj/side-window-capture-size win 'bottom 'cj/--music-playlist-height)))
(delete-window win)
(message "Playlist window closed"))
(progn
(cj/emms--setup)
(setq buffer (cj/music--ensure-playlist-buffer))
- (setq win (cj/side-window-display
- buffer 'bottom 'cj/--music-playlist-height
- cj/music-playlist-window-height))
+ (let* ((side (cj/--music-playlist-side))
+ (right (eq side 'right)))
+ (setq win (cj/side-window-display
+ buffer side
+ (if right 'cj/--music-playlist-width 'cj/--music-playlist-height)
+ (if right cj/music-playlist-window-width
+ cj/music-playlist-window-height))))
(select-window win)
(with-current-buffer buffer
(if (and (fboundp 'emms-playlist-current-selected-track)
@@ -575,26 +650,26 @@ Initializes EMMS if needed."
;;; Dired/Dirvish integration
-(with-eval-after-load 'dirvish
- (defun cj/music-add-dired-selection ()
- "Add selected files/dirs in Dired/Dirvish to the EMMS playlist.
+(defun cj/music-add-dired-selection ()
+ "Add selected files/dirs in Dired/Dirvish to the EMMS playlist.
Dirs added recursively."
- (interactive)
- (unless (derived-mode-p 'dired-mode)
- (user-error "This command must be run in a Dired buffer"))
- (cj/music--ensure-playlist-buffer)
- (let ((files (if (use-region-p)
- (dired-get-marked-files)
- (list (dired-get-file-for-visit)))))
- (when (null files)
- (user-error "No files selected"))
- (dolist (file files)
- (cond
- ((file-directory-p file) (cj/music-add-directory-recursive file))
- ((cj/music--valid-file-p file) (emms-add-file file))
- (t (message "Skipping non-music file: %s" file))))
- (message "Added %d item(s) to playlist" (length files))))
+ (interactive)
+ (unless (derived-mode-p 'dired-mode)
+ (user-error "This command must be run in a Dired buffer"))
+ (cj/music--ensure-playlist-buffer)
+ (let ((files (if (use-region-p)
+ (dired-get-marked-files)
+ (list (dired-get-file-for-visit)))))
+ (when (null files)
+ (user-error "No files selected"))
+ (dolist (file files)
+ (cond
+ ((file-directory-p file) (cj/music-add-directory-recursive file))
+ ((cj/music--valid-file-p file) (emms-add-file file))
+ (t (message "Skipping non-music file: %s" file))))
+ (message "Added %d item(s) to playlist" (length files))))
+(with-eval-after-load 'dirvish
(keymap-set dirvish-mode-map "+" #'cj/music-add-dired-selection))
;;; EMMS setup and keybindings
@@ -636,6 +711,130 @@ Dirs added recursively."
"C-; m z" "random"
"C-; m x" "consume"))
+;;; Playlist display helpers
+;;
+;; Defined at top level (not inside the `emms' use-package `:config') so the
+;; byte-compiler sees them; they touch EMMS only at call time, after load.
+
+(defun cj/music--after-playlist-clear (&rest _)
+ "Forget the associated M3U file after the playlist is cleared."
+ (when-let ((buf (get-buffer cj/music-playlist-buffer-name)))
+ (with-current-buffer buf
+ (setq cj/music-playlist-file nil))))
+
+(defun cj/music--format-duration (seconds)
+ "Convert SECONDS to a \"M:SS\" string."
+ (when (and seconds (numberp seconds) (> seconds 0))
+ (format "%d:%02d" (/ seconds 60) (mod seconds 60))))
+
+(defun cj/music--track-description (track)
+ "Return a human-readable description of TRACK.
+For tagged tracks: \"Artist - Title [M:SS]\".
+For file tracks without tags: filename without path or extension.
+For URL tracks: decoded URL."
+ (let ((type (emms-track-type track))
+ (title (emms-track-get track 'info-title))
+ (artist (emms-track-get track 'info-artist))
+ (duration (emms-track-get track 'info-playing-time))
+ (name (emms-track-name track)))
+ (cond
+ ;; Tagged track with title
+ (title
+ (let ((dur-str (cj/music--format-duration duration))
+ (parts '()))
+ (when artist (push artist parts))
+ (push title parts)
+ (let ((desc (string-join (nreverse parts) " - ")))
+ (if dur-str (format "%s [%s]" desc dur-str) desc))))
+ ;; File without tags — show clean filename
+ ((eq type 'file)
+ (file-name-sans-extension (file-name-nondirectory name)))
+ ;; URL — decode percent-encoded characters
+ ((eq type 'url)
+ (decode-coding-string (url-unhex-string name) 'utf-8))
+ ;; Fallback
+ (t (emms-track-simple-description track)))))
+
+;; Multi-line header overlay
+(defvar-local cj/music--header-overlay nil
+ "Overlay displaying the playlist header.")
+
+(defun cj/music--header-text ()
+ "Build a multi-line header string for the playlist buffer overlay."
+ (let* ((pl-name (if cj/music-playlist-file
+ (file-name-sans-extension
+ (file-name-nondirectory cj/music-playlist-file))
+ "Untitled"))
+ (track-count (count-lines (point-min) (point-max)))
+ (now-playing (cond
+ ((not emms-player-playing-p) "Stopped")
+ (emms-player-paused-p "Paused")
+ (t (let ((track (emms-playlist-current-selected-track)))
+ (if track
+ (cj/music--track-description track)
+ "Playing")))))
+ (mode-indicator
+ (lambda (key label active)
+ (let ((face (if active 'cj/music-mode-on-face 'cj/music-mode-off-face)))
+ (propertize (format "[%s] %s" key label) 'face face)))))
+ (concat
+ (propertize "Playlist" 'face 'cj/music-header-face)
+ (propertize " : " 'face 'cj/music-header-face)
+ (propertize (format "%s (%d)" pl-name track-count) 'face 'cj/music-header-value-face)
+ "\n"
+ (propertize "Current " 'face 'cj/music-header-face)
+ (propertize " : " 'face 'cj/music-header-face)
+ (propertize now-playing 'face 'cj/music-header-value-face)
+ "\n"
+ (propertize "Mode " 'face 'cj/music-header-face)
+ (propertize " : " 'face 'cj/music-header-face)
+ (funcall mode-indicator "r" "repeat" (bound-and-true-p emms-repeat-playlist))
+ " "
+ (funcall mode-indicator "t" "single" (bound-and-true-p emms-repeat-track))
+ " "
+ (funcall mode-indicator "z" "random" (bound-and-true-p emms-random-playlist))
+ " "
+ (funcall mode-indicator "x" "consume" cj/music-consume-mode)
+ "\n"
+ (propertize "Keys " 'face 'cj/music-header-face)
+ (propertize " : " 'face 'cj/music-header-face)
+ (propertize "a:add c:clear L:load S:save SPC:pause <>:skip ↑↓:move C-↑↓:reorder q:dismiss"
+ 'face 'cj/music-keyhint-face)
+ "\n\n")))
+
+(defun cj/music--update-header ()
+ "Insert or update the multi-line header overlay in the playlist buffer."
+ (when-let ((buf (get-buffer cj/music-playlist-buffer-name)))
+ (with-current-buffer buf
+ (unless cj/music--header-overlay
+ (setq cj/music--header-overlay (make-overlay (point-min) (point-min)))
+ (overlay-put cj/music--header-overlay 'priority 100))
+ (move-overlay cj/music--header-overlay (point-min) (point-min))
+ (overlay-put cj/music--header-overlay 'before-string
+ (cj/music--header-text)))))
+
+(defvar-local cj/music--bg-remap-cookie nil
+ "Cookie for the active-window background face remapping.")
+
+(defun cj/music--update-active-bg (&rest _)
+ "Toggle playlist buffer background based on whether its window is selected."
+ (when-let ((buf (get-buffer cj/music-playlist-buffer-name)))
+ (with-current-buffer buf
+ (let ((active (eq buf (window-buffer (selected-window)))))
+ (cond
+ ((and active (not cj/music--bg-remap-cookie))
+ (setq cj/music--bg-remap-cookie
+ (face-remap-add-relative 'default)))
+ ((and (not active) cj/music--bg-remap-cookie)
+ (face-remap-remove-relative cj/music--bg-remap-cookie)
+ (setq cj/music--bg-remap-cookie nil)))))))
+
+(defun cj/music--setup-playlist-display ()
+ "Set up header overlay and focus tracking in the playlist buffer."
+ (setq header-line-format nil)
+ (cj/music--update-header)
+ (add-hook 'window-selection-change-functions #'cj/music--update-active-bg nil t))
+
(use-package emms
:defer t
:init
@@ -660,7 +859,7 @@ Dirs added recursively."
(emms-all)
;; Disable modeline display (keep modeline clean)
- (emms-playing-time-disable-display)
+ (emms-playing-time-display-mode -1)
(emms-mode-line-mode -1)
;; MPV configuration
@@ -674,134 +873,16 @@ Dirs added recursively."
(regexp-opt cj/music-file-extensions)
"\\'\\)"))
- ;; Keep cj/music-playlist-file in sync if playlist is cleared
- (defun cj/music--after-playlist-clear (&rest _)
- (when-let ((buf (get-buffer cj/music-playlist-buffer-name)))
- (with-current-buffer buf
- (setq cj/music-playlist-file nil))))
-
- ;; Ensure we don't stack duplicate advice on reload
+ ;; Keep cj/music-playlist-file in sync if playlist is cleared.
+ ;; Ensure we don't stack duplicate advice on reload.
(advice-remove 'emms-playlist-clear #'cj/music--after-playlist-clear)
(advice-add 'emms-playlist-clear :after #'cj/music--after-playlist-clear)
;;; Playlist display
;; Track description: show "Artist - Title [M:SS]" instead of file paths
- (defun cj/music--format-duration (seconds)
- "Convert SECONDS to a \"M:SS\" string."
- (when (and seconds (numberp seconds) (> seconds 0))
- (format "%d:%02d" (/ seconds 60) (mod seconds 60))))
-
- (defun cj/music--track-description (track)
- "Return a human-readable description of TRACK.
-For tagged tracks: \"Artist - Title [M:SS]\".
-For file tracks without tags: filename without path or extension.
-For URL tracks: decoded URL."
- (let ((type (emms-track-type track))
- (title (emms-track-get track 'info-title))
- (artist (emms-track-get track 'info-artist))
- (duration (emms-track-get track 'info-playing-time))
- (name (emms-track-name track)))
- (cond
- ;; Tagged track with title
- (title
- (let ((dur-str (cj/music--format-duration duration))
- (parts '()))
- (when artist (push artist parts))
- (push title parts)
- (let ((desc (string-join (nreverse parts) " - ")))
- (if dur-str (format "%s [%s]" desc dur-str) desc))))
- ;; File without tags — show clean filename
- ((eq type 'file)
- (file-name-sans-extension (file-name-nondirectory name)))
- ;; URL — decode percent-encoded characters
- ((eq type 'url)
- (decode-coding-string (url-unhex-string name) 'utf-8))
- ;; Fallback
- (t (emms-track-simple-description track)))))
-
(setq emms-track-description-function #'cj/music--track-description)
- ;; Multi-line header overlay
- (defvar-local cj/music--header-overlay nil
- "Overlay displaying the playlist header.")
-
- (defun cj/music--header-text ()
- "Build a multi-line header string for the playlist buffer overlay."
- (let* ((pl-name (if cj/music-playlist-file
- (file-name-sans-extension
- (file-name-nondirectory cj/music-playlist-file))
- "Untitled"))
- (track-count (count-lines (point-min) (point-max)))
- (now-playing (cond
- ((not emms-player-playing-p) "Stopped")
- (emms-player-paused-p "Paused")
- (t (let ((track (emms-playlist-current-selected-track)))
- (if track
- (cj/music--track-description track)
- "Playing")))))
- (mode-indicator
- (lambda (key label active)
- (let ((face (if active 'cj/music-mode-on-face 'cj/music-mode-off-face)))
- (propertize (format "[%s] %s" key label) 'face face)))))
- (concat
- (propertize "Playlist" 'face 'cj/music-header-face)
- (propertize " : " 'face 'cj/music-header-face)
- (propertize (format "%s (%d)" pl-name track-count) 'face 'cj/music-header-value-face)
- "\n"
- (propertize "Current " 'face 'cj/music-header-face)
- (propertize " : " 'face 'cj/music-header-face)
- (propertize now-playing 'face 'cj/music-header-value-face)
- "\n"
- (propertize "Mode " 'face 'cj/music-header-face)
- (propertize " : " 'face 'cj/music-header-face)
- (funcall mode-indicator "r" "repeat" (bound-and-true-p emms-repeat-playlist))
- " "
- (funcall mode-indicator "t" "single" (bound-and-true-p emms-repeat-track))
- " "
- (funcall mode-indicator "z" "random" (bound-and-true-p emms-random-playlist))
- " "
- (funcall mode-indicator "x" "consume" cj/music-consume-mode)
- "\n"
- (propertize "Keys " 'face 'cj/music-header-face)
- (propertize " : " 'face 'cj/music-header-face)
- (propertize "a:add c:clear L:load S:save SPC:pause <>:skip ↑↓:move C-↑↓:reorder q:dismiss"
- 'face 'cj/music-keyhint-face)
- "\n\n")))
-
- (defun cj/music--update-header ()
- "Insert or update the multi-line header overlay in the playlist buffer."
- (when-let ((buf (get-buffer cj/music-playlist-buffer-name)))
- (with-current-buffer buf
- (unless cj/music--header-overlay
- (setq cj/music--header-overlay (make-overlay (point-min) (point-min)))
- (overlay-put cj/music--header-overlay 'priority 100))
- (move-overlay cj/music--header-overlay (point-min) (point-min))
- (overlay-put cj/music--header-overlay 'before-string
- (cj/music--header-text)))))
-
- (defvar-local cj/music--bg-remap-cookie nil
- "Cookie for the active-window background face remapping.")
-
- (defun cj/music--update-active-bg (&rest _)
- "Toggle playlist buffer background based on whether its window is selected."
- (when-let ((buf (get-buffer cj/music-playlist-buffer-name)))
- (with-current-buffer buf
- (let ((active (eq buf (window-buffer (selected-window)))))
- (cond
- ((and active (not cj/music--bg-remap-cookie))
- (setq cj/music--bg-remap-cookie
- (face-remap-add-relative 'default :background "#1d1b19")))
- ((and (not active) cj/music--bg-remap-cookie)
- (face-remap-remove-relative cj/music--bg-remap-cookie)
- (setq cj/music--bg-remap-cookie nil)))))))
-
- (defun cj/music--setup-playlist-display ()
- "Set up header overlay and focus tracking in the playlist buffer."
- (setq header-line-format nil)
- (cj/music--update-header)
- (add-hook 'window-selection-change-functions #'cj/music--update-active-bg nil t))
-
(add-hook 'emms-playlist-mode-hook #'cj/music--setup-playlist-display)
(add-hook 'emms-player-started-hook #'cj/music--record-random-history)
(add-hook 'emms-player-started-hook #'cj/music--update-header)
@@ -853,8 +934,6 @@ For URL tracks: decoded URL."
("S-<down>" . emms-playlist-mode-shift-track-down)
("C-<up>" . emms-playlist-mode-shift-track-up)
("C-<down>" . emms-playlist-mode-shift-track-down)
- ;; Radio
- ("R" . cj/music-create-radio-station)
;; Volume
("+" . emms-volume-raise)
("=" . emms-volume-raise)
@@ -883,5 +962,10 @@ For URL tracks: decoded URL."
(insert content))
(message "Created radio station: %s" (file-name-nondirectory file))))
+;; Bound here rather than in the emms `:bind' so use-package does not emit a
+;; redundant autoload that collides with this same-file definition.
+(with-eval-after-load 'emms
+ (keymap-set emms-playlist-mode-map "R" #'cj/music-create-radio-station))
+
(provide 'music-config)
;;; music-config.el ends here
diff --git a/modules/nerd-icons-config.el b/modules/nerd-icons-config.el
index d3d55b864..e2edb0717 100644
--- a/modules/nerd-icons-config.el
+++ b/modules/nerd-icons-config.el
@@ -1,4 +1,4 @@
-;;; nerd-icons-config.el --- Nerd-icons setup, integrations, and tinting -*- lexical-binding: t; -*-
+;;; nerd-icons-config.el --- Nerd-icons setup and integrations -*- lexical-binding: t; -*-
;; author: Craig Jennings <c@cjennings.net>
;;; Commentary:
@@ -16,51 +16,21 @@
;; - the package itself
;; - completion integration (`nerd-icons-completion')
;; - ibuffer integration (`nerd-icons-ibuffer')
-;; - bulk color tinting of every `nerd-icons-*' color face
;; - dir-icon color advice (so directory glyphs carry a color face like
;; file glyphs do, instead of falling through to the buffer default
;; face)
;;
+;; Icon colors are theme-driven: nerd-icons' 34 `nerd-icons-*' color faces are
+;; owned by the theme (themeable in theme-studio), not overwritten at load time.
+;;
;; Per-feature USE of nerd-icons stays in the feature module that consumes
;; it: `dashboard-icon-type', `dirvish-attributes', and the keyboard-compat
;; terminal-frame icon-blanking advice are not centralized here.
;;; Code:
-;; ----------------------------- Customization ---------------------------------
-
-(defcustom cj/nerd-icons-tint-color "darkgoldenrod"
- "Single foreground color applied to every `nerd-icons-*' color face.
-Set via Customize or by `setq' before this module loads, then call
-`cj/nerd-icons-apply-tint' to re-apply on demand."
- :type 'string
- :group 'cj)
-
-(defconst cj/--nerd-icons-color-faces
- '(nerd-icons-red nerd-icons-lred nerd-icons-dred nerd-icons-red-alt
- nerd-icons-green nerd-icons-lgreen nerd-icons-dgreen
- nerd-icons-yellow nerd-icons-lyellow nerd-icons-dyellow
- nerd-icons-orange nerd-icons-lorange nerd-icons-dorange
- nerd-icons-blue nerd-icons-blue-alt nerd-icons-lblue nerd-icons-dblue
- nerd-icons-cyan nerd-icons-cyan-alt nerd-icons-lcyan nerd-icons-dcyan
- nerd-icons-purple nerd-icons-purple-alt nerd-icons-lpurple nerd-icons-dpurple
- nerd-icons-pink nerd-icons-lpink nerd-icons-dpink
- nerd-icons-maroon nerd-icons-lmaroon nerd-icons-dmaroon
- nerd-icons-silver nerd-icons-lsilver nerd-icons-dsilver)
- "Every color face nerd-icons attaches to glyphs via `:inherit'.")
-
;; ------------------------------- Helpers -------------------------------------
-(defun cj/nerd-icons-apply-tint (&optional color)
- "Set every face in `cj/--nerd-icons-color-faces' to foreground COLOR.
-COLOR defaults to `cj/nerd-icons-tint-color'. Faces that are not yet
-defined (nerd-icons not loaded) are silently skipped."
- (interactive)
- (let ((c (or color cj/nerd-icons-tint-color)))
- (dolist (f cj/--nerd-icons-color-faces)
- (when (facep f)
- (set-face-foreground f c)))))
-
(defun cj/--nerd-icons-color-dir (icon)
"Layer `nerd-icons-yellow' onto ICON's face stack and return ICON.
ICON is the propertized string returned by `nerd-icons-icon-for-dir'.
@@ -87,17 +57,15 @@ every call. The `memq' check skips when the face is already present."
(use-package nerd-icons
:demand t
:config
- (advice-add 'nerd-icons-icon-for-dir :filter-return #'cj/--nerd-icons-color-dir)
- (cj/nerd-icons-apply-tint))
+ (advice-add 'nerd-icons-icon-for-dir :filter-return #'cj/--nerd-icons-color-dir))
;; Safety net: if this module is re-evaluated in a running Emacs where
;; nerd-icons is already loaded, `:config' above won't fire again --
-;; ensure the advice and tint still apply.
+;; ensure the dir advice still applies.
(with-eval-after-load 'nerd-icons
(unless (advice-member-p #'cj/--nerd-icons-color-dir 'nerd-icons-icon-for-dir)
(advice-add 'nerd-icons-icon-for-dir
- :filter-return #'cj/--nerd-icons-color-dir))
- (cj/nerd-icons-apply-tint))
+ :filter-return #'cj/--nerd-icons-color-dir)))
(use-package nerd-icons-completion
:demand t
diff --git a/modules/org-agenda-config-debug.el b/modules/org-agenda-config-debug.el
index a9c713a13..4c1b1dd84 100644
--- a/modules/org-agenda-config-debug.el
+++ b/modules/org-agenda-config-debug.el
@@ -18,6 +18,9 @@
(require 'user-constants)
(require 'system-lib)
+(defvar org-agenda-files)
+(declare-function cj/build-org-agenda-list "org-agenda-config")
+
;; ---------------------------- Debug Functions --------------------------------
;;;###autoload
diff --git a/modules/org-agenda-config.el b/modules/org-agenda-config.el
index 704eaac9a..3234cc929 100644
--- a/modules/org-agenda-config.el
+++ b/modules/org-agenda-config.el
@@ -47,9 +47,10 @@
;; M-f8 - TASK LIST containing all tasks from just the current org-mode buffer.
;;
;; NOTE:
-;; Files that contain information relevant to the agenda will be found in the
-;; following places: the schedule-file, org-roam notes tagged as 'Projects' and
-;; project todo.org files found in project-dir and code-dir.
+;; Files that contain information relevant to the agenda are: the inbox, the
+;; schedule-file, the synced calendars, and the per-project todo.org files found
+;; in immediate subdirectories of projects-dir. (org-roam notes are refile
+;; targets, not agenda sources -- see org-refile-config.el.)
;;; Code:
(require 'user-constants)
@@ -58,7 +59,8 @@
(defcustom cj/org-agenda-window-height 0.75
"Fraction of the selected frame used for the org agenda window."
- :type 'number)
+ :type 'number
+ :group 'org-agenda)
(defun cj/--org-agenda-display-rule ()
"Return the display-buffer rule for the org agenda buffer."
@@ -89,6 +91,12 @@
(setq org-agenda-skip-scheduled-if-done nil)
(setq org-agenda-remove-tags t)
(setq org-agenda-compact-blocks t)
+ ;; Backstop against a non-existent agenda file (e.g. a calendar not yet synced
+ ;; on a fresh machine): skip it silently instead of prompting to create it --
+ ;; the interactive-prompt class that once hung the chime daemon.
+ ;; `cj/--org-agenda-base-files' already filters the list; this catches any path
+ ;; that reaches `org-agenda-files' another way.
+ (setq org-agenda-skip-unavailable-files t)
;; display the agenda from the bottom
(add-to-list 'display-buffer-alist
@@ -177,13 +185,24 @@ Only checks DIRECTORY/*/todo.org — does not recurse deeper."
;; ---------------------------- Rebuild Org Agenda ---------------------------
;; builds the org agenda list from all agenda targets with caching.
-;; agenda targets is the schedule, contacts, project todos,
-;; inbox, and org roam projects.
+;; agenda targets are the inbox, the schedule, the synced calendars,
+;; and the per-project todo.org files under projects-dir.
+(defun cj/--org-agenda-base-files ()
+ "Return the existing base files for the agenda: inbox, schedule, and calendars.
+The single source of the base list shared by the agenda builders and the chime
+initializer, so adding a calendar source is a one-place change. Per-project
+todo.org files are layered on separately. Files that do not exist are dropped
+\(a fresh machine may lack the synced calendars or the inbox) so org-agenda
+never prompts to create them -- the interactive-prompt class that once hung the
+chime daemon; `org-agenda-skip-unavailable-files' is the backstop."
+ (seq-filter #'file-exists-p
+ (list inbox-file schedule-file gcal-file pcal-file dcal-file)))
+
(defun cj/--org-agenda-scan-files ()
"Scan disk for the agenda files list. Pure-ish: no caching, no logging.
Returns the list to assign to `org-agenda-files'. Slow -- walks
`projects-dir' for per-project todo.org files."
- (let ((files (list inbox-file schedule-file gcal-file pcal-file dcal-file)))
+ (let ((files (cj/--org-agenda-base-files)))
;; cj/add-files-to-org-agenda-files-list mutates org-agenda-files; let-bind
;; it for the duration of the helper, then return whatever it produced.
(let ((org-agenda-files files))
@@ -236,8 +255,8 @@ Bypasses cache and scans directories from scratch."
(defun cj/todo-list-all-agenda-files ()
"Displays an \\='org-agenda\\=' todo list.
-The contents of the agenda will be built from org-project-files and org-roam
-files that have project in their filetag."
+The contents of the agenda are built from the base files (inbox, schedule, and
+the synced calendars) plus the per-project todo.org files under projects-dir."
(interactive)
(cj/build-org-agenda-list)
(org-agenda "a" "t"))
@@ -262,9 +281,7 @@ scoped to that project's todo.org plus calendars, schedule, and inbox."
(chosen (completing-read "Show agenda for project: " project-names nil t))
(todo-file (expand-file-name "todo.org"
(expand-file-name chosen projects-dir)))
- (org-agenda-files (list todo-file
- inbox-file schedule-file
- gcal-file pcal-file dcal-file)))
+ (org-agenda-files (cons todo-file (cj/--org-agenda-base-files))))
(org-agenda "a" "d")))
(global-set-key (kbd "C-<f8>") #'cj/todo-list-single-project)
@@ -380,8 +397,7 @@ This uses all org-agenda targets and presents three sections:
- Today's schedule, including habits with consistency graphs
- All priority B and C unscheduled/undeadlined tasks
The agenda is rebuilt from all sources before display, including:
-- inbox-file and schedule-file
-- Org-roam nodes tagged as \"Project\"
+- inbox-file, schedule-file, and the synced calendars
- All todo.org files in immediate subdirectories of projects-dir"
(interactive)
(cj/build-org-agenda-list)
@@ -424,7 +440,7 @@ This allows a line to show in an agenda without being scheduled or a deadline."
:init
;; Initialize org-agenda-files with base files before chime loads
;; The full list will be built asynchronously later
- (setq org-agenda-files (list inbox-file schedule-file gcal-file pcal-file dcal-file))
+ (setq org-agenda-files (cj/--org-agenda-base-files))
;; Debug mode (keep set to nil, but available for troubleshooting)
(setq chime-debug nil)
diff --git a/modules/org-babel-config.el b/modules/org-babel-config.el
index 821403a0d..bc7ccb806 100644
--- a/modules/org-babel-config.el
+++ b/modules/org-babel-config.el
@@ -29,6 +29,12 @@
(setq org-src-fontify-natively t) ;; fontify the code in blocks
(setq org-src-tab-acts-natively t) ;; tabs act like in language major mode buffer
(setq org-src-window-setup 'current-window) ;; don't split window when source editing wih C-c '
+ ;; Treat cj comment blocks (#+begin_src cj: comment ...) as org for editing
+ ;; and fontification: the "cj:" language token maps to org-mode, so C-c '
+ ;; opens an org buffer and the block's prose gets org font-lock in place.
+ ;; The block stays a src block (the cj: grep marker is unchanged); org markup
+ ;; is highlighted and editable, though links are followed from the C-c ' buffer.
+ (add-to-list 'org-src-lang-modes '("cj:" . org))
(setq org-confirm-babel-evaluate t) ;; confirm before running babel; toggle with C-; k
(setq org-babel-default-header-args
(cons '(:tangle . "yes")
diff --git a/modules/org-capture-config.el b/modules/org-capture-config.el
index 18e130dc6..9f5bfbe7f 100644
--- a/modules/org-capture-config.el
+++ b/modules/org-capture-config.el
@@ -30,6 +30,7 @@
(defvar org-complex-heading-regexp-format)
(declare-function cj/--drill-pick-file "org-drill-config")
+(declare-function cj/org-capture--date-prefix "org-capture-config")
(declare-function org-at-encrypted-entry-p "org-crypt")
(declare-function org-at-heading-p "org")
(declare-function org-back-to-heading "org")
@@ -76,6 +77,21 @@
"Return the cache key for PATH and HEADLINE."
(list (org-capture-expand-file path) headline))
+(defun cj/--org-find-or-create-top-heading (search-regexp heading-line)
+ "Move point to the top-level heading matched by SEARCH-REGEXP in this buffer.
+Search from the start of the buffer; on a match leave point at the start of
+that heading line. With no match, append HEADING-LINE (a full \"* ...\" line,
+without a trailing newline) at the end of the buffer and leave point on it.
+Returns point."
+ (goto-char (point-min))
+ (if (re-search-forward search-regexp nil t)
+ (forward-line 0)
+ (goto-char (point-max))
+ (unless (bolp) (insert "\n"))
+ (insert heading-line "\n")
+ (forward-line -1))
+ (point))
+
(defun cj/org-capture--goto-file-headline (path headline)
"Move to capture target PATH and HEADLINE, using a cached marker when valid.
This implements Org's `file+headline' target positioning behavior, but avoids
@@ -94,15 +110,9 @@ re-scanning large target files after the first successful lookup."
(marker (gethash key cj/org-capture--file-headline-target-cache)))
(if (cj/org-capture--headline-marker-valid-p marker headline)
(goto-char marker)
- (goto-char (point-min))
- (if (re-search-forward (format org-complex-heading-regexp-format
- (regexp-quote headline))
- nil t)
- (forward-line 0)
- (goto-char (point-max))
- (unless (bolp) (insert "\n"))
- (insert "* " headline "\n")
- (forward-line -1))
+ (cj/--org-find-or-create-top-heading
+ (format org-complex-heading-regexp-format (regexp-quote headline))
+ (concat "* " headline))
(puthash key (copy-marker (point))
cj/org-capture--file-headline-target-cache))))
@@ -161,7 +171,7 @@ letter upcased: \"~/.emacs.d/\" -> \"Emacs.d\", \"~/code/duet/\" -> \"Duet\"."
ROOT is the projectile project root (or nil); INBOX is the global inbox
file path. Return a plist (:file F :open-work BOOL :project NAME :warn MSG):
- ROOT with a todo.org -> F is that todo.org, :open-work t.
-- ROOT without a todo.org -> F is INBOX, :open-work nil, :warn names the project.
+- ROOT without a todo.org -> F is INBOX, :open-work nil, :warn names project.
- ROOT nil -> F is INBOX, :open-work nil, :warn nil."
(if (and (stringp root) (not (string-empty-p root)))
(let ((todo (expand-file-name "todo.org" root))
@@ -177,27 +187,17 @@ file path. Return a plist (:file F :open-work BOOL :project NAME :warn MSG):
"Move point to a top-level \"... Open Work\" heading in the current buffer.
Create \"* PROJECT-NAME Open Work\" at end of buffer when none exists.
Leave point at the start of the heading line."
- (goto-char (point-min))
- (if (re-search-forward cj/--org-open-work-heading-regexp nil t)
- (forward-line 0)
- (goto-char (point-max))
- (unless (bolp) (insert "\n"))
- (insert (format "* %s Open Work\n" project-name))
- (forward-line -1)))
+ (cj/--org-find-or-create-top-heading
+ cj/--org-open-work-heading-regexp
+ (format "* %s Open Work" project-name)))
(defun cj/--org-capture-goto-exact-headline (headline)
"Move point to the top-level HEADLINE in the current buffer.
Create \"* HEADLINE\" at end of buffer when absent. Leave point at the
start of the heading line."
- (goto-char (point-min))
- (if (re-search-forward (format org-complex-heading-regexp-format
- (regexp-quote headline))
- nil t)
- (forward-line 0)
- (goto-char (point-max))
- (unless (bolp) (insert "\n"))
- (insert "* " headline "\n")
- (forward-line -1)))
+ (cj/--org-find-or-create-top-heading
+ (format org-complex-heading-regexp-format (regexp-quote headline))
+ (concat "* " headline)))
(defun cj/--org-capture-project-location ()
"Org-capture `function' target for project-aware Task/Bug capture.
diff --git a/modules/org-config.el b/modules/org-config.el
index e7538f244..f316ee0df 100644
--- a/modules/org-config.el
+++ b/modules/org-config.el
@@ -17,6 +17,72 @@
(require 'keybindings) ;; provides cj/custom-keymap (used in :init below)
+;; Declare org variables and functions used before org is loaded so this module
+;; byte-compiles standalone. Plain `defvar' (no value) marks the symbol special
+;; without assigning anything, so org's own defaults still apply at runtime.
+(defvar org-dir)
+(defvar org-mode-map)
+(defvar org-mouse-map)
+(defvar org-modules)
+(defvar org-startup-folded)
+(defvar org-cycle-open-archived-trees)
+(defvar org-cycle-hide-drawers)
+(defvar org-id-locations-file)
+(defvar org-return-follows-link)
+(defvar org-list-allow-alphabetical)
+(defvar org-startup-indented)
+(defvar org-adapt-indentation)
+(defvar org-startup-with-inline-images)
+(defvar org-image-actual-width)
+(defvar org-yank-image-save-method)
+(defvar org-bookmark-names-plist)
+(defvar org-file-apps)
+(defvar org-ellipsis)
+(defvar org-hide-emphasis-markers)
+(defvar org-hide-leading-stars)
+(defvar org-pretty-entities)
+(defvar org-pretty-entities-include-sub-superscripts)
+(defvar org-fontify-emphasized-text)
+(defvar org-fontify-whole-heading-line)
+(defvar org-tags-column)
+(defvar org-agenda-tags-column)
+(defvar org-todo-keywords)
+(defvar org-highest-priority)
+(defvar org-lowest-priority)
+(defvar org-default-priority)
+(defvar org-enforce-todo-dependencies)
+(defvar org-enforce-todo-checkbox-dependencies)
+(defvar org-deadline-warning-days)
+(defvar org-treat-insert-todo-heading-as-state-change)
+(defvar org-log-into-drawer)
+(defvar org-log-done)
+(defvar org-use-property-inheritance)
+
+(declare-function org-current-level "org")
+(declare-function org-add-planning-info "org")
+(declare-function org-get-heading "org")
+(declare-function org-edit-headline "org")
+(declare-function org-priority "org")
+(declare-function org-heading-components "org")
+(declare-function org-todo "org")
+(declare-function org-get-todo-state "org")
+(declare-function org-back-to-heading "org")
+(declare-function org-sort-entries "org")
+(declare-function org-eval-in-calendar "org")
+(declare-function org-open-at-point "org")
+(declare-function org-backward-heading-same-level "org")
+(declare-function org-forward-heading-same-level "org")
+(declare-function org-reveal "org")
+(declare-function org-show-todo-tree "org")
+(declare-function org-fold-show-all "org-fold")
+(declare-function outline-next-heading "outline")
+(declare-function org-element-cache-reset "org-element")
+(declare-function org-element-context "org-element")
+(declare-function org-element-type "org-element-ast")
+(declare-function org-superstar-configure-like-org-bullets "org-superstar")
+(declare-function cj/--org-follow-link-same-window "org-config")
+(declare-function cj/org-follow-link-at-mouse-same-window "org-config")
+
;; ---------------------------- Org General Settings ---------------------------
(defun cj/org-general-settings ()
@@ -44,9 +110,6 @@
(setq org-startup-indented t) ;; load org files indented
(setq org-adapt-indentation t) ;; adapt indentation to outline node level
- ;; TASK: this variable doesn't exist. Remove
- ;; (setq org-indent-indentation-per-level 2) ;; indent two character-widths per level
-
;; IMAGES / MEDIA
(setq org-startup-with-inline-images t) ;; preview images by default
(setq org-image-actual-width '(500)) ;; keep image sizes in check
@@ -253,14 +316,14 @@ whole row line."
(keymap-set cj/org-map "<" #'cj/org-narrow-backwards)
;; Sparse trees: lowercase creates, capital of the same letter cancels.
- ;; Both `S' and `T' resolve to `org-show-all' -- same cancel command,
+ ;; Both `S' and `T' resolve to `org-fold-show-all' -- same cancel command,
;; paired with each lowercase create so the mental model is "capital
;; cancels the lowercase command I just ran" without having to recall
;; which letter the cancel actually lives on.
(keymap-set cj/org-map "s" #'org-match-sparse-tree)
- (keymap-set cj/org-map "S" #'org-show-all)
+ (keymap-set cj/org-map "S" #'org-fold-show-all)
(keymap-set cj/org-map "t" #'org-show-todo-tree)
- (keymap-set cj/org-map "T" #'org-show-all)
+ (keymap-set cj/org-map "T" #'org-fold-show-all)
(keymap-set cj/org-map "R" #'org-reveal)
:bind
("C-c c" . org-capture)
@@ -276,8 +339,7 @@ whole row line."
("C-c N" . org-narrow-to-subtree)
("C-c >" . cj/org-narrow-forward)
("C-c <" . cj/org-narrow-backwards)
- ("C-c <ESC>" . widen)
- ("C-c C-a" . cj/org-appear-toggle))
+ ("C-c <ESC>" . widen))
(:map cj/org-map
("r i" . org-table-insert-row)
("r d" . org-table-kill-row)
@@ -404,6 +466,11 @@ especially in tables with long URLs)."
(org-appear-mode 1)
(message "org-appear enabled (links/emphasis show when editing)")))
+;; Bound here (after the defun) rather than in the org use-package `:bind' so
+;; the command isn't autoloaded into a stub that shadows this definition.
+(with-eval-after-load 'org
+ (keymap-set org-mode-map "C-c C-a" #'cj/org-appear-toggle))
+
;; --------------------------------- Org-Tidy ----------------------------------
;; Hide :PROPERTIES: drawers behind a small inline marker so headings stay
@@ -447,7 +514,7 @@ with a file, the function will throw an error."
"Clear the org-element cache for the current buffer or all buffers.
By default, clear cache for all org buffers. With prefix argument, clear only
the current buffer's cache. Useful when encountering parsing errors like
-'wrong-type-argument stringp nil' during agenda generation."
+\"wrong-type-argument stringp nil\" during agenda generation."
(interactive)
(if current-prefix-arg
(if (derived-mode-p 'org-mode)
diff --git a/modules/org-contacts-config.el b/modules/org-contacts-config.el
index d558245b6..64abb9fb5 100644
--- a/modules/org-contacts-config.el
+++ b/modules/org-contacts-config.el
@@ -22,6 +22,36 @@
(require 'user-constants)
+;; Function declarations -- these live in lazily-loaded packages, so the
+;; byte-compiler can't see their definitions when this module compiles
+;; standalone.
+(declare-function org-contacts-db "org-contacts")
+(declare-function org-contacts-anniversaries "org-contacts")
+(declare-function org-contacts-files "org-contacts")
+(declare-function org-columns "org-colview")
+(declare-function org-reveal "org")
+(declare-function org-fold-show-entry "org-fold")
+(declare-function org-heading-components "org")
+(declare-function org-map-entries "org")
+(declare-function org-entry-get "org")
+(declare-function outline-next-heading "outline")
+(declare-function calendar-current-date "calendar")
+(declare-function mu4e-message-at-point "mu4e-message")
+(declare-function mu4e-message-field "mu4e-message")
+(declare-function which-key-add-key-based-replacements "which-key")
+
+;; External package variables referenced below; declared so the compiler
+;; treats them as special rather than free.
+(defvar org-capture-plist)
+(defvar org-capture-templates)
+(defvar mu4e~view-message)
+(defvar org-agenda-include-diary)
+(defvar org-agenda-custom-commands)
+(defvar mu4e-org-contacts-file)
+(defvar mu4e-headers-actions)
+(defvar mu4e-view-actions)
+(defvar mu4e-compose-complete-addresses)
+
;; Set `org-contacts-files' eagerly at require time. Setting it in the
;; `use-package' form below would only apply when org-contacts loads, which is
;; deferred behind `:after (org mu4e)' -- later than the first
@@ -42,10 +72,13 @@
(defun cj/org-contacts-anniversaries-safe ()
"Safely call org-contacts-anniversaries with required bindings."
(require 'diary-lib)
- ;; These need to be dynamically bound for diary functions
- (defvar date)
- (defvar entry)
- (defvar original-date)
+ ;; `date', `entry', and `original-date' are diary special vars that the
+ ;; diary functions read dynamically. Declare them special locally; the
+ ;; suppressed warning is the unprefixed-name lint on these calendar names.
+ (with-suppressed-warnings ((lexical date entry original-date))
+ (defvar date)
+ (defvar entry)
+ (defvar original-date))
(let ((date (calendar-current-date))
(entry "")
(original-date (calendar-current-date)))
@@ -115,14 +148,6 @@
Added: %U"
:prepare-finalize cj/org-contacts-finalize-birthday-timestamp)))
-;; TASK: What purpose did this serve?
-;; duplicate?!?
-;; (with-eval-after-load 'org-capture
-;; (add-to-list 'org-capture-templates
-;; '("C" "Contact" entry (file+headline contacts-file "Contacts")
-;; "* %(cj/org-contacts-template-name)
-;; Added: %U")))
-
(defun cj/org-contacts-template-name ()
"Get name for contact template from context."
(or (when (eq major-mode 'mu4e-headers-mode)
@@ -194,9 +219,10 @@ Added: %U"
(defun cj/--parse-email-string (name email-string)
"Parse EMAIL-STRING and return formatted entries for NAME.
-EMAIL-STRING may contain multiple emails separated by commas, semicolons, or spaces.
-Returns a list of strings formatted as 'Name <email>'.
-Returns nil if EMAIL-STRING is nil or contains only whitespace."
+EMAIL-STRING may contain multiple emails separated by commas,
+semicolons, or spaces. Returns a list of strings formatted as
+\"Name <email>\". Returns nil if EMAIL-STRING is nil or contains only
+whitespace."
(when (and email-string (string-match-p "[^[:space:]]" email-string))
(let ((emails (split-string email-string "[,;[:space:]]+" t)))
(mapcar (lambda (email)
diff --git a/modules/org-faces-config.el b/modules/org-faces-config.el
index e0dfa83fd..dfbfe9d0d 100644
--- a/modules/org-faces-config.el
+++ b/modules/org-faces-config.el
@@ -35,72 +35,72 @@
;; --------------------------- Keyword faces (focused) -------------------------
-(defface org-faces-todo '((t (:foreground "#8fbf73" :weight bold)))
+(defface org-faces-todo '((t (:weight bold)))
"Face for the TODO keyword." :group 'org-faces-config)
-(defface org-faces-project '((t (:foreground "#7a9abe" :weight bold)))
+(defface org-faces-project '((t (:weight bold)))
"Face for the PROJECT keyword." :group 'org-faces-config)
-(defface org-faces-doing '((t (:foreground "#e8c668" :weight bold)))
+(defface org-faces-doing '((t (:weight bold)))
"Face for the DOING keyword." :group 'org-faces-config)
-(defface org-faces-waiting '((t (:foreground "#c9b08a" :weight bold)))
+(defface org-faces-waiting '((t (:weight bold)))
"Face for the WAITING keyword." :group 'org-faces-config)
-(defface org-faces-verify '((t (:foreground "#d98a5a" :weight bold)))
+(defface org-faces-verify '((t (:weight bold)))
"Face for the VERIFY keyword." :group 'org-faces-config)
-(defface org-faces-stalled '((t (:foreground "#9a8fb0" :weight bold)))
+(defface org-faces-stalled '((t (:weight bold)))
"Face for the STALLED keyword." :group 'org-faces-config)
-(defface org-faces-delegated '((t (:foreground "#7fc0a8" :weight bold)))
+(defface org-faces-delegated '((t (:weight bold)))
"Face for the DELEGATED keyword." :group 'org-faces-config)
-(defface org-faces-failed '((t (:foreground "#d05a5a" :weight bold)))
+(defface org-faces-failed '((t (:weight bold)))
"Face for the FAILED keyword." :group 'org-faces-config)
-(defface org-faces-done '((t (:foreground "#6f7a82" :weight bold)))
+(defface org-faces-done '((t (:weight bold)))
"Face for the DONE keyword." :group 'org-faces-config)
-(defface org-faces-cancelled '((t (:foreground "#6f7a82" :weight bold :strike-through t)))
+(defface org-faces-cancelled '((t (:weight bold :strike-through t)))
"Face for the CANCELLED keyword." :group 'org-faces-config)
;; -------------------------- Priority faces (focused) -------------------------
-(defface org-faces-priority-a '((t (:foreground "#7aa0d0" :weight bold)))
+(defface org-faces-priority-a '((t (:weight bold)))
"Face for the [#A] priority cookie." :group 'org-faces-config)
-(defface org-faces-priority-b '((t (:foreground "#e8c668")))
+(defface org-faces-priority-b '((t ()))
"Face for the [#B] priority cookie." :group 'org-faces-config)
-(defface org-faces-priority-c '((t (:foreground "#8fbf73")))
+(defface org-faces-priority-c '((t ()))
"Face for the [#C] priority cookie." :group 'org-faces-config)
-(defface org-faces-priority-d '((t (:foreground "#8a8a8a")))
+(defface org-faces-priority-d '((t ()))
"Face for the [#D] priority cookie." :group 'org-faces-config)
;; ----------------------------- Keyword faces (dim) ---------------------------
;; auto-dim-config.el remaps the focused faces above to these in non-selected
;; windows; a darker shade of the same hue keeps the keyword recognizable.
-(defface org-faces-todo-dim '((t (:foreground "#5f7a4d" :weight bold)))
+(defface org-faces-todo-dim '((t (:weight bold)))
"Dimmed TODO keyword for non-selected windows." :group 'org-faces-config)
-(defface org-faces-project-dim '((t (:foreground "#4f6680" :weight bold)))
+(defface org-faces-project-dim '((t (:weight bold)))
"Dimmed PROJECT keyword for non-selected windows." :group 'org-faces-config)
-(defface org-faces-doing-dim '((t (:foreground "#9a8544" :weight bold)))
+(defface org-faces-doing-dim '((t (:weight bold)))
"Dimmed DOING keyword for non-selected windows." :group 'org-faces-config)
-(defface org-faces-waiting-dim '((t (:foreground "#87745c" :weight bold)))
+(defface org-faces-waiting-dim '((t (:weight bold)))
"Dimmed WAITING keyword for non-selected windows." :group 'org-faces-config)
-(defface org-faces-verify-dim '((t (:foreground "#8f5a3c" :weight bold)))
+(defface org-faces-verify-dim '((t (:weight bold)))
"Dimmed VERIFY keyword for non-selected windows." :group 'org-faces-config)
-(defface org-faces-stalled-dim '((t (:foreground "#665e75" :weight bold)))
+(defface org-faces-stalled-dim '((t (:weight bold)))
"Dimmed STALLED keyword for non-selected windows." :group 'org-faces-config)
-(defface org-faces-delegated-dim '((t (:foreground "#547d6c" :weight bold)))
+(defface org-faces-delegated-dim '((t (:weight bold)))
"Dimmed DELEGATED keyword for non-selected windows." :group 'org-faces-config)
-(defface org-faces-failed-dim '((t (:foreground "#8a3c3c" :weight bold)))
+(defface org-faces-failed-dim '((t (:weight bold)))
"Dimmed FAILED keyword for non-selected windows." :group 'org-faces-config)
-(defface org-faces-done-dim '((t (:foreground "#4a5158" :weight bold)))
+(defface org-faces-done-dim '((t (:weight bold)))
"Dimmed DONE keyword for non-selected windows." :group 'org-faces-config)
-(defface org-faces-cancelled-dim '((t (:foreground "#4a5158" :weight bold :strike-through t)))
+(defface org-faces-cancelled-dim '((t (:weight bold :strike-through t)))
"Dimmed CANCELLED keyword for non-selected windows." :group 'org-faces-config)
;; ---------------------------- Priority faces (dim) ---------------------------
-(defface org-faces-priority-a-dim '((t (:foreground "#4f6a8a" :weight bold)))
+(defface org-faces-priority-a-dim '((t (:weight bold)))
"Dimmed [#A] priority cookie for non-selected windows." :group 'org-faces-config)
-(defface org-faces-priority-b-dim '((t (:foreground "#9a8544")))
+(defface org-faces-priority-b-dim '((t ()))
"Dimmed [#B] priority cookie for non-selected windows." :group 'org-faces-config)
-(defface org-faces-priority-c-dim '((t (:foreground "#5f7a4d")))
+(defface org-faces-priority-c-dim '((t ()))
"Dimmed [#C] priority cookie for non-selected windows." :group 'org-faces-config)
-(defface org-faces-priority-d-dim '((t (:foreground "#5a5a5a")))
+(defface org-faces-priority-d-dim '((t ()))
"Dimmed [#D] priority cookie for non-selected windows." :group 'org-faces-config)
;; ---------------------------------- Wiring -----------------------------------
diff --git a/modules/org-noter-config.el b/modules/org-noter-config.el
index 4e5bd1778..f28f61bb7 100644
--- a/modules/org-noter-config.el
+++ b/modules/org-noter-config.el
@@ -39,9 +39,32 @@
;; Forward declarations
(declare-function org-id-uuid "org-id")
+(declare-function org-entry-get "org")
(declare-function nov-mode "ext:nov")
(declare-function pdf-view-mode "ext:pdf-view")
+;; pdf-tools fit commands (lazily loaded with pdf-tools)
+(declare-function pdf-view-fit-width-to-window "pdf-view")
+(declare-function pdf-view-fit-height-to-window "pdf-view")
+(declare-function pdf-view-fit-page-to-window "pdf-view")
+;; face-remap is built in but loaded lazily
+(declare-function face-remap-remove-relative "face-remap")
+;; org-noter session/sync/skeleton commands (lazily loaded with org-noter)
+(declare-function org-noter--get-notes-window "org-noter")
+(declare-function org-noter--get-doc-window "org-noter")
+(declare-function org-noter-insert-note "org-noter")
+(declare-function org-noter-enable-org-roam-integration "org-noter")
+(declare-function org-noter-sync-next-note "org-noter")
+(declare-function org-noter-sync-prev-note "org-noter")
+(declare-function org-noter-sync-current-note "org-noter")
+(declare-function org-noter-create-skeleton "org-noter")
+(declare-function org-noter-kill-session "org-noter")
+(declare-function org-noter-toggle-notes-window-location "org-noter")
(defvar nov-file-name)
+;; org-noter package variables assigned at session start / config time
+(defvar org-noter-notes-window-location)
+(defvar org-noter-use-pdftools-link-location)
+(defvar org-noter-use-org-id)
+(defvar org-noter-use-unique-org-id)
;;; Configuration Variables
(defvar cj/org-noter-notes-directory roam-dir
@@ -284,7 +307,7 @@ From a PDF/EPUB: starts org-noter session if inactive, then inserts note."
(cond
((and active (not cj/org-noter--bg-remap-cookie))
(setq cj/org-noter--bg-remap-cookie
- (face-remap-add-relative 'default :background "#1d1b19")))
+ (face-remap-add-relative 'default)))
((and (not active) cj/org-noter--bg-remap-cookie)
(face-remap-remove-relative cj/org-noter--bg-remap-cookie)
(setq cj/org-noter--bg-remap-cookie nil))))))))
diff --git a/modules/org-refile-config.el b/modules/org-refile-config.el
index a6b7ac3a4..5f826cacf 100644
--- a/modules/org-refile-config.el
+++ b/modules/org-refile-config.el
@@ -36,7 +36,8 @@
;; ----------------------------- Org Refile Targets ----------------------------
;; sets refile targets
-;; - adds project files in org-roam to the refile targets
+;; - adds org-roam notes tagged "Topic" to the refile targets
+;; (roam "Project" notes were dropped as refile targets 2026-06-24)
;; - adds todo.org files in subdirectories of the code and project directories
(defvar cj/--org-refile-targets-cache (cj/cache-make :ttl 3600)
@@ -100,11 +101,9 @@ Returns the list to assign to `org-refile-targets'. Slow -- walks
(cons schedule-file '(:maxlevel . 1)))))
(when (and (fboundp 'cj/org-roam-list-notes-by-tag)
(fboundp 'org-roam-node-list))
- (let* ((project-and-topic-files
- (append (cj/org-roam-list-notes-by-tag "Project")
- (cj/org-roam-list-notes-by-tag "Topic")))
- (file-rule '(:maxlevel . 1)))
- (dolist (file project-and-topic-files)
+ (let ((topic-files (cj/org-roam-list-notes-by-tag "Topic"))
+ (file-rule '(:maxlevel . 1)))
+ (dolist (file topic-files)
(unless (assoc file new-files)
(push (cons file file-rule) new-files)))))
(let ((file-rule '(:maxlevel . 1)))
diff --git a/modules/org-roam-config.el b/modules/org-roam-config.el
index 218f37d68..eca867df8 100644
--- a/modules/org-roam-config.el
+++ b/modules/org-roam-config.el
@@ -27,6 +27,29 @@
(require 'user-constants)
+;; Declared special so the `let'-binding in `cj/org-roam-copy-todo-to-today'
+;; compiles as a dynamic bind, not a dead lexical local -- otherwise the custom
+;; capture template never reaches org-roam-dailies (the foreign-special-var trap).
+(defvar org-roam-dailies-capture-templates)
+
+;; External variables, declared special so byte-compilation doesn't treat them
+;; as free references/assignments. Owned by org and org-roam-dailies.
+(defvar org-agenda-timegrid-use-ampm)
+(defvar org-roam-dailies-map)
+(defvar org-last-state)
+
+;; External functions, declared so the byte-compiler knows they're defined at
+;; runtime by their respective packages.
+(declare-function org-roam-node-tags "org-roam")
+(declare-function org-roam-node-file "org-roam")
+(declare-function org-roam-node-list "org-roam")
+(declare-function org-roam-dailies--capture "org-roam-dailies")
+(declare-function org-capture-get "org-capture")
+(declare-function org-at-heading-p "org")
+(declare-function org-heading-components "org")
+(declare-function org-copy-subtree "org")
+(declare-function org-cut-subtree "org")
+
;; ---------------------------------- Org Roam ---------------------------------
(defconst cj/--org-roam-dailies-head
@@ -71,8 +94,6 @@ FILETAGS and TITLE must sit on separate lines so Org parses the
:bind (("C-c n l" . org-roam-buffer-toggle)
("C-c n f" . org-roam-node-find)
("C-c n p" . cj/org-roam-find-node-project)
- ("C-c n r" . cj/org-roam-find-node-recipe)
- ("C-c n t" . cj/org-roam-find-node-topic)
("C-c n i" . org-roam-node-insert)
("C-c n w" . cj/org-roam-find-node-webclip)
:map org-mode-map
@@ -81,8 +102,10 @@ FILETAGS and TITLE must sit on separate lines so Org parses the
;; org-log-done is set once in org-config.el (cj/org-todo-settings).
(setq org-agenda-timegrid-use-ampm t)
- (when (fboundp 'cj/build-org-refile-targets)
- (cj/build-org-refile-targets))
+ ;; Don't build the org-refile targets cache here. org-refile-config.el
+ ;; already schedules it on a 5s idle timer; doing it in org-roam's :config
+ ;; (which fires at the 1s :defer) ran the same multi-file scan synchronously
+ ;; at first idle and froze Emacs on a cold cache. The 5s timer covers it.
;; remove/disable if performance slows
;; (setq org-element-use-cache nil) ;; disables caching org files
@@ -186,6 +209,11 @@ created in that subdirectory of `org-roam-directory'."
(interactive)
(cj/org-roam-find-node "Recipe" "r" (concat roam-dir "templates/recipe.org") "recipes/"))
+;; Bound after their defuns (not in the use-package :bind) so the byte-compiler
+;; doesn't see both a :bind autoload and the real defun as two definitions.
+(keymap-global-set "C-c n r" #'cj/org-roam-find-node-recipe)
+(keymap-global-set "C-c n t" #'cj/org-roam-find-node-topic)
+
;; ---------------------- Org Capture After Finalize Hook ----------------------
(defun cj/org-roam-add-node-to-agenda-files-finalize-hook ()
diff --git a/modules/pdf-config.el b/modules/pdf-config.el
index ca2312307..56b397df3 100644
--- a/modules/pdf-config.el
+++ b/modules/pdf-config.el
@@ -14,6 +14,22 @@
;;
;;; Code:
+;; ------------------------------- Declarations --------------------------------
+
+(declare-function pdf-tools-install "pdf-tools")
+(declare-function pdf-view-midnight-minor-mode "pdf-view")
+(declare-function pdf-view-enlarge "pdf-view")
+(declare-function pdf-view-shrink "pdf-view")
+(declare-function pdf-view-next-page "pdf-view")
+(declare-function pdf-view-previous-page "pdf-view")
+(declare-function image-next-line "image-mode")
+(declare-function image-previous-line "image-mode")
+(declare-function image-bob "image-mode")
+(declare-function image-eob "image-mode")
+(declare-function org-store-link "ol")
+(declare-function cj/open-file-with-command "system-utils")
+(declare-function cj/org-noter-insert-note-dwim "org-noter-config")
+
;; --------------------------------- PDF Tools ---------------------------------
(use-package pdf-tools
@@ -24,7 +40,6 @@
:custom
(pdf-view-display-size 'fit-page)
(pdf-view-resize-factor 1.1)
- (pdf-view-midnight-colors '("#F1D5AC" . "#0F0E06")) ;; fg . bg
;; Avoid searching for unicodes to speed up pdf-tools.
;; ... and yes, 'ligther' is not a typo
(pdf-view-use-unicode-ligther nil)
@@ -61,9 +76,9 @@
(define-key pdf-view-mode-map "i" #'cj/org-noter-insert-note-dwim)
;; Page change: C-up/C-down go to top of prev/next page
(define-key pdf-view-mode-map (kbd "C-<down>")
- (lambda () (interactive) (pdf-view-next-page-command) (image-bob)))
+ (lambda () (interactive) (pdf-view-next-page) (image-bob)))
(define-key pdf-view-mode-map (kbd "C-<up>")
- (lambda () (interactive) (pdf-view-previous-page-command) (image-eob))))
+ (lambda () (interactive) (pdf-view-previous-page) (image-eob))))
;; ------------------------------ PDF View Restore -----------------------------
diff --git a/modules/prog-general.el b/modules/prog-general.el
index 53f20ce46..f22f89923 100644
--- a/modules/prog-general.el
+++ b/modules/prog-general.el
@@ -59,14 +59,29 @@
(declare-function treesit-auto-add-to-auto-mode-alist "treesit-auto")
(declare-function treesit-auto-recipe-lang "treesit-auto")
(declare-function highlight-indent-guides-mode "highlight-indent-guides")
+(declare-function electric-pair-default-inhibit "elec-pair")
+(declare-function yas-reload-all "yasnippet")
+(declare-function yas-activate-extra-mode "yasnippet")
;; Forward declarations for treesit-auto variables
(defvar treesit-auto-recipe-list)
+(defvar electric-pair-inhibit-predicate)
;; Forward declarations for functions defined later in this file
-(declare-function cj/find-project-root-file "prog-general")
(declare-function cj/project-switch-actions "prog-general")
-(declare-function cj/deadgrep--initial-term "prog-general")
+
+(defun cj/find-project-root-file (regexp)
+ "Return first file in the current Projectile project root matching REGEXP.
+
+Match is done against (downcase file) for case-insensitivity.
+REGEXP must be a string or an rx form."
+ (when-let ((root (projectile-project-root)))
+ (seq-find (lambda (file)
+ (string-match-p (if (stringp regexp)
+ regexp
+ (rx-to-string regexp))
+ (downcase file)))
+ (directory-files root))))
(declare-function cj/highlight-indent-guides-disable-in-non-prog-modes "prog-general")
;; --------------------- General Programming Mode Settings ---------------------
@@ -177,19 +192,6 @@ reuses the current window otherwise, matching `cj/open-project-root-todo'."
:config
(require 'seq)
- (defun cj/find-project-root-file (regexp)
- "Return first file in the current Projectile project root matching REGEXP.
-
-Match is done against (downcase file) for case-insensitivity.
-REGEXP must be a string or an rx form."
- (when-let ((root (projectile-project-root)))
- (seq-find (lambda (file)
- (string-match-p (if (stringp regexp)
- regexp
- (rx-to-string regexp))
- (downcase file)))
- (directory-files root))))
-
(defun cj/open-project-root-todo ()
"Open todo.org in the current Projectile project root.
@@ -233,6 +235,23 @@ If no such file exists there, display a message."
;; ---------------------------------- Ripgrep ----------------------------------
+(declare-function deadgrep "deadgrep")
+
+(defun cj/deadgrep--initial-term ()
+ "Return the region text or the symbol at point, to seed a Deadgrep search."
+ (cond
+ ((use-region-p)
+ (buffer-substring-no-properties (region-beginning) (region-end)))
+ (t (thing-at-point 'symbol t))))
+
+(defun cj/--deadgrep-run (root &optional term)
+ "Run Deadgrep for TERM under directory ROOT.
+ROOT is normalized to a directory name; TERM defaults to a minibuffer read
+seeded by `cj/deadgrep--initial-term'. Shared tail of the deadgrep commands."
+ (let ((root (file-name-as-directory (expand-file-name root)))
+ (term (or term (read-from-minibuffer "Search: " (cj/deadgrep--initial-term)))))
+ (deadgrep term root)))
+
(use-package deadgrep
:after projectile
:bind
@@ -243,12 +262,6 @@ If no such file exists there, display a message."
:config
(require 'thingatpt)
- (defun cj/deadgrep--initial-term ()
- (cond
- ((use-region-p)
- (buffer-substring-no-properties (region-beginning) (region-end)))
- (t (thing-at-point 'symbol t))))
-
(defun cj/deadgrep-here (&optional term)
"Search with Deadgrep in the most relevant directory at point."
(interactive)
@@ -265,21 +278,28 @@ If no such file exists there, display a message."
(buffer-file-name
(file-name-directory (file-truename buffer-file-name)))
(t default-directory)))
- (root (file-name-as-directory (expand-file-name root)))
- (term (or term (read-from-minibuffer "Search: " (cj/deadgrep--initial-term)))))
- (deadgrep term root)))
+ )
+ (cj/--deadgrep-run root term)))
(defun cj/deadgrep-in-dir (&optional dir term)
"Prompt for a directory, then search there with Deadgrep."
(interactive)
- (let* ((dir (or dir (read-directory-name "Search in directory: " default-directory nil t)))
- (dir (file-name-as-directory (expand-file-name dir)))
- (term (or term (read-from-minibuffer "Search: " (cj/deadgrep--initial-term)))))
- (deadgrep term dir))))
+ (let ((dir (or dir (read-directory-name "Search in directory: " default-directory nil t))))
+ (cj/--deadgrep-run dir term))))
(with-eval-after-load 'dired
(keymap-set dired-mode-map "G" #'cj/deadgrep-here))
+;; ------------------------------------ wgrep ----------------------------------
+;; Make a grep buffer editable, then write the edits back across files -- turns
+;; a consult-grep / embark-export result into a project-wide find-and-replace.
+;; In a grep buffer: C-c C-p to start editing, C-c C-c to apply.
+
+(use-package wgrep
+ :custom
+ (wgrep-auto-save-buffer t) ;; save the touched files when applying
+ (wgrep-change-readonly-file t)) ;; let edits flow into read-only buffers
+
;; ---------------------------------- Snippets ---------------------------------
;; reusable code and text
@@ -364,16 +384,7 @@ defer to `electric-pair-default-inhibit' for any other CHAR."
(use-package hl-todo
:defer 1
:hook
- (prog-mode . hl-todo-mode)
- :config
- (setq hl-todo-keyword-faces
- '(("FIXME" . "#FF0000")
- ("BUG" . "#FF0000")
- ("HACK" . "#FF0000")
- ("ISSUE" . "#DAA520")
- ("TASK" . "#DAA520")
- ("NOTE" . "#2C780E")
- ("WIP" . "#1E90FF"))))
+ (prog-mode . hl-todo-mode))
;; --------------------------- Whitespace Management ---------------------------
;; trims trailing whitespace only from lines you've modified when saving buffer
diff --git a/modules/prog-json.el b/modules/prog-json.el
index 953b5f79b..e7abd1828 100644
--- a/modules/prog-json.el
+++ b/modules/prog-json.el
@@ -9,7 +9,7 @@
;; Eager reason: none necessary; currently eager but should load by JSON major
;; mode (Phase 6 deferral candidate).
;; Top-level side effects: one add-hook, package configuration via use-package.
-;; Runtime requires: none (configures packages via use-package).
+;; Runtime requires: system-lib (cj/format-region-with-program).
;; Direct test load: yes.
;;
;; JSON editing with tree-sitter highlighting, one-key formatting, and
@@ -27,6 +27,8 @@
;;; Code:
+(require 'system-lib)
+
(defvar json-ts-mode-map)
;; -------------------------------- JSON Mode ----------------------------------
@@ -41,38 +43,13 @@
;; -------------------------------- Formatting ---------------------------------
;; pretty-print with sorted keys, bound to standard format key
-(defun cj/--json-format-region (program &rest args)
- "Replace the buffer with PROGRAM ARGS run over its contents, via argv.
-Runs PROGRAM (with ARGS) on the whole buffer through
-`call-process-region' — no shell, so no quoting or word-splitting.
-The buffer is replaced only when PROGRAM exits zero; on a non-zero
-exit the buffer is left untouched and an error is signalled with
-the program's stderr text. Point is preserved as closely as the
-reformatted size allows. Returns t on success."
- (let* ((point (point))
- (src (current-buffer))
- (out (generate-new-buffer " *json-format-out*"))
- (status (apply #'call-process-region
- (point-min) (point-max) program
- nil out nil args)))
- (unwind-protect
- (if (and (integerp status) (zerop status))
- (progn
- (with-current-buffer src
- (replace-buffer-contents out)
- (goto-char (min point (point-max))))
- t)
- (user-error "%s failed: %s" program
- (string-trim (with-current-buffer out (buffer-string)))))
- (kill-buffer out))))
-
(defun cj/json-format-buffer ()
"Format the current JSON buffer with sorted keys.
Uses jq if available for reliable formatting, otherwise falls
back to the built-in `json-pretty-print-buffer-ordered'."
(interactive)
(if (executable-find "jq")
- (cj/--json-format-region "jq" "--sort-keys" ".")
+ (cj/format-region-with-program "jq" "--sort-keys" ".")
(json-pretty-print-buffer-ordered)))
(defun cj/json-setup ()
diff --git a/modules/prog-webdev.el b/modules/prog-webdev.el
index 8832446ac..b228d0cc8 100644
--- a/modules/prog-webdev.el
+++ b/modules/prog-webdev.el
@@ -82,37 +82,12 @@ via `call-process-region', so FILE can contain spaces or shell
metacharacters without risk."
(list "--stdin-filepath" file))
-(defun cj/--webdev-format-region (program &rest args)
- "Replace the buffer with PROGRAM ARGS run over its contents, via argv.
-Runs PROGRAM (with ARGS) on the whole buffer through
-`call-process-region' — no shell, so no quoting or word-splitting.
-The buffer is replaced only when PROGRAM exits zero; on a non-zero
-exit the buffer is left untouched and an error is signalled with
-the program's stderr text. Point is preserved as closely as the
-reformatted size allows. Returns t on success."
- (let* ((point (point))
- (src (current-buffer))
- (out (generate-new-buffer " *webdev-format-out*"))
- (status (apply #'call-process-region
- (point-min) (point-max) program
- nil out nil args)))
- (unwind-protect
- (if (and (integerp status) (zerop status))
- (progn
- (with-current-buffer src
- (replace-buffer-contents out)
- (goto-char (min point (point-max))))
- t)
- (user-error "%s failed: %s" program
- (string-trim (with-current-buffer out (buffer-string)))))
- (kill-buffer out))))
-
(defun cj/webdev-format-buffer ()
"Format the current buffer with prettier.
Detects the file type automatically from the filename."
(interactive)
(if (executable-find prettier-path)
- (apply #'cj/--webdev-format-region prettier-path
+ (apply #'cj/format-region-with-program prettier-path
(cj/--webdev-format-args (or buffer-file-name "file.ts")))
(user-error "prettier not found; install with: sudo pacman -S prettier")))
diff --git a/modules/prog-yaml.el b/modules/prog-yaml.el
index c2bb559b1..e07cf510e 100644
--- a/modules/prog-yaml.el
+++ b/modules/prog-yaml.el
@@ -9,7 +9,7 @@
;; Eager reason: none necessary; currently eager but should load by YAML major
;; mode (Phase 6 deferral candidate).
;; Top-level side effects: one add-hook, package configuration via use-package.
-;; Runtime requires: none (configures packages via use-package).
+;; Runtime requires: system-lib (cj/format-region-with-program).
;; Direct test load: yes.
;;
;; YAML editing with tree-sitter highlighting and one-key formatting.
@@ -24,6 +24,8 @@
;;; Code:
+(require 'system-lib)
+
;; -------------------------------- YAML Mode ----------------------------------
;; tree-sitter mode for YAML files (built-in, Emacs 29+)
;; NOTE: No :mode directive — treesit-auto (in prog-general.el) handles
@@ -36,37 +38,12 @@
;; -------------------------------- Formatting ---------------------------------
;; normalize indentation and style, bound to standard format key
-(defun cj/--yaml-format-region (program &rest args)
- "Replace the buffer with PROGRAM ARGS run over its contents, via argv.
-Runs PROGRAM (with ARGS) on the whole buffer through
-`call-process-region' — no shell, so no quoting or word-splitting.
-The buffer is replaced only when PROGRAM exits zero; on a non-zero
-exit the buffer is left untouched and an error is signalled with
-the program's stderr text. Point is preserved as closely as the
-reformatted size allows. Returns t on success."
- (let* ((point (point))
- (src (current-buffer))
- (out (generate-new-buffer " *yaml-format-out*"))
- (status (apply #'call-process-region
- (point-min) (point-max) program
- nil out nil args)))
- (unwind-protect
- (if (and (integerp status) (zerop status))
- (progn
- (with-current-buffer src
- (replace-buffer-contents out)
- (goto-char (min point (point-max))))
- t)
- (user-error "%s failed: %s" program
- (string-trim (with-current-buffer out (buffer-string)))))
- (kill-buffer out))))
-
(defun cj/yaml-format-buffer ()
"Format the current YAML buffer with prettier.
Preserves point position as closely as possible."
(interactive)
(if (executable-find "prettier")
- (cj/--yaml-format-region "prettier" "--parser" "yaml")
+ (cj/format-region-with-program "prettier" "--parser" "yaml")
(user-error "prettier not found; install with: npm install -g prettier")))
(defun cj/yaml-setup ()
diff --git a/modules/selection-framework.el b/modules/selection-framework.el
index a567e8003..464654a20 100644
--- a/modules/selection-framework.el
+++ b/modules/selection-framework.el
@@ -26,6 +26,12 @@
;;
;;; Code:
+;; External variables and lazily-loaded functions referenced below.
+(defvar xref-show-xrefs-function)
+(defvar xref-show-definitions-function)
+(declare-function consult-dir-projectile-dirs "consult-dir")
+(declare-function prescient-persist-mode "prescient")
+
;; ---------------------------------- Vertico ----------------------------------
;; Vertical completion UI
diff --git a/modules/system-defaults.el b/modules/system-defaults.el
index 0062a82cf..6d9c811a6 100644
--- a/modules/system-defaults.el
+++ b/modules/system-defaults.el
@@ -212,18 +212,13 @@ appears only once per session."
(setq custom-safe-themes t) ;; treat all themes as safe (stop asking)
(setq server-client-instructions nil) ;; I already know what to do when done with the frame
-;; ------------------ Reduce Garbage Collections In Minibuffer -----------------
-
-(defun cj/minibuffer-setup-hook ()
- "Hook to prevent garbage collection while user's in minibuffer."
- (setq gc-cons-threshold most-positive-fixnum))
-
-(defun cj/minibuffer-exit-hook ()
- "Hook to trigger garbage collection when exiting minibuffer."
- (setq gc-cons-threshold 800000))
-
-(add-hook 'minibuffer-setup-hook #'cj/minibuffer-setup-hook)
-(add-hook 'minibuffer-exit-hook #'cj/minibuffer-exit-hook)
+;; ----------------------------- Garbage Collection ----------------------------
+;; GC is managed by gcmh in modules/gcmh-config.el: it keeps gc-cons-threshold
+;; high during activity and collects on idle, replacing the old stock-800KB
+;; scheme (an early-init restore plus a minibuffer setup/exit bump). gcmh lives
+;; in its own module rather than here because system-defaults.el is pre-loaded
+;; by the comp-errors test harness, which has no package system -- an `:ensure'
+;; package loaded here would error at load time and break those tests.
;; ----------------------------- Bookmark Settings -----------------------------
diff --git a/modules/system-lib.el b/modules/system-lib.el
index 9e25be5b7..49bb6cd1a 100644
--- a/modules/system-lib.el
+++ b/modules/system-lib.el
@@ -141,5 +141,52 @@ long-form answer, keeping a stray RET or space from confirming."
(let ((use-short-answers nil))
(yes-or-no-p prompt)))
+(defun cj/--font-lock-global-modes-excluding (current mode)
+ "Return CURRENT `font-lock-global-modes' with MODE added to the exclusion.
+CURRENT has one of three shapes: t (font-lock on in all modes), a
+\(not M...) exclusion list, or an (M...) inclusion list. Pure: returns
+the new value and mutates nothing."
+ (cond
+ ((eq current t) (list 'not mode))
+ ((and (consp current) (eq (car current) 'not))
+ (if (memq mode (cdr current)) current
+ (cons 'not (cons mode (cdr current)))))
+ ((consp current) (delq mode (copy-sequence current)))
+ (t current)))
+
+(defun cj/exclude-from-global-font-lock (&rest modes)
+ "Exclude MODES from `global-font-lock-mode'.
+Some major modes (dashboard, mu4e) paint their buffers with manual `face'
+text properties; global font-lock then strips those, leaving the buffer
+unthemed. Excluding the mode keeps its faces. Additive, so each caller
+contributes its own modes regardless of load order."
+ (dolist (mode modes)
+ (setq font-lock-global-modes
+ (cj/--font-lock-global-modes-excluding font-lock-global-modes mode))))
+
+(defun cj/format-region-with-program (program &rest args)
+ "Replace the current buffer with PROGRAM ARGS run over its contents, via argv.
+Runs PROGRAM (with ARGS) on the whole buffer through `call-process-region'
+-- no shell, so no quoting or word-splitting. The buffer is replaced only
+when PROGRAM exits zero; on a non-zero exit the buffer is left untouched and
+a `user-error' is signalled with the program's stderr text. Point is
+preserved as closely as the reformatted size allows. Returns t on success."
+ (let* ((point (point))
+ (src (current-buffer))
+ (out (generate-new-buffer " *format-out*"))
+ (status (apply #'call-process-region
+ (point-min) (point-max) program
+ nil out nil args)))
+ (unwind-protect
+ (if (and (integerp status) (zerop status))
+ (progn
+ (with-current-buffer src
+ (replace-buffer-contents out)
+ (goto-char (min point (point-max))))
+ t)
+ (user-error "%s failed: %s" program
+ (string-trim (with-current-buffer out (buffer-string)))))
+ (kill-buffer out))))
+
(provide 'system-lib)
;;; system-lib.el ends here
diff --git a/modules/system-utils.el b/modules/system-utils.el
index b3e038ef0..c76193a71 100644
--- a/modules/system-utils.el
+++ b/modules/system-utils.el
@@ -102,7 +102,7 @@ detached from Emacs."
(interactive)
(save-some-buffers)
(kill-emacs))
-(keymap-global-set "C-<f10>" #'cj/server-shutdown)
+(keymap-global-set "C-x C" #'cj/server-shutdown)
;;; ---------------------------- History Persistence ----------------------------
@@ -123,7 +123,8 @@ detached from Emacs."
read-char-history
face-name-history
bookmark-history
- file-name-history))
+ file-name-history
+ wttrin--location-history))
(put 'minibuffer-history 'history-length 50)
(put 'file-name-history 'history-length 50)
@@ -157,39 +158,12 @@ detached from Emacs."
;; Set scratch buffer to org-mode
(setopt initial-major-mode 'org-mode)
-;; Tint the *scratch* background a shade lighter than the default so it reads
-;; as the scratch buffer at a glance. Buffer-local face remap, recomputed from
-;; whatever theme is loaded.
-(require 'color)
-
-(defcustom cj/scratch-background-lighten 5
- "Percent to lighten the *scratch* background above the default background.
-Aesthetic; tune to taste."
- :type 'integer
- :group 'convenience)
-
-(defun cj/--scratch-lightened-background (bg)
- "Return BG lightened by `cj/scratch-background-lighten' percent.
-Return nil when BG is not a usable color string (e.g. `unspecified')."
- (when (and (stringp bg) (color-name-to-rgb bg))
- (color-lighten-name bg cj/scratch-background-lighten)))
-
-(defun cj/scratch-apply-background ()
- "Remap the *scratch* buffer background a shade lighter than the default."
- (when (get-buffer "*scratch*")
- (with-current-buffer "*scratch*"
- (let ((lighter (cj/--scratch-lightened-background
- (face-attribute 'default :background nil t))))
- (when lighter
- (face-remap-add-relative 'default :background lighter))))))
-
-;; Move cursor to end of scratch buffer on startup, and tint its background
+;; Move cursor to end of scratch buffer on startup
(add-hook 'emacs-startup-hook
(lambda ()
(when (get-buffer "*scratch*")
(with-current-buffer "*scratch*"
- (goto-char (point-max))))
- (cj/scratch-apply-background)))
+ (goto-char (point-max))))))
;;; --------------------------------- Dictionary --------------------------------
diff --git a/modules/term-config.el b/modules/term-config.el
index f9c126357..7fb02af2c 100644
--- a/modules/term-config.el
+++ b/modules/term-config.el
@@ -59,6 +59,7 @@
(defvar ghostel-mode-map)
(defvar ghostel-keymap-exceptions)
(defvar ghostel-buffer-name)
+(defvar ghostel--input-mode)
(defvar-keymap cj/term-map
:doc "Personal terminal command map.")
@@ -206,6 +207,44 @@ start of the line for the same column-0 reason."
(ghostel-copy-mode)
(beginning-of-line)))
+;; ----------------------------- copy-mode scroll ------------------------------
+;;
+;; C-<up> both enters copy-mode and scrolls up one line, so a single stroke
+;; lands in the scrollback already moving the right way. It joins
+;; `ghostel-keymap-exceptions' so it reaches Emacs instead of the pty. Only the
+;; up gesture is bound: C-<left>/<right> are readline word-motion at the shell
+;; prompt and must pass through, and the other directions have no copy-mode use.
+;; Pressed again while already in copy-mode it just moves up -- re-entering would
+;; reset the cursor (tmux's prefix-[ + C-a, or ghostel's toggle exiting).
+
+(defun cj/term--tmux-pane-in-copy-mode-p (pane-id)
+ "Return non-nil when tmux PANE-ID is currently displaying a mode.
+tmux's `pane_in_mode' is 1 while a pane is in any mode; copy-mode is the only
+mode this config enters. tmux failures are treated as nil."
+ (condition-case nil
+ (equal "1" (string-trim
+ (cj/term--tmux-output
+ "display-message" "-p" "-t" pane-id "#{pane_in_mode}")))
+ (error nil)))
+
+(defun cj/term-copy-mode-up ()
+ "Enter copy-mode if needed, then scroll up one line.
+A single C-<up> lands in the terminal's copy-mode already moving up. Pressed
+again while already in copy-mode it just moves up another line, so it never
+re-enters and resets the cursor. In tmux, writes the up-arrow escape sequence
+into the pty; without tmux, moves point up in the `ghostel-copy-mode' buffer."
+ (interactive)
+ (let ((pane (ignore-errors (cj/term--current-tmux-pane-id))))
+ (cond
+ (pane
+ (unless (cj/term--tmux-pane-in-copy-mode-p pane)
+ (cj/term-copy-mode-dwim))
+ (ghostel-send-string "\e[A"))
+ (t
+ (unless (eq (bound-and-true-p ghostel--input-mode) 'copy)
+ (cj/term-copy-mode-dwim))
+ (forward-line -1)))))
+
;; ----------------------------- ghostel package -------------------------------
(defun cj/turn-off-chrome-for-term ()
@@ -226,6 +265,15 @@ run its own project-named tmux session instead of a bare, auto-named one.
(ghostel-send-string "tmux\n"))))
(use-package ghostel
+ ;; PINNED at module 0.33.0 (ghostel-20260604.2049, the last pre-rework June-4
+ ;; build), installed directly into elpa/ rather than from MELPA. The 0.35.0-0.35.2
+ ;; native-PTY rework (worker threads + mutex-outside-read-loop) hard-crashes the
+ ;; whole Emacs process when a ghostel buffer is displayed: on Linux/glibc a
+ ;; SIGSETXID handler calls malloc while the main thread holds the arena lock
+ ;; (ghostel upstream #422); on macOS a recursive os_unfair_lock via
+ ;; run_window_change_functions (#423). `:ensure t' is satisfied by the present
+ ;; 0.33.0 dir and will NOT upgrade it -- do NOT `package-upgrade' ghostel until
+ ;; #422/#423 are fixed upstream, or it returns to the crashing 0.35.x.
:ensure t
:commands (ghostel)
:init
@@ -236,15 +284,20 @@ run its own project-named tmux session instead of a bare, auto-named one.
;; `add-to-list' alone updates the list but not the already-built map, so the
;; rebuild is what actually lets the key through to `ghostel-mode-map' / the
;; global map. C-; and F12 are the prefix + toggle; the modified arrows are
- ;; windmove (S-arrows, focus) and buffer-move (C-M-arrows, swap), which the
- ;; ai-term workflow expects to work from inside an agent buffer. F8, F10 and
- ;; C-F10 are global bindings (org agenda, music-playlist toggle, server
- ;; shutdown) that reach Emacs by falling through to the global map once the
- ;; semi-char map stops forwarding them.
+ ;; windmove (S-arrows, focus), buffer-move (C-M-arrows, swap), and copy-mode
+ ;; entry (C-<up> only, via `cj/term-copy-mode-up'), which the ai-term workflow
+ ;; expects to work from inside an agent buffer. C-<left>/<right> deliberately
+ ;; stay forwarding so readline word-motion works at the shell prompt. F8 and
+ ;; F10 are global bindings (org agenda, music-playlist toggle) that reach
+ ;; Emacs by falling through to the global map once the semi-char map stops
+ ;; forwarding them. (Server shutdown moved off C-F10 to C-x C, which is
+ ;; deliberately left forwarding to the terminal program inside an agent
+ ;; buffer.)
(with-eval-after-load 'ghostel
- (dolist (key '("C-;" "<f8>" "<f12>" "<f10>" "C-<f10>"
+ (dolist (key '("C-;" "<f8>" "<f12>" "<f10>"
"S-<up>" "S-<down>" "S-<left>" "S-<right>"
- "C-M-<up>" "C-M-<down>" "C-M-<left>" "C-M-<right>"))
+ "C-M-<up>" "C-M-<down>" "C-M-<left>" "C-M-<right>"
+ "C-<up>"))
(add-to-list 'ghostel-keymap-exceptions key))
(ghostel--rebuild-semi-char-keymap))
:hook
@@ -252,6 +305,12 @@ run its own project-named tmux session instead of a bare, auto-named one.
(ghostel-mode . cj/term-launch-tmux))
:custom
(ghostel-kill-buffer-on-exit t)
+ ;; Auto-download the prebuilt native module on first launch instead of the
+ ;; default `ask' prompt -- it fetches the platform release asset from GitHub
+ ;; (for the pinned 0.33.0 source this resolves to the matching v0.33.0 module).
+ ;; The compile-from-source fallback also works here: zig 0.15.2 is installed at
+ ;; /usr/local/bin/zig (see M-x ghostel-module-compile).
+ (ghostel-module-auto-install 'download)
;; Byte analog of the prior 100000-line vterm setting (~100 bytes/line) -- D7.
(ghostel-max-scrollback (* 10 1024 1024)))
@@ -264,18 +323,43 @@ run its own project-named tmux session instead of a bare, auto-named one.
;; which ai-term.el owns via F9.
(defcustom cj/term-toggle-window-height 0.7
- "Default fraction of frame height for the F12 terminal window."
+ "Default fraction of frame height for the F12 terminal window.
+Used as the size fallback when F12 docks the terminal as a bottom split."
:type 'number
:group 'term)
+(defcustom cj/term-toggle-window-width 0.5
+ "Default fraction of frame width for the F12 terminal window.
+Used as the size fallback when F12 docks the terminal as a right-side
+column (see `cj/--term-toggle-default-direction')."
+ :type 'number
+ :group 'term)
+
+(defun cj/--term-toggle-default-direction ()
+ "Return the default dock direction for the F12 terminal: `right' or `below'.
+Docks as a right-side column only when a side-by-side split would leave
+both panes at least `cj/window-dock-min-columns' wide (the terminal's
+share is `cj/term-toggle-window-width'); otherwise stacks below. See
+`cj/preferred-dock-direction'."
+ (cj/preferred-dock-direction (frame-width) cj/term-toggle-window-width))
+
+(defun cj/--term-toggle-default-size (direction)
+ "Return the default size fraction paired with DIRECTION for the F12 terminal.
+`cj/term-toggle-window-width' for `right', `cj/term-toggle-window-height'
+otherwise."
+ (if (eq direction 'right)
+ cj/term-toggle-window-width
+ cj/term-toggle-window-height))
+
(defvar cj/--term-toggle-last-direction nil
"Last user-chosen direction for the F12 terminal display.
Symbol: right, left, or below. `above' is never stored. nil means use the
default `below' for F12's traditional bottom split.")
(defvar cj/--term-toggle-last-size nil
- "Last user-chosen body size for the F12 terminal display.
-Positive integer: body-cols (right/left) or body-lines (below/above).
+ "Last user-chosen size for the F12 terminal display.
+Positive integer: body-cols (right/left) or total-lines (below/above) -- see
+`cj/window-replay-size' for why the vertical axis uses total, not body.
nil means fall back to `cj/term-toggle-window-height' as a fraction.")
(defun cj/--term-toggle-buffer-p (buffer)
@@ -306,9 +390,10 @@ FRAME defaults to the selected frame. Minibuffer is excluded."
(defun cj/--term-toggle-capture-state (window)
"Capture WINDOW's direction + body size into module-level state.
-Default direction is `below' to match F12's traditional bottom split."
+The default direction (used when WINDOW fills its frame) is the
+column-rule choice from `cj/--term-toggle-default-direction'."
(cj/window-toggle-capture-state
- window 'below
+ window (cj/--term-toggle-default-direction)
'cj/--term-toggle-last-direction
'cj/--term-toggle-last-size
'(right below left)))
@@ -316,11 +401,13 @@ Default direction is `below' to match F12's traditional bottom split."
(defun cj/--term-toggle-display-saved (buffer alist)
"Display-buffer action: split per saved direction and body size.
Delegates to `cj/window-toggle-display-saved' against the F12 state vars,
-falling back to `below' and `cj/term-toggle-window-height'."
- (cj/window-toggle-display-saved
- buffer alist
- 'cj/--term-toggle-last-direction 'below
- 'cj/--term-toggle-last-size cj/term-toggle-window-height))
+falling back to the column-rule default direction
+\(`cj/--term-toggle-default-direction') and its paired size."
+ (let ((dir (cj/--term-toggle-default-direction)))
+ (cj/window-toggle-display-saved
+ buffer alist
+ 'cj/--term-toggle-last-direction dir
+ 'cj/--term-toggle-last-size (cj/--term-toggle-default-size dir))))
(defun cj/--term-toggle-display-rule-list ()
"Return the `display-buffer-alist' entry list installed by F12.
@@ -408,12 +495,13 @@ Forwarding NUL makes C-Space behave like a terminal key."
(defun cj/term-install-keys ()
"Make `C-;' resolve as the personal keymap inside ghostel buffers, bind the
-F12 toggle, and forward C-SPC so it reaches the terminal (see
-`cj/term-send-C-SPC')."
+F12 toggle, forward C-SPC so it reaches the terminal (see
+`cj/term-send-C-SPC'), and bind C-<up> to enter copy-mode and scroll up."
(when (boundp 'ghostel-mode-map)
(keymap-set ghostel-mode-map "C-;" cj/custom-keymap)
(keymap-set ghostel-mode-map "<f12>" #'cj/term-toggle)
- (keymap-set ghostel-mode-map "C-SPC" #'cj/term-send-C-SPC)))
+ (keymap-set ghostel-mode-map "C-SPC" #'cj/term-send-C-SPC)
+ (keymap-set ghostel-mode-map "C-<up>" #'cj/term-copy-mode-up)))
(cj/term-install-keys)
(with-eval-after-load 'ghostel
diff --git a/modules/test-runner.el b/modules/test-runner.el
index 25c38f968..50d4f7e40 100644
--- a/modules/test-runner.el
+++ b/modules/test-runner.el
@@ -358,7 +358,6 @@ Returns a list of test name symbols defined in the file."
(insert-file-contents file)
(goto-char (point-min))
;; Find all (ert-deftest NAME ...) forms
-;; (while (re-search-forward "^\s-*(ert-deftest\s-+\\(\\(?:\\sw\\|\\s_\\)+\\)" nil t)
(while (re-search-forward "^[[:space:]]*(ert-deftest[[:space:]]+\\(\\(?:\\sw\\|\\s_\\)+\\)" nil t)
(push (match-string 1) test-names)))
test-names))
diff --git a/modules/tramp-config.el b/modules/tramp-config.el
index 23010b3e4..e3b835f1f 100644
--- a/modules/tramp-config.el
+++ b/modules/tramp-config.el
@@ -23,6 +23,15 @@
;;; Code:
+;; Silence byte-compiler "assignment to free variable" warnings for vars
+;; defined by lazily-loaded packages (tramp, dirtrack, magit). These are
+;; only set inside the use-package :config block, after the package loads.
+(defvar tramp-copy-size-limit)
+(defvar tramp-use-ssh-controlmaster-options)
+(defvar tramp-cleanup-idle-time)
+(defvar dirtrack-list)
+(defvar magit-git-executable)
+
(use-package tramp
:defer .5
:ensure nil ;; built-in
diff --git a/modules/transcription-config.el b/modules/transcription-config.el
index 566cea499..e00306d1e 100644
--- a/modules/transcription-config.el
+++ b/modules/transcription-config.el
@@ -173,13 +173,17 @@ TITLE and MESSAGE are strings. URGENCY is normal or critical."
:body message
:urgency (or urgency 'normal))))
-(defun cj/--start-transcription-process (audio-file &optional cleanup-file)
+(defun cj/--start-transcription-process (audio-file &optional cleanup-file output-base)
"Start async transcription process for AUDIO-FILE.
Returns the process object.
When CLEANUP-FILE is non-nil, delete that path once the transcription
sentinel fires (success or failure). Used by the video flow to drop
-the temp audio file produced by ffmpeg after transcription completes."
+the temp audio file produced by ffmpeg after transcription completes.
+
+OUTPUT-BASE, when non-nil, is the path the .txt/.log outputs derive from
+instead of AUDIO-FILE. The video flow passes the original video so the
+transcript lands alongside the source, not next to the temp /tmp audio."
(unless (file-exists-p audio-file)
(user-error "Audio file does not exist: %s" audio-file))
@@ -187,7 +191,7 @@ the temp audio file produced by ffmpeg after transcription completes."
(user-error "Not an audio file: %s" audio-file))
(let* ((script (cj/--transcription-script-path))
- (outputs (cj/--transcription-output-files audio-file))
+ (outputs (cj/--transcription-output-files (or output-base audio-file)))
(txt-file (car outputs))
(log-file (cdr outputs))
(buffer-name (format " *transcribe-%s*" (file-name-nondirectory audio-file)))
@@ -371,7 +375,9 @@ FILE.log with process logs. Uses the backend in
(cj/--extract-audio-from-video
path extracted
(lambda ()
- (cj/--start-transcription-process extracted extracted))))))))
+ ;; Pass the source video as the output base so the .txt/.log land
+ ;; alongside it, not next to the temp /tmp audio.
+ (cj/--start-transcription-process extracted extracted path))))))))
;;;###autoload
(defun cj/transcribe-media-at-point ()
diff --git a/modules/ui-config.el b/modules/ui-config.el
index 05448b3c5..32bd393f5 100644
--- a/modules/ui-config.el
+++ b/modules/ui-config.el
@@ -94,10 +94,9 @@ When `cj/enable-transparency' is nil, reset alpha to fully opaque."
(if cj/enable-transparency "enabled" "disabled")))
;; ----------------------------------- Cursor ----------------------------------
-;; The cursor uses the theme's cursor face. Buffer-state cursor coloring was
-;; removed -- a cursor that changed color by buffer state was confusing. The
-;; cj/buffer-status-state / cj/buffer-status-color classifier stays in
-;; user-constants.el; the modeline buffer-name indicator still uses it.
+;; The cursor uses the theme's cursor face. Buffer-state coloring (both the
+;; cursor and the modeline buffer-name) was removed -- changing color by buffer
+;; write state was more confusing than useful.
;; Don’t show a cursor in non-selected windows:
(setq cursor-in-non-selected-windows nil)
diff --git a/modules/ui-navigation.el b/modules/ui-navigation.el
index e9c9eaf26..cb0fc5697 100644
--- a/modules/ui-navigation.el
+++ b/modules/ui-navigation.el
@@ -75,14 +75,55 @@ resize -- each moves the active window's divider in the arrow's direction
"<up>" #'windsize-up
"<down>" #'windsize-down)
+(defun cj/window-pull-side (key)
+ "Map a `C-; b' arrow KEY to the side the revealed window opens on.
+The arrow names the edge the current window shrinks toward, so the new
+window opens on the *opposite* side and the current window keeps the
+arrow's edge: <down> -> above, <up> -> below, <left> -> right,
+<right> -> left. Returns nil for anything else."
+ (pcase key
+ ("<down>" 'above)
+ ("<up>" 'below)
+ ("<left>" 'right)
+ ("<right>" 'left)
+ (_ nil)))
+
+(defun cj/window--pull-away (side)
+ "Split the sole window so the previous buffer opens on SIDE.
+SIDE is one of above/below/left/right -- opposite the pressed arrow, so
+the current window keeps the arrow's edge. The new window is minimized
+to a sliver (the current window keeps almost the whole frame) and shows
+`other-buffer'; focus stays on the current window so the sticky arrows
+then shrink it step by step via `windsize', exactly as resizing an
+existing split does. No-op when SIDE is nil."
+ (when side
+ (let ((new (split-window (selected-window) nil side)))
+ (set-window-buffer new (other-buffer (current-buffer) t))
+ ;; Shrink the reveal to the smallest window Emacs allows (~2 lines, the
+ ;; mode line) so the current window keeps almost the whole frame; the
+ ;; sticky `windsize' arrows grow the reveal from there. `minimize-window'
+ ;; floors at `window-min-height' (4 by default), so bind it down to 1.
+ (let ((window-min-height 1))
+ (minimize-window new))
+ new)))
+
(defun cj/window-resize-sticky ()
"Resize the active window's divider in the just-pressed arrow's direction
-(via `windsize'), then keep `cj/window-resize-map' active so bare arrows keep
-nudging until any other key. Bound to `C-; b <left>/<right>/<up>/<down>'."
+\(via `windsize'), then keep `cj/window-resize-map' active so bare arrows keep
+nudging until any other key. Bound to `C-; b <left>/<right>/<up>/<down>'.
+
+When the selected window is the sole window in the frame there is no
+divider to move, so the first arrow instead splits a sliver away on the
+side opposite the arrow (`cj/window--pull-away'), revealing the previous
+buffer; the current window keeps almost the whole frame and the following
+arrows shrink it via `windsize', so it reads the same as resizing an
+existing split."
(interactive)
- (let ((cmd (keymap-lookup cj/window-resize-map
- (key-description (vector last-command-event)))))
- (when cmd (call-interactively cmd)))
+ (let ((key (key-description (vector last-command-event))))
+ (if (one-window-p)
+ (cj/window--pull-away (cj/window-pull-side key))
+ (let ((cmd (keymap-lookup cj/window-resize-map key)))
+ (when cmd (call-interactively cmd)))))
(set-transient-map cj/window-resize-map t))
;; ------------------------------ Window Splitting -----------------------------
@@ -118,15 +159,30 @@ window. Return the new window."
(set-window-buffer new buffer))
new))
+(defun cj/--split-from-dashboard-p (buffer-name)
+ "Return non-nil when BUFFER-NAME is the dashboard.
+Splitting from the dashboard shows *scratch* in the new window instead of
+the dashboard again."
+ (equal buffer-name "*dashboard*"))
+
+(defun cj/--split-companion-buffer ()
+ "Buffer to show in the new window after a C-x 2 / C-x 3 split.
+The dashboard, or the *scratch* buffer when splitting from the dashboard."
+ (if (cj/--split-from-dashboard-p (buffer-name))
+ (get-scratch-buffer-create)
+ (cj/--dashboard-buffer)))
+
(defun cj/split-below-with-dashboard ()
- "Split below and show the dashboard in the new window; stay in this one."
+ "Split below and show the companion buffer in the new window; stay in this one.
+The companion is the dashboard, or *scratch* when splitting from the dashboard."
(interactive)
- (cj/--split-show-buffer #'split-window-below (cj/--dashboard-buffer)))
+ (cj/--split-show-buffer #'split-window-below (cj/--split-companion-buffer)))
(defun cj/split-right-with-dashboard ()
- "Split right and show the dashboard in the new window; stay in this one."
+ "Split right and show the companion buffer in the new window; stay in this one.
+The companion is the dashboard, or *scratch* when splitting from the dashboard."
(interactive)
- (cj/--split-show-buffer #'split-window-right (cj/--dashboard-buffer)))
+ (cj/--split-show-buffer #'split-window-right (cj/--split-companion-buffer)))
(keymap-global-set "C-x 2" #'cj/split-below-with-dashboard)
(keymap-global-set "C-x 3" #'cj/split-right-with-dashboard)
@@ -227,5 +283,15 @@ With numeric prefix ARG, re-open the ARGth most-recently-killed file
:config
(winner-mode 1))
+;; ------------------------------- Cursor Jump (avy) ---------------------------
+;; Jump anywhere visible by typing a few of the target's characters, then the
+;; decision-tree key avy overlays. Fills the in-buffer motion gap that windmove
+;; (windows) and isearch (text) leave.
+
+(use-package avy
+ :bind (("C-:" . avy-goto-char-timer) ;; type chars, pause, jump to a match
+ ("M-g w" . avy-goto-word-1)
+ ("M-g l" . avy-goto-line)))
+
(provide 'ui-navigation)
;;; ui-navigation.el ends here
diff --git a/modules/ui-theme.el b/modules/ui-theme.el
index 8be3b4fdf..eb4efd9b5 100644
--- a/modules/ui-theme.el
+++ b/modules/ui-theme.el
@@ -139,12 +139,6 @@ Returns fallback-theme-name if no theme is active."
(message "Cannot save theme: %s is unwriteable" theme-file)
(message "%s theme saved to %s" (cj/get-active-theme-name) theme-file)))
-(defun cj/load-fallback-theme (msg)
- "Display MSG and load ui-theme fallback-theme-name.
-Used to handle errors with loading persisted theme."
- (cj/theme-disable-all)
- (cj/theme-load-fallback msg))
-
(defun cj/load-theme-from-file ()
"Apply the theme name contained in theme-file as the active UI theme.
If the theme is nil, it disables all current themes. If an error occurs
diff --git a/modules/user-constants.el b/modules/user-constants.el
index 1ee8ecda3..570b142fb 100644
--- a/modules/user-constants.el
+++ b/modules/user-constants.el
@@ -53,47 +53,6 @@ mail, chime, etc."
(defvar user-mail-address "c@cjennings.net"
"The user's email address.")
-;; ---------------------------- Buffer Status Colors ---------------------------
-
-(defconst cj/buffer-status-faces
- '((read-only . error) ; can't edit
- (overwrite . warning) ; overwrite mode
- (modified . warning) ; writeable, with unsaved changes
- (unmodified . success)) ; clean and writeable
- "Alist mapping a buffer state to the theme face whose foreground colors it.
-Shared by the cursor color (ui-config.el) and the modeline buffer-status
-indicator (modeline-config.el) so the two stay in sync and follow the active
-theme, rather than hard-coding hex colors.")
-
-(defun cj/buffer-status-state ()
- "Return the buffer-state symbol for the current buffer.
-One of `read-only', `overwrite', `modified', or `unmodified' -- the keys of
-`cj/buffer-status-faces'.
-
-A live ghostel terminal (in `ghostel-mode' and an input mode that forwards keys
--- semi-char / char / line) reports `unmodified' even though the buffer is
-read-only: keystrokes go to the terminal process, so from the user's side it is
-writeable and the read-only state would be misleading. ghostel's `copy' and
-`emacs' input modes are the exception -- there the buffer really is a read-only
-Emacs buffer the user navigates, so it falls through to `read-only'."
- (cond
- ((and (eq major-mode 'ghostel-mode)
- (not (memq (bound-and-true-p ghostel--input-mode) '(copy emacs))))
- 'unmodified)
- (buffer-read-only 'read-only)
- (overwrite-mode 'overwrite)
- ((buffer-modified-p) 'modified)
- (t 'unmodified)))
-
-(defun cj/buffer-status-color (state)
- "Return the foreground color of the theme face mapped to buffer STATE.
-Resolves STATE through `cj/buffer-status-faces' against the active theme. Nil
-when the state is unknown or its face has no concrete foreground (face-attribute
-returns the symbol `unspecified' there), so callers can skip cleanly."
- (when-let* ((face (alist-get state cj/buffer-status-faces))
- (fg (face-attribute face :foreground nil t)))
- (and (stringp fg) fg)))
-
;; --------------------------- Media File Extensions ---------------------------
(defvar cj/audio-file-extensions
@@ -195,15 +154,24 @@ Syncthing-synced `org-dir' — see the 2026-06-10 transport migration.")
(defvar gcal-file (expand-file-name "data/gcal.org" user-emacs-directory)
"The location of the org file containing Google Calendar information.
-Stored in .emacs.d/data/ so each machine syncs independently from Google Calendar.")
+Stored in .emacs.d/data/ so each machine syncs independently from
+Google Calendar.")
(defvar pcal-file (expand-file-name "data/pcal.org" user-emacs-directory)
"The location of the org file containing Proton Calendar information.
-Stored in .emacs.d/data/ so each machine syncs independently from Proton Calendar.")
+Stored in .emacs.d/data/ so each machine syncs independently from
+Proton Calendar.")
(defvar dcal-file (expand-file-name "data/dcal.org" user-emacs-directory)
"The location of the org file containing DeepSat Calendar information.
-Stored in .emacs.d/data/ so each machine syncs independently from Google Calendar.")
+Stored in .emacs.d/data/ so each machine syncs independently from
+Google Calendar.")
+
+(defvar keep-file (expand-file-name "data/keep.org" user-emacs-directory)
+ "The location of the generated org file containing Google Keep notes.
+A read-only view regenerated by `cj/keep-refresh'; edits here do not
+sync back to Keep. Stored in .emacs.d/data/ so each machine syncs
+independently.")
(defvar reference-file (expand-file-name "reference.org" org-dir)
"The location of the org file containing reference information.")
diff --git a/modules/vc-config.el b/modules/vc-config.el
index 654116c59..fcca7e07b 100644
--- a/modules/vc-config.el
+++ b/modules/vc-config.el
@@ -27,6 +27,27 @@
(require 'user-constants) ;; provides code-dir
(require 'keybindings) ;; provides cj/custom-keymap
+;; Forward declaration: cj/vc-map is defined later in this file (see
+;; `defvar-keymap' below) but referenced earlier in a use-package :bind form.
+(defvar cj/vc-map)
+
+;; External package variables (assigned in :config blocks of lazily-loaded
+;; packages, so not loaded at byte-compile time).
+(defvar forge-pull-notifications)
+(defvar forge-topic-list-limit)
+
+;; External package functions (from lazily-loaded packages).
+(declare-function git-gutter:next-hunk "git-gutter")
+(declare-function git-gutter:previous-hunk "git-gutter")
+(declare-function git-timemachine--start "git-timemachine")
+(declare-function git-timemachine--revisions "git-timemachine")
+(declare-function git-timemachine-show-revision "git-timemachine")
+(declare-function forge-current-repository "forge")
+(declare-function forge-create-issue "forge")
+
+;; Defined later in this file; referenced earlier in `cj/git-timemachine'.
+(declare-function cj/git-timemachine-show-selected-revision "vc-config")
+
;; ---------------------------- Magit Configuration ----------------------------
(use-package magit
diff --git a/modules/video-audio-recording.el b/modules/video-audio-recording.el
index 4c934ef17..1672529f7 100644
--- a/modules/video-audio-recording.el
+++ b/modules/video-audio-recording.el
@@ -174,9 +174,10 @@ Checks if process is actually alive, not just if variable is set."
(defun cj/recording-process-sentinel (process event)
"Sentinel for recording processes — handles unexpected exits.
PROCESS is the ffmpeg shell process, EVENT describes what happened.
-This is called by Emacs when the process changes state (exits, is killed, etc.).
-It clears the process variable and updates the modeline so the recording indicator
-disappears even if the recording crashes or is killed externally."
+This is called by Emacs when the process changes state (exits, is
+killed, etc.). It clears the process variable and updates the modeline
+so the recording indicator disappears even if the recording crashes or
+is killed externally."
(when (memq (process-status process) '(exit signal))
(cond
((eq process cj/audio-recording-ffmpeg-process)