diff options
Diffstat (limited to 'modules')
38 files changed, 1029 insertions, 898 deletions
diff --git a/modules/ai-config.el b/modules/ai-config.el index 20bf6ec88..97af1296d 100644 --- a/modules/ai-config.el +++ b/modules/ai-config.el @@ -233,6 +233,20 @@ Returns a string like \"Anthropic - Claude: claude-opus-4-7\"." (or backend-name "AI") (cj/gptel--model-to-string current-model)))) +(defun cj/--gptel-apply-model-selection (scope backend model backend-name) + "Set gptel BACKEND and MODEL, globally or buffer-locally per SCOPE. +SCOPE is \"global\" or \"buffer\"; any non-\"global\" value is buffer-local. +MODEL is a symbol. BACKEND-NAME is the display name for the confirmation. +Returns the confirmation message string." + (if (string= scope "global") + (progn + (setq gptel-backend backend) + (setq gptel-model model) + (format "Changed to %s model: %s (global)" backend-name model)) + (setq-local gptel-backend backend) + (setq-local gptel-model model) + (format "Changed to %s model: %s (buffer-local)" backend-name model))) + ;; Backend/model switching commands (defun cj/gptel-change-model () "Change the GPTel backend and select a model from that backend. @@ -257,14 +271,8 @@ necessary. Prompt for whether to apply the selection globally or buffer-locally. (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))))) + (message "%s" (cj/--gptel-apply-model-selection + scope backend model backend-name))))) (defun cj/gptel-switch-backend () "Switch the GPTel backend and then choose one of its models." diff --git a/modules/ai-conversations.el b/modules/ai-conversations.el index 839af9ad3..8061051a8 100644 --- a/modules/ai-conversations.el +++ b/modules/ai-conversations.el @@ -140,10 +140,7 @@ so a path exists to autosave to." (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)) + (cj/gptel--autosave-active-p)) (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)))))) @@ -359,10 +356,7 @@ enable autosave." (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)) + (when (cj/gptel--autosave-active-p) (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)))))) diff --git a/modules/ai-term.el b/modules/ai-term.el index 49d44d25e..25e56c508 100644 --- a/modules/ai-term.el +++ b/modules/ai-term.el @@ -391,21 +391,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 +433,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 +457,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 +546,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 +801,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. @@ -797,55 +886,7 @@ M-F9 (and C-S-F9) close 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 +926,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)))) diff --git a/modules/browser-config.el b/modules/browser-config.el index 4a2c54623..0312cdd18 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, diff --git a/modules/calendar-sync.el b/modules/calendar-sync.el index 13c74ca16..2ff535668 100644 --- a/modules/calendar-sync.el +++ b/modules/calendar-sync.el @@ -454,53 +454,55 @@ 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." (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) diff --git a/modules/calibredb-epub-config.el b/modules/calibredb-epub-config.el index a17bf8c91..6d5963515 100644 --- a/modules/calibredb-epub-config.el +++ b/modules/calibredb-epub-config.el @@ -241,6 +241,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 +279,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 +305,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. + ;; Darker sepia color (#E8DCC0) is easier on the eyes than pure white. + (let ((sepia "#E8DCC0")) + (face-remap-add-relative 'variable-pitch :family "Merriweather" :height 1.0 :foreground sepia) + (face-remap-add-relative 'default :family "Merriweather" :height 180 :foreground sepia) + (face-remap-add-relative 'fixed-pitch :height 180 :foreground sepia)) ;; 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..6f88b2018 100644 --- a/modules/chrono-tools.el +++ b/modules/chrono-tools.el @@ -66,6 +66,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 +93,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 +103,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/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..a2423742d 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/dirvish-config.el b/modules/dirvish-config.el index 8b672764b..c86f3d1bf 100644 --- a/modules/dirvish-config.el +++ b/modules/dirvish-config.el @@ -119,6 +119,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 +160,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 +268,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 @@ -489,8 +529,8 @@ 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) diff --git a/modules/dwim-shell-config.el b/modules/dwim-shell-config.el index ad17ea913..230a8532c 100644 --- a/modules/dwim-shell-config.el +++ b/modules/dwim-shell-config.el @@ -210,6 +210,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 +392,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 +482,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 +712,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..7712f48db 100644 --- a/modules/elfeed-config.el +++ b/modules/elfeed-config.el @@ -126,23 +126,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 +213,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 & < > " ' and ' -- the entities YouTube's +og:title meta tag emits. Decoded left-to-right, & first." + (let ((entities '(("&" . "&") ("<" . "<") (">" . ">") + (""" . "\"") ("'" . "'") ("'" . "'")))) + (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 +273,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 "&" "&" title)) - (setq title (replace-regexp-in-string "<" "<" title)) - (setq title (replace-regexp-in-string ">" ">" title)) - (setq title (replace-regexp-in-string """ "\"" title)) - (setq title (replace-regexp-in-string "'" "'" title)) - (setq title (replace-regexp-in-string "'" "'" 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) diff --git a/modules/erc-config.el b/modules/erc-config.el index 067b1e577..c0fa9c325 100644 --- a/modules/erc-config.el +++ b/modules/erc-config.el @@ -184,6 +184,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 +267,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) diff --git a/modules/font-config.el b/modules/font-config.el index 39d21364c..4821b89e1 100644 --- a/modules/font-config.el +++ b/modules/font-config.el @@ -153,36 +153,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.") + +(declare-function fontaine-set-preset "fontaine") - (defun cj/apply-font-settings-to-frame (&optional frame) - "Apply font settings to FRAME if not already configured. +(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 +198,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 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/jumper.el b/modules/jumper.el index 8941d5087..de270de66 100644 --- a/modules/jumper.el +++ b/modules/jumper.el @@ -106,20 +106,29 @@ 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)) + (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 +136,25 @@ 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--do-store-location () "Store current location in the next free register. @@ -208,9 +221,7 @@ Returns: \\='no-locations if no locations stored, ;; 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 @@ -248,9 +259,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)))) diff --git a/modules/mail-config.el b/modules/mail-config.el index 1ec41f213..08f50b12f 100644 --- a/modules/mail-config.el +++ b/modules/mail-config.el @@ -417,6 +417,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 @@ -425,24 +453,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/modeline-config.el b/modules/modeline-config.el index d669425d3..61dcb69c6 100644 --- a/modules/modeline-config.el +++ b/modules/modeline-config.el @@ -71,6 +71,16 @@ 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 @@ -82,10 +92,7 @@ Example: `my-very-long-name.el' → `my-ver...me.el'" 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)))) + 'local-map (cj/--modeline-click-map 'previous-buffer 'next-buffer)))) "Buffer name in the mode line. Truncates in narrow windows. Click to switch buffers.") @@ -195,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 @@ -215,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..99475fcde 100644 --- a/modules/mousetrap-mode.el +++ b/modules/mousetrap-mode.el @@ -144,30 +144,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 diff --git a/modules/music-config.el b/modules/music-config.el index be836429b..55eb47d25 100644 --- a/modules/music-config.el +++ b/modules/music-config.el @@ -94,6 +94,7 @@ (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) @@ -517,14 +518,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 +560,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) diff --git a/modules/org-agenda-config.el b/modules/org-agenda-config.el index 704eaac9a..d5d610f27 100644 --- a/modules/org-agenda-config.el +++ b/modules/org-agenda-config.el @@ -179,11 +179,18 @@ Only checks DIRECTORY/*/todo.org — does not recurse deeper." ;; builds the org agenda list from all agenda targets with caching. ;; agenda targets is the schedule, contacts, project todos, ;; inbox, and org roam projects. +(defun cj/--org-agenda-base-files () + "Return the fixed 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." + (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)) @@ -262,9 +269,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) @@ -424,7 +429,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-capture-config.el b/modules/org-capture-config.el index 18e130dc6..2f245185f 100644 --- a/modules/org-capture-config.el +++ b/modules/org-capture-config.el @@ -76,6 +76,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 +109,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)))) @@ -177,27 +186,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..8d722ad46 100644 --- a/modules/org-config.el +++ b/modules/org-config.el @@ -44,9 +44,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 diff --git a/modules/org-contacts-config.el b/modules/org-contacts-config.el index d558245b6..556530eb2 100644 --- a/modules/org-contacts-config.el +++ b/modules/org-contacts-config.el @@ -115,14 +115,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) diff --git a/modules/prog-general.el b/modules/prog-general.el index 53f20ce46..968032831 100644 --- a/modules/prog-general.el +++ b/modules/prog-general.el @@ -64,9 +64,21 @@ (defvar treesit-auto-recipe-list) ;; 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 +189,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 +232,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 +259,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,17 +275,14 @@ 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)) 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/system-lib.el b/modules/system-lib.el index ed98a476e..49bb6cd1a 100644 --- a/modules/system-lib.el +++ b/modules/system-lib.el @@ -164,5 +164,29 @@ contributes its own modes regardless of load order." (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/term-config.el b/modules/term-config.el index fe2ead409..0a7991409 100644 --- a/modules/term-config.el +++ b/modules/term-config.el @@ -279,18 +279,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) @@ -321,9 +346,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))) @@ -331,11 +357,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. 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/ui-navigation.el b/modules/ui-navigation.el index d8d7162e2..c099e0834 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 ----------------------------- 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 |
