Merge branch 'main' into quelpa

This commit is contained in:
Howard Abrams 2026-10-09 19:58:57 -07:00
commit 30aa4e5844
29 changed files with 1666 additions and 768 deletions

1
.gitignore vendored
View file

@ -11,3 +11,4 @@
/ha-theme-results.org
/support/dashboard
/.emacs.desktop
/.*-notes.org

View file

@ -6,7 +6,7 @@
A literate programming file for bootstraping my Emacs Configuration.
#+begin_src emacs-lisp :exports none
;;; bootstrap.el --- file for bootstraping my Emacs Configuration
;;; bootstrap.el --- file for bootstraping my Emacs Configuration -*- lexical-binding: t; -*-
;;
;; ██████████
;; ░░███░░░░░█
@ -51,7 +51,7 @@ Limit garbage collection before startup and then go back to the default value (8
(add-hook 'emacs-startup-hook
(lambda ()
(setq gc-cons-threshold (* 100 1024 1024))))
(setq gc-cons-threshold (* 200 1024 1024))))
#+END_SRC
** OS Path and Native Compilation
@ -167,7 +167,7 @@ Much of my more complicated code comes from my website essays and other projects
#+end_src
* Emacs Server Control
I actually run two instances of Emacs on some systems, where one instance has all my work-related projects, perspectives, and packages installed (like LSP), and my personal instance has other packages running (like IRC and Mail). I need a function that can make that distinction, and based on that, it will set =server-start= appropriately, so that =emacsclient= can call into the correct one.
I actually run two instances of Emacs on some systems, where one instance has all my work-related projects, perspectives, and packages installed (like the Language Server Protocol, LSP), and my personal instance has other packages running (like the Internet Relay Chat, IRC, and Mail). I need a function that can make that distinction, and based on that, it will set =server-start= appropriately, so that =emacsclient= can call into the correct one.
#+begin_src emacs-lisp
(defun ha-emacs-for-work? ()
"Return non-nil when the Emacs instance is for work.
@ -230,6 +230,7 @@ The following /defines/ the rest of my org-mode literate files, that I load late
"ha-org-publishing.org"
"ha-email.org"
"ha-aux-apps.org"))
"ha-code-notes.org"
"ha-dashboard.org"))
"List of org files that complete the hamacs project.")
#+end_src
@ -241,7 +242,7 @@ The list of /hamacs/ org-formatted files stored in =ha-hamacs-files= is selectiv
(if (not all)
ha-hamacs-files
(thread-last (rx ".org" string-end)
(thread-last (rx (not ".") (+? any) ".org" string-end)
(directory-files hamacs-source-dir nil)
(append ha-hamacs-files)
(--filter (not (string-match (rx "README") it)))

View file

@ -33,7 +33,8 @@ start some music to indicate we are working, and set a timer.
Call `ha-focus-break' when finished."
(interactive)
(ha-focus-countdown-timer 25 'ha-focus-break)
(ha-focus--command "tell application \"VLC\" to play")
(ha-focus--command "tell application \"VLC\" to play
tell application \"Shortcuts Events\" to run shortcut \"Focus On\"")
(if (eq major-mode 'org-mode)
(org-clock-in)
(org-clock-in-last))
@ -47,7 +48,8 @@ This also starts another break timer, that calls
`ha-focus-break-over' when finished."
(interactive)
(run-with-idle-timer 30 nil 'ha-focus-capture)
(ha-focus--command "tell application \"VLC\" to pause")
(ha-focus--command "tell application \"VLC\" to stop
tell application \"Shortcuts Events\" to run shortcut \"Focus Off\"")
(ha-focus-countdown-timer 5 'ha-focus-break-over)
(message "🍅 Time to take a break."))

View file

@ -23,7 +23,7 @@ A literate programming file configuring critical applications.
;; And tangle the file to recreate this one.
;;
;;; Code:
#+end_src
#+end_src
Can we call the following /applications/? I guess.
* Agentic Interface
@ -59,6 +59,9 @@ Installing Xenodium’s [[https://github.com/xenodium/agent-shell][agent-shell]]
(when (string-match-p "\\*agent-shell-diff\\*" (buffer-name))
(evil-emacs-state)))))
#+END_SRC
This also requires installing some command line support utilities, as well as [[https://agentclientprotocol.com/get-started/introduction][ACP]].
*** Notifications
When my /artificial intern/ completes a task, I have long since nipped out to the kitchen, put the kettle on ... buttering scones... and getting crumbs and bits of food out of those round brown straw mats that the teapot goes on.
@ -148,9 +151,12 @@ And point Emacs to it:
(use-package agent-shell
:config
(setq agent-shell-preferred-agent-config (agent-shell-anthropic-make-claude-code-config)
agent-shell-anthropic-claude-acp-command
`,(file-expand-wildcards "/opt/homebrew/Cellar/node/*/bin/claude-agent-acp")))
;; /opt/homebrew/Cellar/node/26.0.0/bin/claude-agent-acp
agent-shell-anthropic-authentication (agent-shell-anthropic-make-authentication :login t))
(setq agent-shell-anthropic-claude-acp-command
(if (file-exists-p "/opt/homebrew")
(file-expand-wildcards "/opt/homebrew/bin/claude-agent-acp")
'("/usr/local/bin/claude-agent-acp"))))
#+END_SRC
*** Cursor
@ -199,6 +205,12 @@ First install the [[https://github.com/google-gemini/gemini-cli][gemini-cli]]:
brew install gemini-cli
#+END_SRC
Or:
#+BEGIN_SRC sh
npm install -g @google/gemini-cli
#+END_SRC
And let’s make that the default now:
#+BEGIN_SRC emacs-lisp :tangle no
@ -206,36 +218,6 @@ And let’s make that the default now:
:config
(setq agent-shell-preferred-agent-config (agent-shell-google-make-gemini-config)))
#+END_SRC
** AI Code Interface
While the =agent-shell= offers a /vibe-codey/ interface to Chatbots, the [[https://github.com/tninja/ai-code-interface.el][ai-code-interface]] offers a more /programmatic/ interface.
#+BEGIN_SRC emacs-lisp
(use-package ai-code
:quelpa (:fetcher github :repo "tninja/ai-code-interface.el")
:config
;; use codex as backend, other options are 'claude-code, 'gemini,
;; 'github-copilot-cli, 'opencode, 'grok, 'cursor, 'kiro,
;; 'codebuddy, 'aider, 'eca, 'agent-shell, 'claude-code-ide,
;; 'claude-code-el
(ai-code-set-backend 'gemini)
;; Enable global keybinding for the main menu
(global-set-key (kbd "C-c a") #'ai-code-menu)
;; Optional: Enable @ file completion in comments and AI sessions
(ai-code-prompt-filepath-completion-mode 1)
;; Optional: Ask AI to run test after code changes, for a tighter build-test loop
;; (setq ai-code-auto-test-type 'ask-me)
;; Optional: In AI session buffers, SPC in Evil normal state triggers the prompt-enter UI
;; (with-eval-after-load 'evil (ai-code-backends-infra-evil-setup))
;; Optional: Set up Magit integration for AI commands in Magit popups
(with-eval-after-load 'magit
(ai-code-magit-setup-transients)))
#+END_SRC
* Git and Magit
Can not live without [[https://magit.vc/][Magit]], a Git porcelain for Emacs. I stole the bulk of this work from Doom Emacs.
#+begin_src emacs-lisp
@ -1048,28 +1030,6 @@ I do want to change a couple of bindings, as ~j~ to pull up a =completing-read=
(define-key dired-mode-map (kbd "n") 'evil-search-next)
(define-key dired-mode-map (kbd ",") 'major-mode-hydras/dired-mode/body)
#+end_src
* Annotations
Let's try [[https://github.com/bastibe/annotate.el][annotate-mode]], which allows you to drop "notes" and then move to them (yes, serious overlap with bookmarks, which we will return to).
#+begin_src emacs-lisp
(use-package annotate
:config
(ha-leader
"t A" '("annotations" . annotate-mode)
"n" '(:ignore t :which-key "notes")
"n a" '("toggle mode" . annotate-mode)
"n n" '("annotate" . annotate-annotate)
"n d" '("delete" . annotate-delete)
"n s" '("summary" . annotate-show-annotation-summary)
"n j" '("next" . annotate-goto-next-annotation)
"n k" '("prev" . annotate-goto-previous-annotation)
;; If a shift binding isn't set, it defaults to non-shift version
;; Use SPC N N to jump to the next error:
"n N" '("next error" . flycheck-next-error)))
#+end_src
Keep the annotations simple, almost /tag-like/, and then the summary allows you to display them.
* Keepass
Use the [[https://github.com/ifosch/keepass-mode][keepass-mode]] to view a /read-only/ version of my Keepass file in Emacs:
#+begin_src emacs-lisp

View file

@ -1,7 +1,7 @@
#+title: Capturing Notes with Org
#+author: Howard X. Abrams
#+date: 2020-09-18
#+tags: emacs org
#+TITLE: Capturing Notes with Org
#+AUTHOR: Howard X. Abrams
#+DATE: 2020-09-18
#+TAGS: emacs org
A literate programming file for configuring org for capturing notes.

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

631
ha-code-notes.org Normal file
View file

@ -0,0 +1,631 @@
#+TITLE: Taking Notes with Org
#+AUTHOR: Howard X. Abrams
#+DATE: 2026-07-14
#+FILETAGS: emacs hamacs
#+LASTMOD: [2026-07-14 Tue]
#+PROPERTY: foo baz
A literate programming file for configuring Emacs to take notes.
#+begin_src emacs-lisp :exports none
;;; ha-code-notes --- configuring Emacs to take notes. -*- lexical-binding: t; -*-
;;
;; © 2026 Howard X. Abrams
;; Licensed under a Creative Commons Attribution 4.0 International License.
;; See http://creativecommons.org/licenses/by/4.0/
;;
;; Author: Howard X. Abrams <http://gitlab.com/howardabrams>
;; Maintainer: Howard X. Abrams
;; Created: July 14, 2026
;;
;; While obvious, GNU Emacs does not include this file or project.
;;
;; *NB:* Do not edit this file. Instead, edit the original literate file at:
;; /Users/howard.abrams/src/hamacs/ha-code-notes.org
;; And tangle the file to recreate this one.
;;
;;; Code:
#+end_src
* Introduction
Seems silly to have a full set of instructions for /taking notes/ using Org-mode, because that is what it does, but this is a bit special.
When I [[file:ha-capturing-notes.org][capture notes]] with a link to some source code, the /destination/ is a *clocked in* task. Useful, but seems to require a dedicated task and some forethought. The following project pairs a “source code file” (which can be any file, actually) and a “notes file” with headers based on the function in the original file.
#+begin_src dot :file ha-code-notes-illustration.png :results file :exports results
digraph G {
rankdir=LR;
// Make to icons side-by-side
code_file [shape=note, label="def square(x):\l return x*x", fontname="Inconsolata", fixedsize=true, width=2.2, height=1, fontsize=10];
note_file [shape=note, label="* Square\lThoughts on function.\l", fixedsize=true, width=2.2, height=1];
// Create a couple of label to live _below_ the icons:
code_label [shape=plaintext, label="foobar.py"];
note_label [shape=plaintext, label=".foobar-notes.org"];
{ rank=same; code_file; code_label; }
{ rank=same; note_file; note_label; }
code_file -> code_label [style=invis];
note_file -> note_label [style=invis];
// Connect the code and note icons:
code_file -> note_file;
}
#+end_src
#+attr_org: :width 800px
[[file:ha-code-notes-illustration.png]]
This allows me to /wax poetic/ with a parallel, but separate org file. Of course, this requires adding the following to /every project’s =.gitignore= file/ (or in your =HOME= directory).
#+BEGIN_EXAMPLE
/.*-notes.org
#+END_EXAMPLE
If this isn’t good for you, check out [[https://github.com/agoodman42/montag][Montag]]. Same project, different approach using a single directory for all notes with [[https://www.orgroam.com/][org-roam]].
Let’s create a pattern for what a notes file is, and how to recognize them:
#+BEGIN_SRC emacs-lisp
(defconst ha-code-notes-rx (rx (optional "/")
"." (one-or-more (not "/")) "-notes.org" string-end))
(defun ha-code-notes-file (file &optional parent)
"Return a FILE's 'code notes' filename.
Prepend the PARENT if given."
(cond
((and parent (string-match-p (rx "/" string-end) parent))
(format "%s.%s-notes.org" parent file))
(parent (format "%s/.%s-notes.org" parent file))
(t (format ".%s-notes.org" file))))
#+END_SRC
Another feature when looking at the notes in the org buffer, is to hit the same key to return to the source code file referencing the notes.
# TODO Create custom settings to override default behavior.
* Helper Functions
While this project started simple, I’ve expanded the ideas, and this requires some custom helper functions.
** Relative Code Locations
Creating a note based on the filename, should be easy, but what if I made the header’s in this file reference a location in the original source code. For instance:
#+begin_example
foo.py .foo-notes.org
------ ------------------
def square(x): → * Square
  return x*x Notes about the function
#+end_example
We /could/ store the line number as an Org Property of the =foobar= header, but this would get out of sync as the =foo.py= source code changed.
What we want is to store the /function name/ as an Org Property, and some sort of offset from the function name. For instance:
#+begin_example
foo.py .foo-notes.org
------ ------------------
def square(x): → * Square
  "Return the square of x." :PROPERTIES:
  return x*x :XREF_NAME: square
:XREF_OFFSET: 2
:END:
Notes about the function
#+end_example
My immediate thought was to tie into the =xref= module for Emacs, but it doesn’t have a query function about what function or class/method the point is in. The following functions take advantage of =which-function= and =imenu= to programmatically give me /relative location/ and a =-goto= to return to that location.
This was far gnarlier than I originally thought, since IMenu only wants to /interactively/ walk down a tree, specifically the top-level class, then the methods inside that class, and even to the parameters of the method.
#+BEGIN_SRC emacs-lisp
(defun ha-code-notes-location ()
"Return point location relative from its nearest enclosing definition.
Can use later, even if intervening lines shift.
Returns a list for `ha-code-location-goto' to use, suitable for
`seq-let':
(file qualified-name offset)"
(let* ((here (point))
(entry (ignore-errors
(thread-last (imenu--make-index-alist t)
;; Flatten hierarchy labels with dot separators:
(ha-code-notes-location--flatten-index)
;; Filter to only entries that occur after point:
(seq-filter (lambda (e) (<= (cdr e) here)))
;; Sort the remaining entries by position
;; (since out flatten-index function
;; doesn't guarantee the order):
(seq-sort-by #'cdr #'>)
;; And the first entry on the list is our goal:
car))))
(unless entry
(error "No enclosing definition found for point"))
(list (buffer-file-name)
(car entry)
(- (line-number-at-pos here) (line-number-at-pos (cdr entry))))))
#+END_SRC
The needed /trick/ is to flatten this IMenu hierarchy using this recursive beauty:
#+BEGIN_SRC emacs-lisp
(defun ha-code-notes-location--flatten-index (alist &optional prefix)
"Flatten imenu ALIST into a list of (NAME . POSITION).
Where the name matches what which-function/imenu expect.
For instance:
(((\"foo_class\") (\"method_one\") (\"method_two\") ...) ...)
To:
((\"foo_class.method_one\" ...) (\"foo_class.method_two\" ...)...)
Called recursively, where PREFIX could be a class name, or other higher
abstraction when the nesting represents a real outline (Org, Markdown).
Entries tagged with `imenu-kind' or `breadcrumb-kind' property (as Eglot
nests a function's local variables for Python) are already a flat
namespace of functions/variables/constants, so their own names are kept
bare and not qualified by an enclosing function's name."
(mapcan
(lambda (entry)
(unless (or (null entry) (atom entry))
(let* ((raw-name (car entry))
(kind (and (stringp raw-name)
(or (get-text-property 0 'imenu-kind raw-name)
(get-text-property 0 'breadcrumb-kind raw-name))))
(name (if (stringp raw-name)
(replace-regexp-in-string
(rx space "(" (one-or-more alpha) ")" string-end)
"" (substring-no-properties raw-name))
(format "%s" raw-name)))
(value (cdr entry))
(qualified (if (and prefix (not kind)) (format "%s.%s" prefix name) name)))
(cond
;; Case 1: Nested submenu (list of alist entries). Eglot
;; never gives the container itself a position among its
;; children, as Org does; it stashes it in the
;; `imenu-region' text property instead, so recover it
;; here. Children only inherit QUALIFIED as their prefix
;; when this entry has no `imenu-kind' of its own -- i.e.
;; when the nesting is a real outline, not Eglot's flat
;; function/variable/constant tagging.
((and (listp value) (consp (car value)))
(append
(let ((region (and (stringp raw-name)
(get-text-property 0 'imenu-region raw-name))))
(when region (list (cons qualified (car region)))))
(ha-code-notes-location--flatten-index value (unless kind qualified))))
;; Case 2: Direct marker or integer position
((integer-or-marker-p value)
(list (cons qualified (if (markerp value) (marker-position value) value))))
;; Case 3: Overlay or element containing a position in car/cdr
((overlayp value)
(list (cons qualified (overlay-start value))))
((and (consp value) (integer-or-marker-p (car value)))
(list (cons qualified (if (markerp (car value))
(marker-position (car value))
(car value)))))
;; Fallback: ignore non-positional Imenu metadata entries
(t nil)))))
alist))
#+END_SRC
This flatten feature has been a pain in my side. An org-mode formatted file works well, for instance, running the following on this document:
#+BEGIN_SRC emacs-lisp :tangle no :results replace value raw :export both :wrap example
(ha-code-notes-location--flatten-index (imenu--make-index-alist t))
#+END_SRC
#+RESULTS:
#+begin_example
((*Rescan* . -99) (Introduction . 946) (Helper Functions.Relative Code Locations . 3719) (Helper Functions.Org Properties . 13220) (Helper Functions . 3592) (Write a Note.Return to Source Code . 22408) (Write a Note.Fringe Indicators for Notes . 24001) (Write a Note . 17005) (Technical Artifacts . 27464))
#+end_example
But running the same expression on a Python file (via Eglot) nests the local variables and parameters of each function as children in the index, each tagged with an =imenu-kind= text property on its name, e.g. a function like this:
#+begin_example
(#("parse_args" 0 10 (imenu-region (1245 . 1627) imenu-kind "Function" breadcrumb-region (1245 . 1627) breadcrumb-kind "Function"))
(#("argv" 0 4 (imenu-region (1260 . 1289) imenu-kind "Variable" ...)) . 1260)
(#("parser" 0 6 (imenu-region (1365 . 1371) imenu-kind "Variable" ...)) . 1365))
#+end_example
Naively flattening this treats =argv= and =parser= as if they were nested methods, producing useless entries like ~parse_args.argv~. Worse, the function itself never had its own position among its children (unlike Org, which gives a parent headline a self-pointing entry), so there was no way to jump straight to ~parse_args~ at all.
The fix: the presence of an =imenu-kind=/=breadcrumb-kind= property means the nesting is Eglot's flat function/variable/constant tagging, not a real outline -- so a child's name is never qualified by its parent's. When recursing into a nested submenu, the container's own position is recovered from its =imenu-region= text property, and the name is stripped of text properties. That turns the above into clean, bare entries for every name -- function, variable, and constant alike:
#+begin_example
((parse_args . 1245) (argv . 1260) (parser . 1365) (registry_credentials . 1630) ...)
#+end_example
Once inside a source file, we can jump to one of these /relative locations/:
#+BEGIN_SRC emacs-lisp
(defun ha-code-notes-location-goto (file name offset)
"Move point to the position described by relative location.
FILE is the filename to load, may be nil to use current buffer.
NAME is a function name or other definition, e.g. ClassName.method
OFFSET is the number of lines below NAME to position the point."
(when (and file (not (equal file (buffer-file-name))))
(find-file-other-window file))
(condition-case t
(ha-code-notes--location-goto name offset)
(message "Definition `%s' no longer found in %s" name file))
(ignore-errors
))
(defun ha-code-notes--location-goto (name &optional offset)
"Use `imenu' interface to goto NAME location.
If OFFSET given, move that many lines below."
(let* ((index (ha-code-notes-location--flatten-index (imenu--make-index-alist t)))
(entry (assoc name index)))
(when entry
(goto-char (cdr entry))
(when offset
(forward-line offset)))))
#+END_SRC
To verify that this works:
#+BEGIN_SRC emacs-lisp
(seq-let (file heading offset) (ha-code-notes-location)
(ha-code-notes-location-goto file heading offset))
#+END_SRC
The cool part of these functions is that this works in Org and Markdown files too!
** Org Properties
The =org-set-property= will set a key/value pair in the ~:PROPERTIES:~ section of the /current section/, but I want to add a buffer-level /property/ to an org-mode file, for instance:
#+begin_example
,#+TITLE: The title of the file
,#+PROPERTY: key1 value1
#+end_example
The tricky bit about this function is that if (in the above example) =key1= exists, we should /replace/ it, not add to it.
#+BEGIN_SRC emacs-lisp
(defun org-set-buffer-property (key value)
"Set a buffer-level property at the top of an Org file.
If KEY already refers to a #+PROPERTY, replace it.
Otherwise, insert it at the end of the Org header lines."
(let ((property-line (format "#+PROPERTY: %s %s" key value))
(magic-re (rx (group line-start "#+PROPERTY:"
(one-or-more space) (literal key) (one-or-more space)
(zero-or-more any)
line-end))))
(save-excursion
(goto-char (point-min))
(while (cond
((looking-at magic-re) (replace-match property-line t t))
((looking-at "#") (forward-line))
(t (insert property-line ?\n)))))))
#+END_SRC
Note: The =while= loop above has no body, as the =cond= is the predicate as it returns non-nil if it has more to process. This works because =replace-match= and =insert= return =nil=, while =forward-line= returns a non-nil value.
The function, =org-entry-get=, returns the value of a property /of the current heading/, and will walk up to parent sections too when passed a non-nil INHERIT argument. That handles everything except the buffer-level default set via =#+PROPERTY:=, which isn't attached to any heading, so we need a fallback for that case.
And we need the ability to read it. The Org API doesn’t have a function to read it without parsing the entire structure, so we use the =org-collect-keywords= for the =PROPERTY= value, and then parse the results.
#+BEGIN_SRC emacs-lisp
(defun org-get-property (property)
"Return the value of the Org PROPERTY.
Works even if the property is set in a parent section.
Return nil if the property is not found."
(defun org-get-buffer-property (property)
"Helper function that reads the current PROPERTY set in the buffer."
(when-let* ((properties (thread-last "PROPERTY"
(list) ; Requires a list of keywords
(org-collect-keywords)
(car) ; A list of lists? Get first entry
(cdr))) ; Remove the `PROPERTY' element
;; See if property matches the key in a "key value" pair:
(find-property-p (lambda (kv) (string= property (car (split-string kv)))))
;; Each entry in properties is a string with the key and value:
(entry (seq-find find-property-p properties)))
(substring entry (1+ (string-search " " entry)))))
;; Check the entry at point (and its ancestors) first; only look
;; for a buffer-level default if neither has it set:
(or (org-entry-get nil property t)
(org-get-buffer-property property)))
#+END_SRC
These two work like:
#+BEGIN_SRC emacs-lisp :tangle no
(org-set-buffer-property "foo" "bar")
(org-get-property "foo") ; ⟹ "bar"
;; Reset the value:
(org-set-buffer-property "foo" "baz")
(org-get-property "foo") ; ⟹ "baz"
;; Over shadow the global property with local one:
(org-set-property "foo" "boo")
(org-get-property "foo") ; ⟹ "boo"
;; And remove it:
(org-delete-property "foo")
(org-get-property "foo") ; ⟹ "baz"
#+END_SRC
* Write a Note
This function defines what the notes filename should look like, loads it in a side window, and adds a /back reference/ in the form of an org-mode =property=. Next it needs to either find the section that matches the function in the code we are writing about, or jumps to the bottom and creates it.
#+BEGIN_SRC emacs-lisp
(require 'which-func)
(defun ha-code-notes ()
"Open an Org file based on the current opened file.
The pattern for choosing the name of the org file is:
foobar.py --> .foobar-notes.org
The Org header will be the name of the function in the original source
code file. This means you have one note section per function, which
should be fine in practice because functions are small and succinct,
right?"
(interactive)
(let* ((orig-file (buffer-file-name))
(orig-parent (file-name-directory orig-file))
(orig-base (file-name-base orig-file))
;; Keep in mind the `orig-parent' has a final slash, so the
;; initial . here marks it as hidden:
(note-file (ha-code-notes-file orig-base orig-parent))
(header (which-function))
(offset (ha-code-notes-defun-rel-line)))
;; With the above local variables defined, we can open the file in
;; a window (pane) to the side:
(find-file-other-window note-file)
(org-set-buffer-property "XREF" orig-file)
;; Create a new section in the notes file:
(ha-code-notes-insert-heading header offset)
;; (when-let ((buf (find-buffer-visiting orig-file)))
;; (with-current-buffer buf
;; (ha-code-notes--fringe)))
))
#+END_SRC
Use the builtin autoinsert feature to inject a basic template at the beginning of the notes file when we first create the notes file:
#+BEGIN_SRC emacs-lisp
(use-package autoinsert
:config
(define-auto-insert
(cons ha-code-notes-rx "Org Notes Template")
'("Short description: "
"#+TITLE: "
(s-titleized-words (s-replace-regexp (rx (any "-" "_")) " "
(file-name-base (buffer-file-name))))
\n
"#+DATE:" (format-time-string "%Y-%m-%d %a")
\n
"#+LASTMOD:" (format-time-string "[%Y-%m-%d %a]")
\n \n)))
#+END_SRC
What is the offset?
#+BEGIN_SRC emacs-lisp
(defun ha-code-notes-defun-rel-line ()
"Return the number of lines between point and the start of the current defun."
(let ((orig-line (line-number-at-pos)))
(save-excursion
(if (provided-mode-derived-p major-mode '(text-mode))
(org-previous-visible-heading 1)
(beginning-of-defun))
(- orig-line (line-number-at-pos)))))
#+END_SRC
If a heading matching the function already exists, we add a new subheading under it to record this particular visit. The real purpose of this, is to store a relative line number to another section of the function. Its title is left blank, so we hand off to the user to name it, then jump to the body once they press RET or TAB:
#+BEGIN_SRC emacs-lisp
(defun ha-code-notes-insert-heading (header offset)
"Insert heading recording OFFSET under heading matching HEADER.
Finds the top-level Org heading whose `XREF_NAME' property equals
HEADER. If none exists, inserts one at the end of the buffer.
Otherwise, looks inside that heading's subtree for an entry whose
`XREF_LINE' property already equals OFFSET: if found, this visit
was already recorded, so we jump to its body instead of inserting
a duplicate. Otherwise, inserts a new level-2 subheading at the
end of the section.
Before inserting a new subheading, it will prompt for the value."
(goto-char (point-min))
(let ((top-level (org-find-property "XREF_NAME" header)))
(if (not top-level)
;; No section for this function yet: create one at the end.
(progn
(goto-char (point-max))
(ha-code-notes--insert-heading header offset 1))
;; Found the function's section; look inside it for this
;; exact visit before deciding to insert a new subheading.
(goto-char top-level)
(let ((visit (save-excursion
(save-restriction
(org-narrow-to-subtree)
(org-find-property "XREF_LINE" (number-to-string offset))))))
(if visit
(progn (goto-char visit) (org-end-of-subtree))
(ha-code-notes--insert-heading "" offset 2))))))
#+END_SRC
The above function require this helper function to insert the initial text of the section and its header:
#+BEGIN_SRC emacs-lisp
(defun ha-code-notes--insert-heading (header offset level)
"Insert a section with headline, HEADER."
(when-let ((section-label (read-string "Section header: " header)))
;; Make sure our new heading is at the end of current section:
(org-insert-heading '(4) nil level)
(insert (format "%s" section-label))
(org-insert-property-drawer)
;; In case we want to change the section header name, we store
;; the name of the function that led us here as a property:
(when (= level 1)
(org-set-property "XREF_NAME" header))
(org-set-property "XREF_LINE" (number-to-string offset))
(org-end-of-subtree)))
#+END_SRC
** Return to Source Code
If we are /inside/ one of these note files, let’s have a quick way to return back to the original “code” file:
#+BEGIN_SRC emacs-lisp
(defun ha-code-notes-return ()
"Return to the code referenced in the notes.
Essentially pretends we have a backlink without a database. Reads
XREF_LINE and XREF_NAME off the entry containing point, rather than
just the first match anywhere in the buffer, so returning from a
subheading lands on the line for that particular visit."
(interactive)
(let* ((filename (org-get-property "XREF"))
(f-offset (when-let ((line (org-entry-get nil "XREF_LINE")))
(string-to-number line)))
(function (or (org-entry-get nil "XREF_NAME" t) (which-function))))
;; If the property is set, load that file (which jumps to the
;; buffer if it is displayed), otherwise, we assume the previous
;; buffer contains it:
(if filename
(find-file-other-window filename)
(switch-to-prev-buffer))
(ha-code-notes-location-goto filename function f-offset)))
#+END_SRC
And give us keybinding that will either go to the notes (if we are in some code) or return to the source code (if we are in our notes):
#+BEGIN_SRC emacs-lisp
(defun ha-code-notes-dwim ()
"Open the notes buffer, or return to the code."
(interactive)
(when (buffer-file-name)
(if (string-match ha-code-notes-rx (buffer-file-name))
(ha-code-notes-return)
(ha-code-notes))))
(ha-leader "n c" '("code notes" . ha-code-notes-dwim))
#+END_SRC
** Fringe Indicators for Notes
A code file with an associated notes file is easy to forget about. Let's mark, in the fringe, every line that has a note, so we notice it as we scroll past:
#+BEGIN_SRC emacs-lisp
(define-fringe-bitmap 'ha-code-notes-bitmap
[#b00001100
#b00010110
#b00010111
#b00101110
#b00101110
#b01011100
#b01011100
#b10110000
#b10010000
#b11100000]
nil nil 'center)
(defface ha-code-notes-face
'((t :foreground "yellow"))
"Face for the fringe marker indicating a line has an associated note.")
(defvar-local ha-code-notes--fringe-overlays nil
"Overlays marking lines in this buffer that have notes in the paired notes file.")
(defun ha-code-notes--fringe ()
"Mark, in the fringe, every line in this buffer that has a note.
Notes live in the paired `.BASE-notes.org' file (see
`ha-code-notes') as headings whose XREF property matches this
file, XREF_NAME names the function (inherited by subheadings from
their parent), and XREF_LINE is a line offset from that function's
start, computed by `ha-code-notes-defun-rel-line'. We resolve each
pair back to an absolute line via `ha-code-notes-location-goto', since the function
may have moved since the note was taken."
(mapc #'delete-overlay ha-code-notes--fringe-overlays)
(setq ha-code-notes--fringe-overlays nil)
(let* ((orig-file (buffer-file-name))
(note-file (and orig-file
(ha-code-notes-file
(file-name-directory orig-file)
(file-name-base orig-file))))
notes)
;; Only run if this is an actual file AND its notes file exists:
(when (and orig-file
note-file
(file-exists-p note-file)
(not (string-match-p ha-code-notes-rx orig-file)))
(with-temp-buffer
(insert-file-contents note-file)
(org-mode)
(org-map-entries
(lambda ()
(when (equal (org-get-property "XREF") orig-file)
(when-let ((line (org-entry-get nil "XREF_LINE")))
(push (cons (org-entry-get nil "XREF_NAME" t)
(string-to-number line))
notes))))))
(dolist (note notes)
(save-excursion
(ha-code-notes-location-goto nil (car note) (cdr note))
(let ((ov (make-overlay (point) (point))))
(overlay-put ov 'before-string
(propertize "x" 'display
'(left-fringe ha-code-notes-bitmap
ha-code-notes-face)))
(push ov ha-code-notes--fringe-overlays)))))))
(add-hook 'find-file-hook #'ha-code-notes--fringe)
#+END_SRC
New notes and edited notes should refresh the markers too, so we hook into saving a notes file, and refresh right after inserting a new XREF property drawer:
#+BEGIN_SRC emacs-lisp
(defun ha-code-notes--fringe-notes-refresh-all ()
"Refresh fringe note markers in every buffer after saving a notes file."
(when (string-match ha-code-notes-rx (buffer-file-name))
(dolist (buf (buffer-list))
(with-current-buffer buf
(when buffer-file-name
(ha-code-notes--fringe))))))
(add-hook 'after-save-hook #'ha-code-notes--fringe-notes-refresh-all)
#+END_SRC
* Technical Artifacts :noexport:
Let's =provide= a name so we can =require= this file:
#+begin_src emacs-lisp :exports none
(provide 'ha-code-notes)
;;; ha-code-notes.el ends here
#+end_src
#+DESCRIPTION: configuring Emacs to take notes.
#+PROPERTY: header-args:sh :tangle no
#+PROPERTY: header-args:emacs-lisp :tangle yes
#+PROPERTY: header-args :results none :eval no-export :comments no mkdirp yes
#+OPTIONS: num:nil toc:nil todo:nil tasks:nil tags:nil date:nil
#+OPTIONS: skip:nil author:nil email:nil creator:nil timestamp:nil
#+INFOJS_OPT: view:nil toc:nil ltoc:t mouse:underline buttons:0 path:http://orgmode.org/org-info.js

View file

@ -963,16 +963,6 @@ I like the idea of dropping returnable bookmarks, but with /good defaults/ for t
(bookmark-set label)))
#+END_SRC
The built-in behavior doesn’t honor either /projects/ or /perspectives/, but I use [[https://codeberg.org/ideasman42/emacs-bookmark-in-project][bookmark-in-project]] package to make a =project=-specific bookmarks and use that to jump to only bookmarks in the current project.
#+BEGIN_SRC emacs-lisp
(use-package bookmark-in-project
:bind
(("C-x r m" . bookmark-in-project-toggle)
("C-x r M" . ha-bookmark-set)))
#+END_SRC
** Minor Keybinding Annoys
I like ~C-a~ to go to the beginning of the line, but what about getting to the beginning of text on that line? In Evil, you have ~^~ for beginning of line, and ~0~ for first text. Why not have ~C-a~ toggle between them both:

View file

@ -58,43 +58,13 @@ Let's install and load some of packages from the [[https://github.com/hlissner/d
doom-modeline-modal 'evil
doom-modeline-lsp-icon t
doom-modeline-percent-position nil)
;; Weird bug:
(defvar helm-ag-show-status-function nil "Workaround")
(doom-modeline-mode 1))
#+end_src
After reading [[https://blog.davep.org/2026/06/12/simplifying-my-mode-line.html][this essay]], I decided to try
#+BEGIN_SRC emacs-lisp :tangle no
(use-package mood-line
:ensure t
:custom
(mood-line-glyph-alist mood-line-glyphs-fira-code)
:config
(mood-line-mode 1)
(setq mood-line-format
(mood-line-defformat
:padding ""
:left
(((mood-line-segment-modal) . " ")
((mood-line-segment-anzu) . " ")
((mood-line-segment-buffer-status) . " ")
((mood-line-segment-buffer-name) . " ")
" ")
:right
(((mood-line-segment-process) . " ")
((mood-line-segment-major-mode) . " ")
((mood-line-segment-misc-info) . " ")
((mood-line-segment-vc) . " ")
((mood-line-segment-checker) . " "))))
(setq mood-line-segment-modal-evil-state-alist
`((normal ,(nerd-icons-mdicon "nf-md-alpha_n_circle") . font-lock-keyword-face)
(insert ,(nerd-icons-mdicon "nf-md-alpha_i_circle") . font-lock-variable-name-face)
(visual ,(nerd-icons-mdicon "nf-md-alpha_v_circle") . font-lock-string-face)
(replace ,(nerd-icons-mdicon "nf-md-alpha_r_circle") . font-lock-type-face)
(motion ,(nerd-icons-mdicon "nf-md-alpha_m_circle") . font-lock-constant-face)
(emacs ,(nerd-icons-mdicon "nf-md-alpha_r_circle") . font-lock-constant-face))))
#+END_SRC
* Window Dimmer
To make the active window /more noticeable/, we /dim/ the in-active windows with the [[https://github.com/gonewest818/dimmer.el][dimmer project]].
@ -571,17 +541,18 @@ The nerd font package takes a popular font like "Iosevka" and jams a bunch of th
** Symbols and Emojis
Display these two symbols as one character, as using [[Ligatures]] often stretches wider, and the following are nice to be collapsed:
Display these two symbols as one character, as using [[Ligatures]] often stretches wider, and the following are nice to be collapsed into a single glyph:
#+begin_src emacs-lisp
(add-hook 'text-mode-hook (lambda ()
(dolist (pair '(("!?" . "‽")
("ae" . "æ")
("..." . "…") ; ??
("??" . "⁇")
;; ("<<" . "«")
;; (">>" . "»")
("AE" . "Æ")))
("<<" . "«")
(">>" . "»")
(":-)" . "🙂")
(":-D" . "😃")
(";-)" . "😉")
("..." . "…")))
(push pair prettify-symbols-alist))))
#+end_src

View file

@ -36,7 +36,7 @@ Next type ~s~ to view and organize mail I've never seen before. We need to focus
- ~P~ :: receipts go to this *Paper Trail*, which takes a *tag* as the name of the store
- ~f~ :: mailing lists and other email that might be nice to read go to *The Feed*
** Email Addresses
* Email Addresses
The configuration files below expect email addresses (I store passwords and other encrypted information elsewhere). These email addresses are /not/ private, but I figured I would annoy any screenscraping spam-inducing crawlers out there, while still allowing others to follow my lead on configuring Emacs and Email.
#+name: email-address-1
@ -54,19 +54,18 @@ The configuration files below expect email addresses (I store passwords and othe
(rot13-string "ubjneq@shmmlgbnfg.pbz")
#+end_src
To use these, we set the =:noweb yes= (to pull in the /name/ of the code block) but put a pair of parens after the name to have it evaluated. For instance, the configuration for sending mail through the MUA in Emacs:
To use these, we set the =:noweb yes= (to pull in the /name/ of the code block) but put a pair of parens after the name to have it evaluated. For instance, the configuration for sending mail through the MUA in Emacs. Note that port 465 requires implicit SSL/TLS (not STARTTLS), so we set =smtpmail-stream-type= to ~ssl~ and let =auth-source= (e.g. =~/.authinfo.gpg=) supply the credentials for =<<email-address-1>>=:
#+begin_src emacs-lisp :noweb yes
(setq send-mail-function 'smtpmail-send-it
message-send-mail-function 'smtpmail-send-it
smtpmail-starttls-credentials '(("smtp.gmail.com" 587 nil nil))
smtpmail-auth-credentials `(("smtp.gmail.com" 587 ,<<email-address-1>> nil))
smtpmail-default-smtp-server "smtp.gmail.com"
smtpmail-smtp-server "smtp.gmail.com"
smtpmail-smtp-service 587)
smtpmail-smtp-server "smtp.mailbox.org"
smtpmail-smtp-service 465
smtpmail-stream-type 'ssl)
#+end_src
* Sending Mail
#+BEGIN_SRC emacs-lisp
(require 'smtpmail)
(require 'smtpmail)
#+END_SRC
* Installation and Basic Configuration
@ -176,6 +175,7 @@ There are global settings:
#+begin_src conf :tangle ~/.mbsyncrc :noweb yes
# Note: We now tangle this file from ~/src/hamacs/ha-email.org
Create Both
Expunge Both
SyncState *
MaxMessages 100
Sync All # New ReNew Flags
@ -187,37 +187,41 @@ The file generally can have a =Pass= entry for the encrypted passcode, but to sh
#+begin_src conf :tangle ~/.mbsyncrc :noweb yes
# PERSONAL ACCOUNT
IMAPAccount personal
Host imap.gmail.com
User <<email-address-1()>> # Substitute your own email address here
PassCmd "gpg --quiet --for-your-eyes-only --no-tty --decrypt ~/.mailpass-personal.gpg"
SSLType IMAPS
AuthMechs LOGIN
IMAPStore personal-remote
Account personal
Host imap.mailbox.org
User <<email-address-1()>> # Substitute your own email address here
PassCmd "gpg --quiet --for-your-eyes-only --no-tty --decrypt ~/.mailpass-personal.gpg"
SSLType STARTTLS
MaildirStore personal-local
Path ~/.mail/personal/
Inbox ~/.mail/personal/INBOX
Flatten .
SubFolders Verbatim
Channel personal-inbox
Far :personal-remote:
Near :personal-local:
Patterns * !"[Gmail]/Drafts" !"[Gmail]/Spam"
Expunge Both
# Patterns "inbox"
# ExpireUnread no
Channel mailbox
Master :mailbox-remote:
Slave :mailbox-local:
Patterns * !Archives
Channel personal-sent
Far :personal-remote:"[Gmail]/Sent Mail"
Near :personal-local:sent
ExpireUnread yes
Channel personal-trash
Far :personal-remote:"[Gmail]/Trash"
Near :personal-local:trash
ExpireUnread yes
## Channel personal-inbox
## Far :personal-remote:
## Near :personal-local:
## # Patterns * !"[Gmail]/Drafts" !"[Gmail]/Spam"
## Expunge Both
## # Patterns "inbox"
## # ExpireUnread no
##
## Channel personal-sent
## # Far :personal-remote:"[Gmail]/Sent Mail"
## Near :personal-local:sent
## ExpireUnread yes
##
## Channel personal-trash
## # Far :personal-remote:"[Gmail]/Trash"
## Near :personal-local:trash
## ExpireUnread yes
#+end_src
I have other email accounts that could use or ignore.
@ -745,7 +749,7 @@ The idea of linking org documents to email could be nice, however, the =ol-notmu
To use, read a message and save a link to it with ~SPC o l~. Next, in an org document, create a link with ~, l~. Now, you can return to the message from that document with ~, o~. Regardless, I may need to store a local copy when I upgrade Org.
* Display Configuration
Using the [[https://github.com/seagle0128/doom-modeline][Doom Modeline]] to add notifications:
#+begin_src emacs-lisp
#+begin_src emacs-lisp :tangle no
(use-package doom-modeline
:config
(setq doom-modeline-mu4e t))

View file

@ -361,10 +361,15 @@ And the collection of useful operations:
"b C-g" '(keyboard-escape-quit :which-key t))
#+end_src
* Bookmarks
Expand on my [[file:ha-config.org::*Bookmarks][Bookmarks]] with the following key sequences:
The built-in behavior of bookmarks doesn’t honor either /projects/ or /perspectives/, but the [[https://codeberg.org/ideasman42/emacs-bookmark-in-project][bookmark-in-project]] package makes =project=-specific bookmarks.
This expands on my global [[file:ha-config.org::*Bookmarks][Bookmarks]]:
#+begin_src emacs-lisp
(use-package bookmark-in-project
:bind
(("C-x r m" . bookmark-in-project-toggle)
("C-x r M" . ha-bookmark-set))
:config
(ha-leader
;; Set or delete a bookmark associated with project:
@ -376,6 +381,31 @@ Expand on my [[file:ha-config.org::*Bookmarks][Bookmarks]] with the following ke
"b <down>" '("next mark" . bookmark-in-project-jump-next)
"b <up>" '("previous mark" . bookmark-in-project-jump-previous)))
#+end_src
** Annotations
Let's try [[https://github.com/bastibe/annotate.el][annotate-mode]], which allows you to drop "notes" displayed /inline/ with the buffer.
#+begin_src emacs-lisp
(use-package annotate
:config
(ha-leader
"t A" '("annotations" . annotate-mode)
"n" '(:ignore t :which-key "notes")
"n a" '("toggle mode" . annotate-mode)
"n n" '("annotate" . annotate-annotate)
"n d" '("delete" . annotate-delete-annotation)
;; Can't seem to get anything useful out of this function:
"n s" '("summary" . annotate-show-annotation-summary)
;; The next and previous only work for the current file:
"n j" '("next" . annotate-goto-next-annotation)
"n k" '("prev" . annotate-goto-previous-annotation)))
#+end_src
Keep the annotations simple, almost /tag-like/, and then the summary doesn’t wrap. For longer notes, see my [[file:ha-capturing-notes.org::*Code Notes][Code Notes]] section.
The annotations are stored as s-expressions in the file, =~/.emacs.d/annotations=. Let’s see how well this scales.
* Centering
After reading [[https://mbork.pl/2024-04-15_Improving_recenter-top-bottom_and_reposition-window][this essay]], I got to thinking that it would be nice to position the text in a buffer /near the top/, but show context based on some specific, textual /things/. My thought is to have a function that prompts for the thing (like the current paragraph, function, etc), but also create thing-specific functions.

View file

@ -122,7 +122,7 @@ And a quick shortcuts to call it:
#+end_src
* Display Configuration
Using the [[https://github.com/seagle0128/doom-modeline][Doom Modeline]] to add notifications:
#+begin_src emacs-lisp
#+begin_src emacs-lisp :tangle no
(setq doom-modeline-irc t
doom-modeline-irc-stylize 'identity)
#+end_src

View file

@ -145,7 +145,7 @@ Let's define the clipboard for a Mac. The challenge here is that we need to bina
(shell-command-with-exit-code "osascript" "-e" "the clipboard as \"HTML\"")
(if (= 0 exit-code)
(list :html (ha-convert-applescript-to-html contents))
(list :text (shell-command-to-string "osascript -e 'the clipboard'")))))
(list :text (string-replace "\r" "\n" (shell-command-to-string "osascript -e 'the clipboard'"))))))
(defun ha-convert-applescript-to-html (packed-contents)
"Applescript's clipboard returns the contents in a packed array.

View file

@ -2,7 +2,7 @@
#+author: Howard Abrams
#+date: 2024-07-07
#+filetags: emacs hamacs
#+lastmod: [2025-02-20 Thu]
#+lastmod: [2026-09-22 Tue]
A literate programming file for literate programming in Emacs Org Files.
@ -19,16 +19,15 @@ A literate programming file for literate programming in Emacs Org Files.
;;
;; While obvious, GNU Emacs does not include this file or project.
;;
;; *NB:* Do not edit this file. Instead, edit the original literate file at:
;; ~/src/hamacs/ha-org-literate.org
;; Using `find-file-at-point', and tangle the file to recreate this.
;;
;;; Commentary:
;;
;; This file contains a collection of functions to easy some of the
;; sharp edges when doing literate programming in Org files.
;;
;; *NB:* Do not edit this file. Instead, edit the original
;; literate file at:
;; ~/src/hamacs/ha-org-literate.org
;; And tangle the file to recreate this one.
;;
;;; Code:
#+end_src
* Introduction
@ -51,7 +50,7 @@ Since we are using Emacs, the downsides of using a literate approach (even for p
** Surround with Org Block
This simple change allows me to highlight any text, and surround it in an org block. We
#+BEGIN_SRC snippet :tangle ~/.emacs.d/snippets/org-mode/surround-org-block
#+BEGIN_SRC snippet :tangle ~/.emacs.d/snippets/org-mode/surround-org-block :eval none
# name: surround-org-block
# --
,#+BEGIN_${1:SRC} ${2:emacs-lisp} $0
@ -90,7 +89,7 @@ Actually, I probably want all the parameters (if any) to come along for the ride
This allows us to now split a block into two parts:
#+BEGIN_SRC snippet :tangle ~/.emacs.d/snippets/org-mode/split-org-block
#+BEGIN_SRC snippet :tangle ~/.emacs.d/snippets/org-mode/split-org-block :eval none
,# -*- mode: snippet -*-
,# name: split-org-block
,# key: #split
@ -712,7 +711,8 @@ Not every header should be a destination, as many of my org files have duplicate
"Install"
"Overview"
"Summary"
"Technical Artifacts"))
"Technical Artifacts"
"[["))
"Regular expression matching headers to purge.")
#+end_src
@ -777,12 +777,20 @@ Before we dive into the implementation of this function, let’s write a test to
'("Somefile∷ Parent﹥ Subparent﹥ Deep Heading"
"ha-somefile.org" 73)))
(setq ha-hamacs-edit-prev-head-list '("Parent" "Subparent" "Subby"))
(should (equal
(ha-hamacs-edit--process-entry
"ha-somefile.org:73:**** Deep Heading")
'("Somefile∷ Parent﹥ Subparent﹥ Subby﹥ Deep Heading"
"ha-somefile.org" 73)))
(setq ha-hamacs-edit-prev-head-list '("Parent" "Subparent"
"Subby" "Deepsubby"))
(should (equal
(ha-hamacs-edit--process-entry
"ha-somefile.org:73:***** Deepest Heading")
'("Somefile∷ ... Deepest Heading"
'("Somefile∷ Parent﹥ Subparent﹥ Subby﹥ Deepsubby﹥ Deepest Heading"
"ha-somefile.org" 73))))
#+end_src
@ -928,13 +936,9 @@ Let's =provide= a name so we can =require= this file:
#+DESCRIPTION: literate programming in Emacs Org Files.
#+PROPERTY: header-args:sh :tangle no
#+PROPERTY: header-args:emacs-lisp :tangle yes :comments link
#+PROPERTY: header-args:emacs-lisp :tangle yes
#+PROPERTY: header-args :results none :eval no-export :comments no mkdirp yes
#+OPTIONS: num:nil toc:t todo:nil tasks:nil tags:nil date:nil
#+OPTIONS: skip:nil author:nil email:nil creator:nil timestamp:nil
#+INFOJS_OPT: view:nil toc:nil ltoc:t mouse:underline buttons:0 path:http://orgmode.org/org-info.js
# Local Variables:
# jinx-local-words: "parseable"
# End:

View file

@ -160,6 +160,7 @@ My main blog made up a collection of org files:
(:meta (@ :http-equiv "X-Clacks-Overhead" :content "Darol Allen"))
(:meta (@ :http-equiv "X-Clacks-Overhead" :content "George Vanecek"))
(:meta (@ :http-equiv "X-Clacks-Overhead" :content "Rick Cooper"))
(:meta (@ :http-equiv "X-Clacks-Overhead" :content "Rick Sothern"))
(:meta (@ :http-equiv "X-Clacks-Overhead" :content "Terry Pratchett"))))))
#+end_src
@ -190,10 +191,64 @@ The RSS generation seems to be something I do /later/ once I have my site workin
:include ("index.org")))
#+end_src
Rather than maintain a hand-written =emacs.org= index, we auto-generate it. A helper formats each file as an RSS entry with the properties =org-rss= expects:
#+begin_src emacs-lisp
(defun ha/org-rss-sitemap-format-entry (entry style project)
"Format ENTRY as an RSS item for the Emacs notes feed."
(let* ((title (org-publish-find-title entry project))
(date (org-publish-find-date entry project))
(desc (org-publish-find-property entry :description project))
(path (concat "Technical/Emacs/"
(file-name-sans-extension entry) ".html")))
(format "* [[https://www.howardism.org/%s][%s]]
:PROPERTIES:
:RSS_PERMALINK: %s
:PUBDATE: <%s>
:END:
%s\n"
path title path
(format-time-string "%Y-%m-%d %a" date)
(or desc ""))))
#+end_src
The auto-sitemap and the `:exclude'/`:include' filters share the same file list, so we need a separate project to scan all the files and write =emacs.org= — without actually publishing each file. A no-op publishing function handles that:
#+begin_src emacs-lisp
(defun ha/org-publish-noop (_plist _filename _pub-dir)
"No-op publishing function, used only to trigger auto-sitemap generation.")
(add-to-list 'org-publish-project-alist
`("emacs-sitemap"
:base-directory ,(concat org-mode-websrc-directory "/Technical/Emacs/")
:base-extension "org"
:publishing-directory ,(concat org-mode-websrc-directory "/Technical/Emacs/")
:publishing-function ha/org-publish-noop
:auto-sitemap t
:sitemap-filename "emacs.org"
:sitemap-title "Howard's Emacs Notes"
:sitemap-sort-files anti-chronologically
:sitemap-format-entry ha/org-rss-sitemap-format-entry))
#+end_src
Then the RSS project publishes the generated =emacs.org= as =emacs.xml= at the top level:
#+begin_src emacs-lisp
(add-to-list 'org-publish-project-alist
`("emacs-rss"
:base-directory ,(concat org-mode-websrc-directory "/Technical/Emacs/")
:base-extension "org"
:rss-image-url "https://howardism.org/img/dragon-head.png"
:publishing-directory ,org-mode-publishing-directory
:publishing-function (org-rss-publish-to-rss)
:html-link-home "https://www.howardism.org/"
:html-link-use-abs-url t
:with-toc nil
:exclude ".*"
:include ("emacs.org")))
#+end_src
And let’s make some blends of the individual projects:
#+begin_src emacs-lisp
(add-to-list 'org-publish-project-alist
`("blog" :components ("blog-content" "blog-static" "blog-rss")))
`("blog" :components ("blog-content" "blog-static" "blog-rss" "emacs-sitemap" "emacs-rss")))
#+end_src
** Technical Notes
I take notes on a variety of technical subjects, and since I can share these notes with others, I feel like I can publish those:
@ -240,6 +295,7 @@ As above, we can separate the publishing of the images and other static files:
:recursive t
:publishing-function org-publish-attachment))
#+end_src
** Literate Emacs Configuration
I’ve been committing my literate-style Emacs configuration for years now, and Github has rendered it well, but I felt I could publish this to my own web site as a /cleaner version/.
#+begin_src emacs-lisp

View file

@ -2,9 +2,7 @@
#+author: Howard X. Abrams
#+date: 2020-09-25
#+tags: emacs work
A literate program for configuring org files for work-related notes.
#+begin_src emacs-lisp :exports none
;;; org-sprint --- Configuring org files for work-related notes. -*- lexical-binding: t; -*-
;;
@ -25,33 +23,51 @@ A literate program for configuring org files for work-related notes.
;;; Code:
#+end_src
* Introduction
At the beginning of each Sprint, I create a new org file dedicated to it. This workflow/technique strikes a balance between a single ever-growing file, and a thousand little ones. This also gives me a sense of continuity, as the filename of each sprint is date-based.
I want a single keybinding that always displays the current Sprint note file, regardless of the Sprint. This means, I need to have functions that can calculate what this is.
To have the Org Capture features to be able to write to correct locations in the current file, I need each file to follow a particular format. I create a [[file:templates/sprint.org][sprint note template]] that will be automatically expanded with a new sprint.
This template needs the following functions:
- =sprint-current-name= to be both the numeric label as well as the nickname
- =sprint-date-range= to include a org-formatted date range beginning and ending the sprint
- =sprint-date-from-start= return a date for pre-scheduled and recurring meetings
* Naming Sprints
I give each sprint a nickname, based on a /theme/ of some sorts, alphabetized. Since our sprints are every two weeks, this allows me to go through the alphabet once. Yeah, my group likes to boringly /number/ the sprints, so I do both… for myself.
At the beginning of the year, I choose a theme, and make a list for the upcoming sprints. In the org file, this is a list, that gets /tangled/ into an actual Emacs LIsp list. This is pretty cool.
#+begin_src emacs-lisp :var sprint-names=sprint-names-2025
#+begin_src emacs-lisp :var sprint-names=sprint-names-2026
(defvar sprint-nicknames sprint-names
"List of 26 Sprint Nicknames from A to Z.")
#+end_src
** 2026
Drunk animals? Everyday AI?
Migrating to a new team should include something different.
#+name: sprint-names-2026
- Alchemist’s Amber
- Bubblegloop Bogs
- Crumpet Crossroads
- Dandelion Drifters
- Elfin Espresso
- Firefly Fandango
- Giggling Goblins
- Hobgoblin Hideaway
- Inkwell Isles
- Jester’s Junction
- Knapsack Knolls
- Lavender Labyrinths
- Moonbeam Meadow
- Nectar Nibblers
- Owl’s Overlook
- Pixie Dust Pipeline
- Quizzical Quagmires
- Runaway Radishes
- Starfruit Springs
- Thimbleweed Thicket
- Unicorn Unwinding
- Velvet Valley
- Whistling Willows
- Xanadu Xylophones
- Yawning Yearlings
- Zephyr Zigzags
** 2025
This year is the animals representing corporate slogans:
#+name: sprint-names-2025
- Accelerated and Adaptive Ant
- Buy-in Bee and Blue-sky Bull
@ -110,7 +126,6 @@ How about Tabaxi names this year … especially since my next character has to b
- Zip in the Wind
** 2023
How about a list of Ent names?
#+name: sprint-names-2023
- ashskin
- birchblossom
@ -139,9 +154,7 @@ How about a list of Ent names?
- yewbiquitous
- zelkova
** 2022
Fun sprint names for 2022 lists my favorite D&D monsters, also see [[https://list.fandom.com/wiki/List_of_monsters][this list of monsters]] from mythology and other sources:
#+name: sprint-names-2022
- ankheg
- beholder
@ -171,7 +184,6 @@ Fun sprint names for 2022 lists my favorite D&D monsters, also see [[https://lis
- zombie
** 2021
Choosing Sprint Names based on [[https://www.imagineforest.com/blog/funniest-words-in-the-english-language/][Funny or Silly Words]]:
#+name: sprint-names-2021
- abibliophobia :: The fear of running out of reading materials to read
- bamboozled :: To trick or confuse someone
@ -200,9 +212,7 @@ Choosing Sprint Names based on [[https://www.imagineforest.com/blog/funniest-wor
- yerk :: Pull or push something with a sudden movement.
- zazzy :: Something that is shiny and flashy
** 2020
New names from [[https://en.m.wikipedia.org/wiki/List_of_dinosaur_genera][list of dinosaurs]].
#+name: sprint-names-2020
- ankylosaurus
- brontosaurus
@ -230,11 +240,8 @@ New names from [[https://en.m.wikipedia.org/wiki/List_of_dinosaur_genera][list o
- xiaotingia
- yi
- zuul
** 2019
Came up with a list of somewhat well-known cities throughout the world (at least, they had to have a population of 100,000 or more), but I didn't want any real obvious ones.
#+name: sprint-names-2019
- achy-aachen
- bare-bacabal
@ -262,10 +269,8 @@ Came up with a list of somewhat well-known cities throughout the world (at least
- xenophobic-xichang
- yellow-yamaguchi
- zippy-zinder
* Sprint Boundaries
Function to help in calculating dates and other features of a two-week sprint that starts on Tuesday and ends on a Monday… how we work at my job.
Emacs have an internal rep of a time.
#+begin_src emacs-lisp
(defun get-date-time (date)
@ -279,44 +284,34 @@ Emacs have an internal rep of a time.
(apply 'encode-time))
date))
#+end_src
** Sprint Numbering
Each year, specify the first day of the first sprint of the year:
#+BEGIN_SRC emacs-lisp
;; CHANGEME Each year as this should update:
(defvar sprint-start-date (get-date-time "2026-01-06")
"The date of the first day of the first sprint of the year.
See `sprint-range'.")
#+END_SRC
My company has sprints two weeks long that we can calculate from
#+begin_src emacs-lisp
(defvar sprint-length (* 14 24 60 60)
"The length of a sprint, in seconds. This is 2 weeks long")
#+end_src
The number of the sprint comes from the number of /bi-weeks/ (14 day increments) from the =sprint-start-date=. We can calculate the number of seconds from this /start date/ and divide it by the =sprint-length=:
#+begin_src emacs-lisp
(defun sprint-number (&optional date)
"Return the number of 14-day intervals since SPRINT-START-DATE to DATE.
DATE is a string in YYYY-MM-DD format."
(unless date
(setq date (format-time-string "%Y-%m-%d")))
(let* ((end-time (get-date-time date))
(diff-seconds (float-time (time-subtract end-time sprint-start-date))))
;; After calculating the number of 'bi-weeks' (2 week sprint increments),
;; we add one to return the correct sprint for the networking team:
;; (1+ (floor (/ diff-seconds sprint-length)))
;; Or for the platform storage team:
(1+ (* 2 (floor (/ diff-seconds sprint-length))))))
#+end_src
And some tests to verify that:
#+begin_src emacs-lisp :tangle no
(ert-deftest sprint-number-test ()
@ -335,7 +330,6 @@ I create my org-file notes based on the Sprint number.
(format-time-string "%Y" d)
(sprint-number d)))))
#+end_src
So given a particular date, I should expect to be able to find the correct Sprint file name:
#+begin_src emacs-lisp :tangle no
(ert-deftest sprint-current-file-test ()
@ -344,9 +338,7 @@ So given a particular date, I should expect to be able to find the correct Sprin
(should (s-ends-with? "Sprint-2024-13.org" (sprint-current-file "2024-02-01")))
(should (s-ends-with? "Sprint-2024-14.org" (sprint-current-file "2024-02-13"))))
#+end_src
Daily note-taking goes into my sprint file notes, so this interactive function makes an easy global short-cut key.
#+begin_src emacs-lisp
(defun sprint-current-find-file (&optional date)
"Load the `org-mode' note associated with my current sprint."
@ -357,33 +349,32 @@ Daily note-taking goes into my sprint file notes, so this interactive function m
(add-to-list 'org-agenda-files filename)
(find-file filename)))
#+end_src
The /name/ and /nickname/ of the sprint will be used in the =#+TITLE= section, and it looks something like: =Sprint 2019-07 (darling-dadu)=
#+begin_src emacs-lisp
(defun sprint-current-name (&optional date)
"Return the default name of the current sprint (based on DATE)."
(let* ((d (get-date-time date))
(sprint-num (sprint-number d))
(nickname (nth (1- sprint-num) sprint-nicknames)))
(nickname (nth (/ (1- sprint-num) 2) sprint-nicknames)))
(format "Sprint %s-%02d :: %s"
(format-time-string "%Y" d)
(sprint-number d)
nickname)))
#+end_src
These test won't pass any more, as the nickname of the sprint changes from year to year.
Current sprint name:
#+BEGIN_SRC emacs-lisp :tangle no
(sprint-current-name)
#+END_SRC
These test won't pass any more, as the nickname of the sprint changes from year to year.
#+begin_src emacs-lisp :tangle no
(ert-deftest sprint-current-name-test ()
(should (equal "Sprint 2024-01 :: Art of Shadows" (sprint-current-name "2024-01-02")))
(should (equal "Sprint 2024-04 :: Daydream at Night" (sprint-current-name "2024-02-14"))))
#+end_src
** Sprint Start and End
I want to print the beginning and ending of the sprint, where we have a sprint number or a data, and we can give the dates that bound the sprint. This odd function calculates this based on knowing the date of the /first Tuesday/ of the year, so I need to begin the year changing this value. I should fix this.
#+begin_src emacs-lisp
(defun sprint-range (&optional number-or-date)
"Return a list of three entries, start of the current sprint,
@ -401,9 +392,7 @@ I want to print the beginning and ending of the sprint, where we have a sprint n
(sprint-end (time-add sprint-next (- day-length))))
(list sprint-start sprint-end sprint-next)))
#+end_src
Format the start and end so that we can insert this directly in the org file:
#+begin_src emacs-lisp
(defun sprint-date-range (&optional number-or-date)
"Return `org-mode' formatted date range for a given sprint.
@ -415,7 +404,6 @@ Format the start and end so that we can insert this directly in the org file:
(end (format-time-string formatter sprint-end)))
(format "[%s]--[%s]" start end))))
#+end_src
And validate with a test:
#+begin_src emacs-lisp
(ert-deftest sprint-date-range ()
@ -430,11 +418,8 @@ And validate with a test:
(should (equal (sprint-date-range 5)
(sprint-date-range "2024-01-31"))))
#+end_src
** Pre-scheduled Dates
Due to the regularity of the sprint cadence, I can pre-schedule meetings and other deadlines by /counting/ the number of days from the start of the sprint:
#+begin_src emacs-lisp
(defun sprint-date-from-start (days &optional formatter)
"Return formatted date string from number of DAYS from the start of the sprint."
@ -445,18 +430,14 @@ Due to the regularity of the sprint cadence, I can pre-schedule meetings and oth
(format-time-string formatter adate)
(format-time-string "%Y-%m-%d %a" adate))))
#+end_src
* Other Date Functions
The following functions /were/ helpful at times. But I'm not sure I will use them.
#+begin_src emacs-lisp :tangle no
(defun sprint-num-days (time-interval)
"Converts a TIME-INTERVAL to a number of days."
(let ((day-length (* 3600 24)))
(round (/ (float-time time-interval) day-length))))
#+end_src
#+begin_src emacs-lisp :tangle no
(defun sprint-day-range (&optional date)
"Returns a list of two values, the number of days from the
@ -468,7 +449,6 @@ The following functions /were/ helpful at times. But I'm not sure I will use the
(ending (time-subtract sprint-end now)))
(list (sprint-num-days starting) (sprint-num-days ending)))))
#+end_src
#+begin_src emacs-lisp :tangle no
(ert-deftest sprint-day-range ()
;; This sprint starts on 2/13 and ends on 2/26
@ -476,33 +456,25 @@ The following functions /were/ helpful at times. But I'm not sure I will use the
(should (equal '(-1 12) (sprint-day-range "2020-02-14")))
(should (equal '(-13 0) (sprint-day-range "2020-02-26"))))
#+end_src
#+begin_src emacs-lisp :tangle no
(defun sprint-day-start (&optional date)
"Return a relative number of days to the start of the current sprint. For instance, if today was Friday, and the sprint started on Tuesday, this would return -1."
(first (sprint-day-range date)))
(defun sprint-day-end (&optional date)
"Return a relative number of days to the end of the current sprint. For instance, if today was Monday, and the sprint will end on Monday, this would return 3."
(second (sprint-day-range date)))
#+end_src
* Technical Artifacts :noexport:
Let's =provide= a name so we can =require= this file:
#+begin_src emacs-lisp :exports none
(provide 'ha-org-sprint)
;;; ha-org-sprint.el ends here
#+end_src
Before you can build this on a new system, make sure that you put the cursor over any of these properties, and hit: ~C-c C-c~
#+description: A literate program for configuring org files for work-related notes.
#+property: header-args:sh :tangle no
#+property: header-args:emacs-lisp :tangle yes
#+property: header-args :results none :eval no-export :comments no mkdirp yes
#+options: num:nil toc:t todo:nil tasks:nil tags:nil date:nil
#+options: skip:nil author:nil email:nil creator:nil timestamp:nil
#+infojs_opt: view:nil toc:t ltoc:t mouse:underline buttons:0 path:http://orgmode.org/org-info.js

View file

@ -338,11 +338,12 @@ The [[https://github.com/minad/org-modern][org-modern]] project attempts to do a
(org-modern-table nil)
(org-pretty-entities t)
(setq org-modern-fold-stars '(("▸" . "▾")
("▹" . "▿")
("▸" . "▾")
("▹" . "▿")
("▸" . "▾")))
("▹" . "▿")
("▸" . "▾")
("▹" . "▿")
("▸" . "▾")))
:config
(set-face-attribute 'org-modern-todo nil :inverse-video nil)
(set-face-attribute 'org-ellipsis nil :inherit 'default :box nil :underline nil)
(set-face-attribute 'org-modern-symbol nil :family "Iosevka"))
#+end_src

View file

@ -3,7 +3,7 @@
#+date: 2020-09-18
#+tags: emacs org
#+startup: inlineimages
#+lastmod: [2026-06-18 Thu]
#+lastmod: [2026-10-09 Fri]
A literate programming file for configuring org-mode and those files.
@ -64,6 +64,7 @@ Begin by initializing these org variables:
org-edit-src-content-indentation 2 ; Doom Emacs sets this to 0,
; but uses a trick to make it
; appear indented.
org-use-sub-superscripts '{}
org-imenu-depth 4
sentence-end-double-space nil ; I jump around by sentences, but seldom have two spaces.
@ -152,7 +153,7 @@ What should we do if we are at the end of a line?
- In a table? Create a new row.
- In a list, create a new item.
I should break this function into smaller bits ...
I should break this function into smaller bits:
#+begin_src emacs-lisp
(defun ha-org-special-return (&optional ignore)
@ -178,7 +179,7 @@ I should break this function into smaller bits ...
(org-return)))))
#+end_src
How do we know if we are in a list item? Lists end with two blank lines, so we need to make sure we are also not at the beginning of a line to avoid a loop where a new entry gets created with one blank line.
How do we know if we are in a list item? Lists end with two empty lines, so we need to make sure we are also not at the beginning of a line to avoid a loop where a new entry gets created with one empty line.
#+begin_src emacs-lisp
(defun org-really-in-item-p ()
"Return item beginning position when in a plain list, nil otherwise.
@ -222,10 +223,11 @@ I need to add a /blocked/ state, and wouldn’t /doing/ be better than /in progr
(add-hook 'org-after-todo-state-change-hook 'ha-org-clock-todo-change)
#+end_src
And I would like to have cute little icons for those states:
#+name: org-font-lock
#+begin_src emacs-lisp
#+begin_src emacs-lisp :tangle no
(dolist (m '(org-mode org-journal-mode))
(font-lock-add-keywords m ; A bit silly but my headers are now
`(("^\\*+ \\(TODO\\) " ; shorter, and that is nice canceled
@ -245,31 +247,6 @@ And I would like to have cute little icons for those states:
(0 (prog1 () (compose-region (match-beginning 1) (match-end 1) "•")))))))
#+end_src
What was
#+BEGIN_SRC emacs-lisp
(defun display-latest-clocked-task ()
"Display the name of the latest task that was clocked in."
(interactive)
(let ((latest-task (car (org-clock-get-clock-string))))
(if latest-task
(message "Latest clocked task: %s" latest-task)
(message "No task is currently clocked in."))))
#+END_SRC
Need to be able to clock out of a task even if no /clock-in/ has occurred.
#+BEGIN_SRC emacs-lisp
(defun ha-clock-out ()
"Safely clock out of the current task.
This will not throw an error if not active clock exists."
(interactive)
(ignore-errors
(org-clock-out)
(message "Clocked out.")))
#+END_SRC
** Meetings
I've notice that while showing a screen while taking meeting notes, I don't always like showing other windows, so I created this function to remove distractions during a meeting.
@ -433,8 +410,9 @@ And let’s see how it works:
User-Agent: ${user-agent}
#+end_src
#+results:
#+begin_src js
Results in:
#+begin_src js :tangle no
{
"Emacs Lisp": 15327,
"Shell": 139
@ -455,8 +433,9 @@ And let’s try this:
User-Agent: ${user-agent}
#+end_src
#+results:
#+begin_src js
Results in the same output:
#+begin_src js :tangle no
{
"Emacs Lisp": 15327,
"Shell": 139
@ -814,9 +793,6 @@ Splitting out HTML snippets is often a way that I can transfer org-formatted con
hard-newline))))))
#+end_src
** Focused Work
:LOGBOOK:
CLOCK: [2022-02-11 Fri 11:05]--[2022-02-11 Fri 11:21] => 0:16
:END:
I've been working on my own [[http://www.howardism.org/Technical/Emacs/focused-work.html][approach to focused work]],
#+begin_src emacs-lisp
@ -832,8 +808,49 @@ I've been working on my own [[http://www.howardism.org/Technical/Emacs/focused-w
("S-<f12>" . ha-focus-interrupt)
("s-<f12>" . ha-focus-timer-left)))
#+end_src
Need to be able to clock out of a task even if no /clock-in/ has occurred.
#+begin_src emacs-lisp
(defun ha-clock-out ()
"Safely clock out of the current task.
This will not throw an error if no active clock exists."
(interactive)
(ignore-errors
(org-clock-out)
(message "Clocked out.")))
#+end_src
I call this function from [[file:hammerspoon.org::*Clocking out a Task][my Hammerspoon configuration]] to clock out of a task when I close my laptop.
What was I working on? Opening the laptop after a break seldom answers that, so this reports whatever clock is still running, and when none is, the one I stopped last, which is the more likely question after a break.
#+begin_src emacs-lisp
(defun ha-display-latest-clocked-task ()
"Display the task clocked in now, or the one most recently clocked out."
(interactive)
(cond
((org-clocking-p)
(message "Currently clocked in: %s"
(substring-no-properties (org-clock-get-clock-string))))
((and org-clock-out-time
(stringp org-clock-heading)
(not (string-empty-p org-clock-heading)))
(let ((seconds (float-time (time-subtract nil org-clock-out-time))))
(message "Clocked out of \"%s\" %s ago" org-clock-heading
(if (< seconds 60)
"less than a minute"
(format-seconds "%D %H %M%z" seconds)))))
(t (message "No task is currently clocked in."))))
#+end_src
The =%z= at the /end/ of the format drops the larger units while they read zero, turning =0 days 0 hours 25 minutes= into =25 minutes=. It has nothing to lean on when every unit is zero, so the first minute gets phrased by hand:
** Spell Checking
Let's hook some spell-checking into org files, and actually all text files. I’m making this particularly delicious.
Let's hook some spell checking into org files, and actually all text files. I’m making this particularly delicious.
*** abbrev
First, we turn on =abbrev-mode=. While this package comes with Emacs, check out [[https://masteringemacs.org/article/correcting-typos-misspellings-abbrev][Mickey Petersen's overview]] of using this package for auto-correcting typos.
@ -853,7 +870,7 @@ The idea is that you can correct a typo /and remember/ it. Perhaps calling [[hel
*** jinx
Once upon a time, I used [[https://www.emacswiki.org/emacs/FlySpell][flyspell]] mode to highlight the misspelled words, and the venerable [[https://www.emacswiki.org/emacs/InteractiveSpell][ispell]] for correcting. To be able to correct spelling mistakes /from a distance/, without navigation, I wrote a function that took advantage of Evil’s [[help:evil-prev-flyspell-error][evil-prev-flyspell-error]] to jump back to the last spelling mistake.
Now, I’m using [[https://github.com/minad/jinx][jinx]], as it is the /complete basket/. It spellchecks based on the fontlock face and uses an external [[https://github.com/AbiWord/enchant][enchant program]] (to make spell-checking fast and asynchronous). Like =flymake=, Jinx does on-the-fly spellchecking of code comments and strings.
Now, I’m using [[https://github.com/minad/jinx][jinx]], as it is the /complete basket/. It spellchecks based on the fontlock face and uses an external [[https://github.com/AbiWord/enchant][enchant program]] (to make spell checking fast and asynchronous). Like =flymake=, Jinx does on-the-fly spell checking of code comments and strings.
I keep =jinx-correct= bound to ~C-;~ à la flyspell because it is so darn helpful. Supports checking documents with mixed languages.
@ -913,14 +930,13 @@ The key-bindings, keystrokes, and key-connections work well with a hyper-command
:bind ("s-t" . powerthesaurus-lookup-dwim))
#+END_SRC
*** Definitions
Since the /definitions/ do not work, so let's use the [[https://github.com/abo-abo/define-word][define-word]] project:
#+begin_src emacs-lisp
(use-package define-word
:config
(ha-leader :keymaps 'text-mode-map
(ha-leader
"s d" '(:ignore t :which-key "dictionary")
"s d d" '("define this word" . define-word-at-point)
"s d a" '("define any word" . define-word)))
@ -959,21 +975,103 @@ Once in the dictionary buffer, acquiesce these keybindings:
Also note that the dictionary has links to other pages, so ~n~ and ~TAB~ jumps to the next link and ~RET~ opens that link.
** Grammar and Prose Linting
Flagging cliches, weak phrasing and other poor grammar choices.
Flagging clichés, weak phrasing and other poor grammar choices.
We are trying a lot of checkers, so we need to /chain/ them with a call to =flycheck-add-next-checker=:
We are trying a lot of checkers, as each have their specialties. To do this, we /chain/ them with a call to =flycheck-add-next-checker=:
=write-good= —> =proselint= —> =textlint= —> =jinx= (for spell checking)
*** Ignoring Code Blocks
None of these checkers understand Org, so each one grades my source blocks as if they were English. This becomes especially problematic when a Lisp quote turns off =proselint= for the rest of the file. I solved this issue in Markdown with [[file:ha-programming.org::*Remark][Remark]] and a code-stripping plugin, but the Org checkers have no such pipeline.
/Every/ checker gets the buffer through one of two functions: =flycheck-process-send-buffer= for the ones reading standard input, and =flycheck-save-buffer-to-file= for the ones handed a temporary file. Both work on whatever buffer happens to be current, so rather than wrap all three tools, I =advise= the pair to cover every checker in the chain, including any I add later.
The blanking replaces each character with a space instead of deleting it. Line numbers, columns, and character offsets all survive, so the positions the checkers report still line up with the real buffer:
=write-good= —> =proselint= —> =textlint= —> =languagetool=?
*** Writegood
The [[https://github.com/bnbeckwith/writegood-mode][writegood-mode]] is effective at highlighting passive and weasel words.
#+begin_src emacs-lisp
(use-package writegood-mode)
(defcustom ha-org-prose-ignored-blocks '("src" "example" "export")
"Org block types whose contents the prose checkers should never see.
Note the absence of `quote' and `verse', as those hold prose worth
grading."
:type '(repeat string)
:group 'flycheck)
(defun ha-org--blank-region (start end)
"Replace each non-newline character between START and END with a space.
To keep the line number positions correct, I can't just delete a code block,
but need to replace the code block contents with innocuous spaces, but keep
the newline characters."
(save-excursion
(goto-char start)
(while (< (point) end)
(let ((eol (min end (line-end-position))))
(unless (= eol (point))
(let ((len (- eol (point))))
(delete-region (point) eol)
(insert (make-string len ?\s)))))
(forward-line 1))))
(defun ha-org--blank-inline-code ()
"Blank inline verbatim and code markup in the current buffer.
Only group 2 of `org-verbatim-re', the markup and its delimiters,
gets blanked, leaving the surrounding punctuation it also matches."
(goto-char (point-min))
(while (re-search-forward org-verbatim-re nil t)
(ha-org--blank-region (match-beginning 2) (match-end 2))
;; Stop short of the trailing character, since it doubles as the
;; leading character of whatever construct comes next.
(goto-char (match-end 2))))
(defun ha-org-prose-only-text ()
"Return this buffer's text with code blocks and inline code blanked."
(let ((text (buffer-substring-no-properties (point-min) (point-max))))
(with-temp-buffer
(insert text)
(goto-char (point-min))
(let* ((case-fold-search t)
(types (regexp-opt ha-org-prose-ignored-blocks t))
(start-re (concat "^[ \t]*#\\+begin_" types "\\b")))
(while (re-search-forward start-re nil t)
(let ((type (match-string 1))
(start (match-beginning 0)))
(when (re-search-forward
(concat "^[ \t]*#\\+end_" (regexp-quote type) "\\b.*$") nil t)
(ha-org--blank-region start (point))))))
;; After the blocks, since their contents no longer contain markup.
(ha-org--blank-inline-code)
(buffer-string))))
#+end_src
And it reports obnoxious messages.
Note: Instead of hooking the =writegood-mode= to Org files, I will hook it to =flycheck= instead.
Another issue I encounter (again solved differently for Markdown files using [[file:ha-programming.org::*Remark][Remark]]) involves ignoring these grammar and /proselinters/ for verbatim-formatted code. This allows me to write about =just= as a program, and not have it flagged.
Both advised functions read the current buffer, so the trick is to make a scratch buffer current that holds the blanked text. The =derived-mode-p= test happens /before/ the temporary buffer exists, since that buffer is in =fundamental-mode=:
#+begin_src emacs-lisp
(defun ha-flycheck--org-prose-only (orig &rest args)
"Call ORIG with code blocks blanked, when checking an Org buffer."
(if (derived-mode-p 'org-mode)
(let ((text (ha-org-prose-only-text)))
(with-temp-buffer
(insert text)
(apply orig args)))
(apply orig args)))
(advice-add 'flycheck-process-send-buffer :around #'ha-flycheck--org-prose-only)
(advice-add 'flycheck-save-buffer-to-file :around #'ha-flycheck--org-prose-only)
#+end_src
This matters more than tidiness for =proselint=. Since version 0.16, it pairs quote characters across the whole document and silently discards any complaint landing between a pair. Lisp is full of quoted symbols and strings, so those pairings run wild: 80% of this file counts as “quoted”, and the warnings in it never appear. Blanking the code drops that figure to a fraction of a percent.
*** Writegood
The [[https://github.com/bnbeckwith/writegood-mode][writegood-mode]] is effective at highlighting passive voice and weasel words.
For instance:
#+begin_quote
The cake was eaten by the children.
#+end_quote
We install the =write-good= npm:
We install the =write-good= NPM:
#+begin_src shell
npm install -g write-good
#+end_src
@ -983,7 +1081,9 @@ And check that the following works:
write-good --text="So it is what it is."
#+end_src
Now, let’s connect it to flycheck:
Instead of hooking the =writegood-mode= to Org files, I =hook= it to =flycheck= instead.
Note that =markdown-mode= is absent from the list of modes, as Markdown files go through [[file:ha-programming.org::*Remark][Remark]] instead, which runs =write-good= over the prose while ignoring the code blocks:
#+begin_src emacs-lisp
(use-package flycheck
:config
@ -993,21 +1093,31 @@ Now, let’s connect it to flycheck:
:standard-input nil
:error-patterns
((warning line-start (file-name) ":" line ":" column ":" (message) line-end))
:modes (markdown-mode org-mode text-mode))
:modes (org-mode text-mode))
(add-to-list 'flycheck-checkers 'write-good))
#+end_src
*** Proselint
With overlapping goals to =write-good=, the [[https://github.com/amperser/proselint/][proselint]] project, once installed, can check for some English phrasings. I like =write-good= better, but I want this available for its level of /pedantic-ness/.
The [[https://github.com/amperser/proselint/][proselint]] project checks for poor English phrasings, clichés, and corporate-speak. For instance:
#+begin_quote
Let's touch base and circle back.
#+end_quote
Install it on a Mac via:
#+begin_src sh
brew install proselint
#+end_src
And on Linux:
#+BEGIN_SRC sh
sudo apt install python3-proselint
#+END_SRC
Next, create a configuration file, =~/.config/proselint/config= file, to turn on/off checks:
#+begin_src js :tangle ~/.config/proselint/config.json :mkdirp yes
{
"checks": {
@ -1019,17 +1129,28 @@ Next, create a configuration file, =~/.config/proselint/config= file, to turn on
#+end_src
And tell [[https://www.flycheck.org/][flycheck]] to use Proselint:
#+begin_src emacs-lisp :tangle no
#+begin_src emacs-lisp
(use-package flycheck
:config
(add-to-list 'flycheck-checkers 'proselint)
;; And create the chain of checkers so that both work:
(flycheck-add-next-checker 'write-good 'proselint))
#+end_src
Without this block tangling, =write-good= has no /next/ checker, and since it sits at the front of =flycheck-checkers=, it becomes the one Org buffers select. Flycheck then stops there, and every checker chained behind it never runs.
*** Textlint
The [[https://textlint.github.io/][textlint]] project comes with =flycheck=, as long as there is an executable:
The [[https://textlint.github.io/][textlint]] project comes with =flycheck=, and flags undefined acronyms (which annoyingly display at the beginning of the file), using the wrong punctuation, and “profane” words. For instance:
#+begin_quote
NASA launched a new rocket ball’s deep to the moon.
#+end_quote
This requires an executable:
#+begin_src sh :results silent
sudo npm install -g textlint
# And all the rules
sudo npm install -g textlint-rule-alex
sudo npm install -g textlint-rule-diacritics
@ -1037,75 +1158,113 @@ The [[https://textlint.github.io/][textlint]] project comes with =flycheck=, as
sudo npm install -g textlint-rule-max-comma
sudo npm install -g textlint-rule-no-start-duplicated-conjunction
sudo npm install -g textlint-rule-period-in-list-item
sudo npm install -g textlint-rule-stop-words
sudo npm install -g textlint-rule-terminology
sudo npm install -g textlint-rule-unexpanded-acronym
#+end_src
I create a configuration file in my home directory:
#+begin_src js :tangle ~/.textlintrc
{
"filters": {},
"rules": {
"abbr-within-parentheses": false,
"alex": true,
"alex": { "severity": "warning" },
"common-misspellings": false,
"diacritics": true,
"en-max-word-count": true,
"max-comma": true,
"no-start-duplicated-conjunction": true,
"period-in-list-item": true,
"stop-words": true,
"terminology": true,
"unexpanded-acronym": true,
"write-good": false
"diacritics": { "severity": "warning" },
"en-max-word-count": { "severity": "warning" },
"max-comma": { "severity": "warning" },
"no-start-duplicated-conjunction": { "severity": "warning" },
"period-in-list-item": { "severity": "warning" },
"stop-words": false,
"terminology": { "severity": "warning" },
"unexpanded-acronym": { "severity": "warning" },
"write-good": false,
"unexpanded-acronym": false
}
}
#+end_src
Add =textlint= to the /chain/ for Org files:
Every rule carries an explicit =severity=, as textlint defaults each one to /error/, and =flycheck-parse-eslint= turns that into an Emacs error. Left alone, a quibble over a hyphen would outrank a misspelling. Note the /object/ form: a rule set to =true= takes no options, so the severity has to replace that value rather than sit beside it.
Add =textlint= to the /chain/ for Org files. The built-in checker hands textlint a temporary file named after the buffer, and textlint /silently skips/ any file whose extension it does not know. Since =.org= is not on that list, it reports nothing and exits successfully, which looks identical to a clean buffer…ugh.
Piping the buffer in under a name textlint accepts avoids that. The =stdin.txt= name is cosmetic, as =flycheck-parse-eslint= overwrites it with the real buffer’s file name:
#+begin_src emacs-lisp
(use-package flycheck
:config
(setq flycheck-textlint-config (format "%s/.textlintrc" (getenv "HOME")))
(flycheck-add-next-checker 'proselint 'textlint t))
(flycheck-define-checker org-textlint
"A prose checker for Org files using textlint.
Textlint skips files whose extension it does not know, and `.org' is
not among them, so the buffer arrives on standard input under a name
the text plugin accepts."
:command ("textlint"
(config-file "--config" flycheck-textlint-config)
"--format" "json"
"--plugin" "@textlint/text"
"--stdin" "--stdin-filename" "stdin.txt")
:standard-input t
:error-parser flycheck-parse-eslint
:modes (org-mode))
(add-to-list 'flycheck-checkers 'org-textlint t)
(flycheck-add-next-checker 'proselint 'org-textlint t))
#+end_src
*** Language Tool
Another flycheck feature is to use [[http://languagetool.org][LanguageTool]] connection to [[https://github.com/emacs-languagetool/flycheck-languagetool][flycheck-languagetool]]:
Note: The text plugin has no notion of Org, but that no longer matters, since [[*Ignoring Code Blocks][the advice above]] hands it prose with the code already blanked.
*** Spelling
I like correcting spelling through the [[*jinx][jinx]] interface, but would also like to jump through misspellings using the =flycheck= UI.
Note: Since =flycheck= only /reports/ problems (like a misspelling), I still require =jinx-correct= to repair the problem.
#+BEGIN_SRC emacs-lisp :tangle no
(use-package flycheck-languagetool
:ensure t
:hook (text-mode . flycheck-languagetool-setup)
:init
(setq flycheck-languagetool-server-jar (expand-file-name "/opt/homebrew/Cellar/languagetool/6.6/libexec/languagetool-commandline.jar")
flycheck-languagetool-server-args (expand-file-name "~/.config/languagetool/config.properties")))
#+END_SRC
Jinx already does the work and leaves an overlay on each misspelling, so the checker collects them:
Where it can read: [[file:~/.config/languagetool/config.properties][config.properties]].
And connect it to the chain:
#+BEGIN_SRC emacs-lisp :tangle no
#+begin_src emacs-lisp
(use-package flycheck
:config (flycheck-add-next-checker 'textlint 'languagetool t)
:after jinx
:config
(defun ha-jinx--flycheck-errors (checker)
"Return a `flycheck-error' for each misspelling jinx finds."
;; Jinx separates prose from code by font-lock face, and font-lock
;; only fontifies what has been displayed. Without this, the rest of
;; the buffer arrives faceless and every symbol reads as misspelled.
(font-lock-ensure)
(jinx--check-region (point-min) (point-max))
(mapcar (lambda (ov)
(let ((start (overlay-start ov))
(end (overlay-end ov)))
(flycheck-error-new-at-pos
start 'error
(format "Misspelled: %s"
(buffer-substring-no-properties start end))
:id "jinx"
:checker checker
:end-pos end)))
(jinx--get-overlays (point-min) (point-max))))
;; May have to specify a Java on one of my Mac machines:
(when (file-exists-p "/opt/homebrew/opt/openjdk")
(add-to-list 'exec-path "/opt/homebrew/opt/openjdk/bin")))
#+END_SRC
(flycheck-define-generic-checker 'jinx
"A spell checker reporting what jinx and enchant already found."
:start (lambda (checker callback)
(condition-case err
(funcall callback 'finished (ha-jinx--flycheck-errors checker))
(error (funcall callback 'errored (error-message-string err)))))
;; Without jinx enabled there are no dictionaries to ask.
:predicate (lambda () (bound-and-true-p jinx-mode))
:modes '(org-mode text-mode markdown-mode gfm-mode))
This check complains about whitespace in Org files (duh), so let’s create a configuration file where we can disable that rule (and any other we can require):
(add-to-list 'flycheck-checkers 'jinx t)
(flycheck-add-next-checker 'org-textlint 'jinx t))
#+end_src
#+BEGIN_SRC conf :tangle ~/.config/languagetool/config.properties :mkdirp ~/.config/languagetool
disabledRuleIds: WHITESPACE
#+END_SRC
Note that jinx underlining the words itself, /on top of/ what flycheck now draws. Turning that off would mean would apply that everywhere — including the programming buffers where this prose-chain never runs, and I would need jinx’s flagging. In other words, the doubled underline seems the smaller cost.
Gotta admit that Language Tool doesn’t seem to help much. $ 100 ?
** Perfect Sentence
Chris Malorana’s [[https://www.youtube.com/watch?v=E-yk_V5TnNU][video tutorial]] demonstrates the ability to extrude a single sentence into another buffer, edit different versions of that sentence, and replace one version into the original buffer. For instance, how org-mode edits blocks.
Jordan Peterson's writing app, [[https://essay.app/guide][Essay]], inspired Chris Malorana’s [[https://www.youtube.com/watch?v=E-yk_V5TnNU][video tutorial]] showing the ability to extrude a single sentence into another buffer, edit different versions of that sentence, and replace one version into the original buffer. Similar to how org-mode edits blocks.
Malorana based this idea on Jordan Peterson's writing app, [[https://essay.app/guide][Essay]]. Thought I might work on it, but I want my version more resilient and not as dependent on the context.
Thought I might work on it, but I want my version more resilient and not as dependent on the context.
When we create a new buffer, we set the following /buffer-local/ variables, so we know where to return:
@ -1188,9 +1347,11 @@ In that case, we need to select the text before hitting the ~C-c C-c~ sequence.
(delete-region orig-start orig-end) ; Or call `kill-region' to put on clipboard?
(insert chosen-sentence))))
#+end_src
The [[help:kill-region][kill-region]] function takes the original text and places it on the [[help:kill-ring][kill-ring]] (the clipboard). But since we already copied that when we created the buffer, we call [[help:delete-region][delete-region]] instead. Especially since if we felt like we made a mistake, we could just undo the changes.
With my limited experience, I seldom enter completely difference sentences. Instead, I want to /copy/ the sentence and work on that. Let’s make a function to duplicate it.
The [[help:kill-region][kill-region]] function takes the original text and places it on the [[help:kill-ring][kill-ring]] (the clipboard). But since we already copied that when we created the buffer, we call [[help:delete-region][delete-region]] instead. If we felt like we made a mistake, we can undo the changes.
With my limited experience, I seldom replace the sentence. Instead, I want to /copy/ the sentence and work on that:
#+begin_src emacs-lisp
(defun ha-sentence-duplicate ()
(interactive)
@ -1202,7 +1363,7 @@ With my limited experience, I seldom enter completely difference sentences. Inst
(goto-char starting-point))))
#+end_src
When creating this new editing buffer, we need keybindings that exist only for this buffer, in other words, a [[https://www.gnu.org/software/emacs/manual/html_node/elisp/Defining-Minor-Modes.html][minor mode]]:
When creating this new editing buffer, we need keybindings that exist for this buffer, in other words, a [[https://www.gnu.org/software/emacs/manual/html_node/elisp/Defining-Minor-Modes.html][minor mode]]:
#+begin_src emacs-lisp
(defvar ha-sentence-buffer-mode-map (make-sparse-keymap) "Keymap for `my-mode'.")
(define-key ha-sentence-buffer-mode-map (kbd "C-c C-c") #'ha-sentence-choose)
@ -1234,7 +1395,9 @@ And something else while in Evil mode:
#+begin_src emacs-lisp
(ha-leader "x b" '("edit sentence" . ha-sentence-break))
#+end_src
Perhaps he might get around to turning [[https://git.chrismaiorana.com/?p=sentinel.git;a=blob;f=sentin.el;h=2738eff6ac2b0877576bafe88878683a7eff3125;hb=refs/heads/master][his code]] into a package. Features needed include:
While Malorana might get around to turning [[https://git.chrismaiorana.com/?p=sentinel.git;a=blob;f=sentin.el;h=2738eff6ac2b0877576bafe88878683a7eff3125;hb=refs/heads/master][his code]] into a package, new features need to include:
- Adding an overlay to the original text, help:org-src--make-source-overlay
** Distraction-Free Writing
@ -1315,5 +1478,5 @@ Before you can build this on a new system, make sure that you put the cursor ove
#+infojs_opt: view:nil toc:t ltoc:t mouse:underline buttons:0 path:http://orgmode.org/org-info.js
# Local Variables:
# jinx-local-words: "Braganza Graphviz Malorana’s Proselint Somers Textlint Writegood flycheck flyspell fontlock"
# jinx-local-words: "Braganza Graphviz Malorana Malorana’s Proselint Somers Textlint Writegood flycheck flyspell fontlock"
# End:

View file

@ -318,85 +318,6 @@ This allows me to delete a Python “block” using ~dal~.
("Misc"
(("t" python-tests/body "Tests..."))))))
#+end_src
* Elpy
The [[https://elpy.readthedocs.io/en/latest/introduction.html][Elpy Project]] expands on the =python-mode=.
#+BEGIN_SRC emacs-lisp
(use-package elpy
:init
(advice-add 'python-mode :before 'elpy-enable)
:config
;; (elpy-enable)
(setq elpy-test-runner 'elpy-test-pytest-runner)
(setq elpy-formatter 'black)
(setq elpy-shell-echo-input nil)
(setq elpy-modules (delq 'elpy-module-flymake elpy-modules)))
#+END_SRC
Elpy uses its *own* virtual environment for its backend process (jedi, rope, etc.), keeping elpy's own dependencies out of your project venvs. While there is a [[help:elpy-rpc-reinstall-virtualenv][elpy-rpc-reinstall-virtualenv]] function, I find it doesn’t seem to install everything correctly, and I need to do this by hand:
#+BEGIN_SRC sh
source ~/.emacs.d/elpy/rpc-venv/bin/activate
pip install jedi black flake8 ipython
#+END_SRC
After we’ve loaded the Company section, we can add jedi to the list of completions:
#+BEGIN_SRC emacs-lisp
(use-package elpy
:after company-mode
:config (add-to-list 'company-backends 'company-jedi))
#+END_SRC
Let’s expand our =major-mode-hydra= with some extras:
#+begin_src emacs-lisp
(use-package major-mode-hydra
:after elpy
:config
(pretty-hydra-define python-evaluate (:color blue :quit-key "q"
:title ha-python-eval-title)
("Section"
(("F" elpy-shell-send-defun "Function")
("E" elpy-shell-send-statement "Statement")
(";" python-shell-send-string "Expression"))
"Entirety"
(("B" elpy-shell-send-buffer "Buffer")
("r" elpy-shell-send-region-or-buffer "region"))
"And Step..."
(("f" elpy-shell-send-defun-and-step "Function" :color pink)
("e" elpy-shell-send-statement-and-step "Statement" :color pink))))
(pretty-hydra-define+ python-refactor nil
("Elpy"
(("r" elpy-refactor-rename "Rename")
("i" elpy-refactor-inline "Inline var")
("v" elpy-refactor-extract-variable "To variable")
("f" elpy-refactor-extract-function "To function")
("a" elpy-refactor-mode "All..."))))
(major-mode-hydra-define+ python-mode (:quit-key "q" :color blue)
("Server"
(("s" elpy-shell-switch-to-shell "Go to Server")
("C" elpy-config "Config Elpy"))
"Edit"
(("f" elpy-black-fix-code "Fix/format code"))
"Docs"
(("d" elpy-eldoc-documentation "Describe Symbol")
("D" elpy-doc "Docs Symbol")))))
#+end_src
* Anaconda
The [[https://github.com/pythonic-emacs/anaconda-mode][anaconda-mode project]] seems as good as Elpy, but also include Evil keybindings.
#+BEGIN_SRC emacs-lisp :tangle no
(use-mode anaconda-mode
:hook ((python-mode . anaconda-mode)
(python-mode ../ anaconda-eldoc-mode)))
#+END_SRC
Since we are using
* LSP Integration of Python
** Dependencies
Each Python project's =requirements-dev.txt= file would reference the [[https://pypi.org/project/python-lsp-server/][python-lsp-server]] (not the /unmaintained/ project, =python-language-server=):
@ -422,100 +343,60 @@ Each Python project's =requirements-dev.txt= file would reference the [[https://
# ...
#+end_src
** Pyright
I’m using the Microsoft-supported [[https://github.com/Microsoft/pyright][pyright]] package instead. Adding this to my =requirements.txt= files:
I’m using the Microsoft-supported [[https://github.com/Microsoft/pyright][pyright]] package instead, adding it to the global Python scope.
#+begin_src conf :tangle no
pyright
#+end_src
The [[https://github.com/emacs-lsp/lsp-pyright][pyright package]] works with LSP.
While the [[https://github.com/emacs-lsp/lsp-pyright][pyright package]] works with LSP, this isn’t needed, as =eglot= works directly with it.
** eglot
The built-in Eglot package natively supports [[https://github.com/Microsoft/pyright][pyright]] via =eglot-server-programs= (no extra package needed):
#+begin_src emacs-lisp :tangle no
(use-package lsp-pyright
:hook (python-mode . (lambda () (require 'lsp-pyright)))
:init (when (executable-find "python3")
(setq lsp-pyright-python-executable-cmd "python3")))
#+begin_src emacs-lisp
(use-package eglot
:straight nil
:after python
:defer t
:hook (python-mode . eglot-ensure)
:config
(add-to-list 'eglot-server-programs
'((python-mode python-ts-mode) . ("pyright-langserver" "--stdio"))))
#+end_src
*** Keybindings
Now that the [[file:ha-programming.org::*Language Server Protocol (LSP) Integration][LSP Integration]] is complete, we can stitch the two projects together, by calling =lsp=. I oscillate between automatically turning on LSP mode with every Python file, but I sometimes run into issues when starting, so I conditionally turn it on.
Keybindings for the eglot-based LSP sub-menu, wired into the existing =python-mode= hydra:
#+begin_src emacs-lisp
(defvar ha-python-lsp-title (font-icons 'faicon "python" :title "Python LSP"))
(defun ha-setup-python-lsp ()
"Configure the keybindings for LSP in Python."
(interactive)
(use-package eglot
:straight nil
:after major-mode-hydra
:config
(pretty-hydra-define python-lsp (:color blue :quit-key "q"
:title ha-python-lsp-title)
("Server"
(("D" lsp-disconnect "Disconnect")
("R" lsp-workspace-restart "Restart")
("S" lsp-workspace-shutdown "Shutdown")
("?" lsp-describe-session "Describe"))
(("D" eglot-shutdown "Disconnect")
("R" eglot-reconnect "Reconnect")
("?" eglot-show-workspace-configuration "Describe"))
"Refactoring"
(("a" lsp-execute-code-action "Code Actions")
("o" lsp-organize-imports "Organize Imports")
("l" lsp-avy-lens "Avy Lens"))
"Toggles"
(("b" lsp-headerline-breadcrumb-mode "Breadcrumbs")
("d" lsp-ui-doc-mode "Documentation Popups")
("m" lsp-modeline-diagnostics-mode "Modeline Diagnostics")
("s" lsp-ui-sideline-mode "Sideline Mode"))
""
(("t" lsp-toggle-on-type-formatting "Type Formatting")
("h" lsp-toggle-symbol-highlight "Symbol Highlighting")
("L" lsp-toggle-trace-io "Log I/O"))))
(pretty-hydra-define+ python-goto (:quit-key "q")
("LSP"
(("g" lsp-find-definition "Definition")
("d" lsp-find-declaration "Declaration")
("r" lsp-find-references "References")
("t" lsp-find-type-definition "Type Definition"))
"Peek"
(("D" lsp-ui-peek-find-definitions "Definitions")
("I" lsp-ui-peek-find-implementation "Implementations")
("R" lsp-ui-peek-find-references "References")
("S" lsp-ui-peek-find-workspace-symbol "Symbols"))
"LSP+"
(("u" lsp-ui-imenu "UI Menu")
("i" lsp-find-implementation "Implementations")
("h" lsp-treemacs-call-hierarchy "Hierarchy")
("E" lsp-treemacs-errors-list "Error List"))))
(major-mode-hydra-define+ python-mode nil
("Server"
(("l" python-lsp/body "LSP..."))
"Edit"
(("=" lsp-format-region "Format"))
"Navigate"
(("A" lsp-workspace-folders-add "Add Folder")
("R" lsp-workspace-folders-remove "Remove Folder"))
(("a" eglot-code-actions "Code Actions")
("o" eglot-code-action-organize-imports "Organize Imports")
("r" eglot-rename "Rename"))
"Navigation"
(("." xref-find-definitions "Definition")
("/" xref-find-references "References")
("t" eglot-find-typeDefinition "Type Definition")
("i" eglot-find-implementation "Implementation"))
"Docs"
(("D" lsp-describe-thing-at-point "Describe LSP Symbol")
("h" lsp-ui-doc-glance "Glance Help")
("H" lsp-document-highlight "Highlight"))))
(("d" eldoc-doc-buffer "Eldoc Buffer")
("h" eglot-inlay-hints-mode "Inlay Hints")
("=" eglot-format-buffer "Format Buffer"))))
(call-interactively 'lsp))
(use-package lsp-mode
:config
(major-mode-hydra-define+ python-mode (:quit-key "q")
("Server"
(("L" ha-setup-python-lsp "Start LSP Server")))))
;; ----------------------------------------------------------------------
;; Missing Symbols to be integrated?
;; "0" '("treemacs" . lsp-treemacs-symbols)
;; "/" '("complete" . completion-at-point)
;; "k" '("check code" . python-check)
;; "Fb" '("un-blacklist folder" . lsp-workspace-blacklist-remove)
;; "hs" '("signature help" . lsp-signature-activate)
;; "tT" '("toggle treemacs integration" . lsp-treemacs-sync-mode)
;; "ta" '("toggle modeline code actions" . lsp-modeline-code-actions-mode)
;; "th" '("toggle highlighting" . lsp-toggle-symbol-highlight)
;; "tl" '("toggle lenses" . lsp-lens-mode)
;; "ts" '("toggle signature" . lsp-toggle-signature-auto-activate)
( ;; ("L" eglot-ensure "Start eglot") --> Not needed with eglot-ensure
("l" python-lsp/body "LSP...")))))
#+end_src
* Project Configuration
I work with a lot of projects with my team where I need to /configure/ the project such that LSP and my Emacs setup works. Let's suppose I could point a function at a project directory, and have it /set it up/:
@ -541,17 +422,9 @@ I work with a lot of projects with my team where I need to /configure/ the proje
(shell-command "pipconf --local")
(shell-command "pip install --upgrade pip"))
(message "Configuring pip for LSP")
(message "Configuring pip for eglot/pyright")
(with-temp-file "requirements-dev.txt"
(insert "python-lsp-server[all]\n")
;; Let's install these extra packages individually ...
(insert "pyls-flake8\n")
;; (insert "pylsp-mypy")
;; (insert "pyls-isort")
;; (insert "python-lsp-black")
;; (insert "pyls-memestra")
(insert "pylsp-rope\n"))
(insert "pyright\n"))
(shell-command "pip install -r requirements-dev.txt")))
#+end_src
* Major Mode Hydra

View file

@ -229,37 +229,6 @@ The [[https://github.com/r0man/ruby-test-mode][ruby-test-mode]] project aims a r
"t A" '("test all" . ruby-test-run)
"t a" '("retest" . ruby-test-rerun)))
#+end_src
** Robe
The [[https://github.com/dgutov/robe][Robe project]] can be used instead of [[file:ha-programming.org::*Language Server Protocol (LSP) Integration][LSP]].
#+begin_src emacs-lisp
(use-package robe
:config
(ha-local-leader 'ruby-mode-map
"w" '(:ignore t :which-key "robe")
"ws" '("start" . robe-start))
;; The following leader-like keys, are only available when I have
;; started LSP, and is an alternate to Command-m:
:general
(:states 'normal :keymaps 'robe-mode-map
", w r" '("restart" . lsp-reconnect)
", w b" '("events" . lsp-events-buffer)
", w e" '("errors" . lsp-stderr-buffer)
", w q" '("quit" . lsp-shutdown)
", w l" '("load file" . ruby-load-file)
", l r" '("rename" . lsp-rename)
", l f" '("format" . lsp-format)
", l a" '("actions" . lsp-code-actions)
", l i" '("imports" . lsp-code-action-organize-imports)
", l d" '("doc" . lsp-lookup-documentation)))
#+end_src
Do we want to load Robe /automatically/?
#+begin_src emacs-lisp
(use-package robe :hook (ruby-mode . robe-mode))
#+end_src
** Bundler
The [[https://github.com/endofunky/bundler.el][Bundler project]] integrates [[https://bundler.io/][bundler]] to install a projects Gems.
@ -295,6 +264,34 @@ Seems that to understand and edit Cucumber /feature/ definitions, you need [[htt
** RSpec
https://github.com/pezra/rspec-mode
* LSP
The built-in Eglot package natively supports [[https://github.com/castwide/solargraph][Solargraph]] via =eglot-server-programs= (no extra package needed):
#+begin_src emacs-lisp
(use-package eglot
:straight nil
:after ruby-mode
:defer t
:hook (ruby-mode . eglot-ensure))
#+end_src
Keybindings for the eglot-based LSP sub-menu, wired into the =ruby-mode= local leader:
#+begin_src emacs-lisp
(use-package eglot
:straight nil
:after ruby-mode
:config
(ha-local-leader 'ruby-mode-map
"w" '(:ignore t :which-key "eglot")
"wD" '("disconnect" . eglot-shutdown)
"wR" '("reconnect" . eglot-reconnect)
"w?" '("describe" . eglot-show-workspace-configuration)
"wa" '("code actions" . eglot-code-actions)
"wo" '("organize imports" . eglot-code-action-organize-imports)
"wr" '("rename" . eglot-rename)
"w=" '("format buffer" . eglot-format-buffer)))
#+end_src
Need to install [[https://github.com/castwide/solargraph][Solargraph]] for the LSP server experience:
#+begin_src sh
gem install solargraph
@ -303,29 +300,7 @@ Or add it to your =Gemfile=:
#+begin_src ruby
gem 'solargraph', group: :development
#+end_src
* XRef Interface with GNU Global
The [[http://www.gnu.org/software/global/][GNU Global]] has the ability to generate a tags file for large, multi-project Ruby code bases.
First, issue these two:
#+begin_src sh :dir ~/work/gourmet
find . -name .git | while read DOTGIT
do
REPO=$(dirname $DOTGIT)
(cd $REPO && git pull origin master)
done
find . -name "*.rb" > gtags.files
gtags --gtagslabel=new-ctags --file gtags.files
#+end_src
And now we need the GNU Global for Emacs, we are using the most up-to-date version of [[https://github.com/leoliu/ggtags][ggtags]].
#+begin_src emacs-lisp
(use-package ggtags
:hook ((ruby-mode . #'ggtags-mode)))
#+end_src
Careful observers will note that
Once installed, [[*eglot][eglot]] finds and talks to =solargraph= automatically; no further Emacs configuration is needed.
* Technical Artifacts :noexport:
Let's =provide= a name so we can =require= this file:

View file

@ -68,24 +68,10 @@ The [[https://github.com/brotzeit/rustic][rustic project]] incorporates [[https:
#+begin_src emacs-lisp
(use-package rustic
:init
:config
(setq rustic-lsp-client 'eglot
rustic-analyzer-command '("/opt/homebrew/bin/rust-analyzer"))
;; :bind (:map rustic-mode-map
;; ("M-j" . lsp-ui-imenu)
;; ("M-?" . lsp-find-references)
;; ("C-c C-c l" . flycheck-list-errors)
;; ("C-c C-c a" . lsp-execute-code-action)
;; ("C-c C-c r" . lsp-rename)
;; ("C-c C-c q" . lsp-workspace-restart)
;; ("C-c C-c Q" . lsp-workspace-shutdown)
;; ("C-c C-c s" . lsp-rust-analyzer-status)
;; ("C-c C-c e" . lsp-rust-analyzer-expand-macro)
;; ("C-c C-c d" . dap-hydra)
;; ("C-c C-c h" . lsp-ui-doc-glance))
:config
(setq rustic-format-on-save t))
rustic-analyzer-command '("/opt/homebrew/bin/rust-analyzer")
rustic-format-on-save t))
#+end_src
** The Playground
@ -102,7 +88,6 @@ The [[https://github.com/dryman/toml-mode.el][toml-mode]] adds syntax highlighti
#+begin_src emacs-lisp
(use-package toml-mode)
#+end_src
* LSP
* Technical Artifacts :noexport:
Let's =provide= a name so we can =require= this file:

View file

@ -687,86 +687,21 @@ I have two different /jumping/ systems, the [[info:emacs#Xref][Xref interface]]
The [[https://microsoft.github.io/language-server-protocol/][LSP]] is a way to connect /editors/ (like Emacs) to /languages/ (like Lisp)… wait, no. While originally designed for VS Code and probably Python, we can abstract away [[https://github.com/davidhalter/jedi][Jedi]] and the [[http://tkf.github.io/emacs-jedi/latest/][Emacs integration to Jedi]] (and duplicate everything for Ruby, and Clojure, and…).
Emacs has two LSP projects, and while I have used [[LSP Mode]], but since I don’t have heavy IDE requirements, I am finding that [[eglot]] to be simpler.
*** LSP
#+begin_src emacs-lisp
(use-package lsp-mode
:commands (lsp lsp-deferred)
:init
;; Let's make lsp-doctor happy with these settings:
(setq gc-cons-threshold (* 100 1024 1024)
read-process-output-max (* 1024 1024)
company-idle-delay 0.0 ; Are thing fast enough to do this?
lsp-keymap-prefix "s-m")
(use-package eglot
:straight nil
:commands eglot-ensure
:config
(global-set-key (kbd "s-m") 'lsp)
;; (ha-local-leader :keymaps 'prog-mode-map
;; "w" '(:ignore t :which-key "lsp")
;; "l" '(:ignore t :which-key "lsp")
;; "ws" '("start" . lsp))
;; ;; The following leader-like keys, are only available when I have
;; ;; started LSP, and is an alternate to Command-m:
;; :general
;; (:states 'normal :keymaps 'lsp-mode-map
;; ", w r" '("restart" . lsp-reconnect)
;; ", w b" '("events" . lsp-events-buffer)
;; ", w e" '("errors" . lsp-stderr-buffer)
;; ", w q" '("quit" . lsp-shutdown)
;; ", w Q" '("quit all" . lsp-shutdown-all)
;; ", l r" '("rename" . lsp-rename)
;; ", l f" '("format" . lsp-format)
;; ", l a" '("actions" . lsp-code-actions)
;; ", l i" '("imports" . lsp-code-action-organize-imports)
;; ", l d" '("doc" . lsp-lookup-documentation))
:hook ((lsp-mode . lsp-enable-which-key-integration)))
(setq eglot-autoshutdown t))
#+end_src
I will want to start adding commands under my =,= mode-specific key sequence leader, but in the meantime, all LSP-related keybindings are available under ~⌘-m~. See [[https://emacs-lsp.github.io/lsp-mode/page/keybindings/][this page]] for the default keybindings.
Using the [[https://github.com/seagle0128/doom-modeline][Doom Modeline]] to add notifications:
The [[https://github.com/flycheck/flycheck-eglot][flycheck-eglot]] package bridges eglot diagnostics into flycheck, so existing checkers and keybindings continue to work unchanged:
#+begin_src emacs-lisp
(use-package doom-modeline
(use-package flycheck-eglot
:after (flycheck eglot)
:config
(setq doom-modeline-lsp t
doom-modeline-env-version t))
#+end_src
**** UI
The [[https://github.com/emacs-lsp/lsp-ui][lsp-ui]] project offers much of the display and interface to LSP. Seems to make the screen cluttered.
#+begin_src emacs-lisp
(use-package lsp-ui
:commands lsp-ui-mode
:config
(setq lsp-ui-sideline-ignore-duplicate t
lsp-ui-sideline-show-hover t
lsp-ui-sideline-show-diagnostics t)
:hook (lsp-mode . lsp-ui-mode))
#+end_src
*** Company Completion
The [[https://github.com/tigersoldier/company-lsp][company-lsp]] offers a [[http://company-mode.github.io/][company]] completion backend for [[https://github.com/emacs-lsp/lsp-mode][lsp-mode]]:
#+begin_src emacs-lisp :tangle no
(use-package company-lsp
:config
(push 'company-lsp company-backends))
#+end_src
To options that might be interesting:
- =company-lsp-async=: When set to non-nil, fetch completion candidates asynchronously.
- =company-lsp-enable-snippet=: Set it to non-nil if you want to enable snippet expansion on completion. Set it to nil to disable this feature.
*** LSP iMenu
The [[https://github.com/emacs-lsp/lsp-ui/blob/master/lsp-ui-imenu.el][lsp-imenu]] project offers a =lsp-ui-imenu= function for jumping to functions:
#+begin_src emacs-lisp :tangle no
(use-package lsp-ui-imenu
:straight nil
:after lsp-ui
:config
(ha-local-leader :keymaps 'prog-mode-map
"g" '(:ignore t :which-key "goto")
"g m" '("imenu" . lsp-ui-imenu))
(add-hook 'lsp-after-open-hook 'lsp-enable-imenu))
(global-flycheck-eglot-mode 1))
#+end_src
** General Code Editing
*** iEdit
@ -1080,9 +1015,8 @@ So many configuration files to track:
("\\.setup.*\\'" . conf-space-mode)))
#+end_src
** JSON
While interested in the [[https://github.com/emacs-tree-sitter/tree-sitter-langs][tree-sitter]] extensions for JSON, e.g. =json-ts-mode=, that comes with Emacs 29, I’ll deal with what is bundled now.
I’m interested in the [[https://github.com/emacs-tree-sitter/tree-sitter-langs][tree-sitter]] extensions for JSON, e.g. =json-ts-mode=, that comes with Emacs 29, but instead of /searching/ for particular data in a JSON buffer, what about whittling that data with [[https://jqlang.github.io/jq/][jq]]?
However, what about taking a buffer of JSON data, and whittling it down with [[https://jqlang.github.io/jq/][jq]]?
#+begin_src emacs-lisp
(defun ha-json-buffer-to-jq (query)
"Runs JSON buffer with QUERY through an external `jq' program.
@ -1163,12 +1097,14 @@ I can type, ~, j~ and then type =.data.timeout.seconds= and end up with:
300
#+end_src
** Markdown
Most project =README= files and other documentation use [[https://jblevins.org/projects/markdown-mode/][markdown-mode]]. Note that the /preview/ is based on =multimarkdown=, when needs to be /pre-installed/, for instance:
Most projects’ =README= files and other documentation use [[https://jblevins.org/projects/markdown-mode/][markdown-mode]]. Note that the /preview/ uses =multimarkdown=, which should be /pre-installed/. For instance:
#+begin_src sh
brew install multimarkdown
#+end_src
Also, I like Markdown is look like a word processor, similarly to my org files:
Also, I like Markdown to look like a word processor, similarly to my org files:
#+begin_src emacs-lisp
(use-package markdown-mode
:mode ((rx ".md" string-end) . gfm-mode)
@ -1193,51 +1129,14 @@ Also, I like Markdown is look like a word processor, similarly to my org files:
Note that the markdown-specific commands use the ~C-c C-c~ and ~C-c C-s~ prefixes.
Let’s make sure that [[https://www.flycheck.org/en/latest/languages.html#markdown][markdown]] is proper using [[https://pypi.org/project/pymarkdownlnt/][PyMarkdown]]. First, get the script installed globally:
The [[https://github.com/Fanael/edit-indirect/blob/master/edit-indirect.el][edit-indirect]] code allows me to edit triple-backtick code in a separate buffer.
#+begin_src sh
pip install pymarkdown
#+end_src
#+BEGIN_SRC emacs-lisp
(use-package edit-indirect)
#+END_SRC
And then we can use it. For some reason, the =pymarkdown= (which I need to use from work) doesn’t seem to be part of the version of Flycheck available on Melpa, so…
#+begin_src emacs-lisp
(use-package markdown-mode
:after flycheck
:config
(setq flycheck-markdown-pymarkdown-config
(expand-file-name ".pymarkdown.yml" (getenv "HOME")))
(flycheck-may-enable-checker 'markdown-pymarkdown))
#+end_src
Ugh
#+begin_src emacs-lisp
(flycheck-def-config-file-var flycheck-markdown-pymarkdown-config
markdown-pymarkdown nil
:package-version '(flycheck . "34"))
(flycheck-define-checker markdown-pymarkdown
"Markdown checker using PyMarkdown.
See URL `https://pypi.org/project/pymarkdownlnt/'."
:command ("pymarkdown"
(config-file "--config" flycheck-markdown-pymarkdown-config)
"scan"
source)
:error-patterns
((error line-start
(file-name) ":" line
(? ":" column) ": " (id (one-or-more alnum))
": " (message) line-end))
:error-filter
(lambda (errors)
(flycheck-sanitize-errors
(flycheck-remove-error-file-names "(string)" errors)))
:modes (markdown-mode gfm-mode))
#+end_src
Both the =markdown-command= and the =markdown-open-command= variables are called to render (and preview) a Markdown file (~C-c C-c o~), and calls the following scripts (which in turn, call =pandoc= as I depend on this for other org-related features):
*** Rendering with Pandoc
We call both the =markdown-command= and the =markdown-open-command= variables to render (and preview) a Markdown file (~C-c C-c o~), and calls the following scripts (which in turn, call =pandoc= as I depend on this for other org-related features):
#+begin_src sh :tangle ~/bin/markdown :shebang "#!/usr/bin/env bash" :tangle-mode u+x
pandoc --to=html --from=gfm $*
@ -1256,6 +1155,250 @@ Both the =markdown-command= and the =markdown-open-command= variables are called
fi
#+end_src
*** PyMarkdown
My teams have standardized on “linting” markdown files using [[https://pypi.org/project/pymarkdownlnt/][PyMarkdown]], specifying a =.pymarkdown.yml= to configure what is allowed. For instance:
#+BEGIN_SRC yaml :tangle no
---
# Enable front-matter extensions, as Hugo needs them.
extensions:
front-matter:
enabled: true
plugins:
md013:
enabled: true
line_length: 80
heading_line_length: 80
code_block_line_length: 160
#+END_SRC
Flycheck ships the =markdown-pymarkdown= checker itself, so all it wants is the configuration file.
Note that PyMarkdown does /not/ look for =.pymarkdown.yml= on its own — it only reads a configuration passed with =--config=. Naming the file without a directory hands the search to flycheck, whose =flycheck-locate-config-file-functions= walks the ancestor directories with =locate-dominating-file= and then falls back to my home directory. A repository that defines its own rules therefore gets them, and everything else gets my defaults:
#+begin_src emacs-lisp
(use-package flycheck
:config
(setq flycheck-markdown-pymarkdown-config ".pymarkdown.yml"))
#+end_src
*** Remark
The [[https://github.com/remarkjs/remark][Remark]] project can transform markdown with plugins, evaluating and changing through its pipeline. This means I can apply [[file:ha-org.org::*Writegood][Writegood]] intelligently to a Markdown file, ignoring code blocks, etc. Prose is the /only/ job it has here, and [[*Remark and Flycheck][flycheck chains the two together]].
The =remark= executable itself lives globally, since flycheck calls it by name:
#+begin_src sh
npm install -g remark-cli
#+end_src
The /plugins/, however, can not. The configuration file below uses ESM =import= statements, and Node resolves those specifiers relative to /importing the file/, as globally installed packages are not on the path. The =~/.config/remark= directory has to be a self-contained package with its own =node_modules=, with a =package.json= file.
Note the ="type": "module"= entry belongs here too, otherwise Node parses each =.js= file as CommonJS, fails, and re-parses it as a module while complaining:
#+begin_src js :tangle ~/.config/remark/package.json :mkdirp yes
{
"name": "remark-config",
"private": true,
"type": "module",
"dependencies": {
"remark-frontmatter": "^5.0.0",
"remark-lint-write-good": "^1.2.0",
"unist-util-visit": "^5.1.0"
}
}
#+end_src
After tangling that the above file, we install the plugins /into the =.config/remark= directory/:
#+begin_src sh :dir ~/.config/remark
npm install
#+end_src
Let’s create a /code-stripping/ plugin that removes all text but the prose of a Markdown document. We can then validate the prose with =write-good= on the results:
#+begin_src js :tangle ~/.config/remark/ignore-code.js :mkdirp yes
import { visit } from 'unist-util-visit';
// Bare URLs and autolinks land in `text` nodes, where write-good
// grades the path segments as if they were prose. A `[label](url)`
// needs no help here, since the url of a link node never reaches
// the prose checker anyway.
const URL_PATTERN = /\b(?:https?:\/\/|www\.)[^\s<>()[\]{}'"]+/gi;
/** Spaces of equal length, so line numbers and offsets survive. */
const blank = (text) => ' '.repeat(text.length);
export default function remarkIgnoreCode() {
return (tree) => {
visit(tree, ['code', 'inlineCode'], (node) => {
// Replaces code block and backtick content with spaces of
// equal length. This silences linters while preserving line
// numbers and offsets.
node.value = blank(node.value);
});
visit(tree, 'text', (node) => {
node.value = node.value.replace(URL_PATTERN, (match) => {
// Trailing punctuation stays, so sentence boundaries are
// not merged.
const url = match.replace(/[.,;:!?]+$/, '');
return blank(url) + match.slice(url.length);
});
});
};
}
#+end_src
A path like =/a/very/long/= reads as weasel words to =write-good=, so blanking the URL is what keeps =very= and =obviously= out of the report. The =[label](url)= form is left alone deliberately: its label /is/ prose worth grading, and its url was never visited. Trailing punctuation survives so that =…/foo.= still ends a sentence, rather than running it into the next one.
**** Configuring the pipeline
The other plugins have been made, so Remark’s configuration file (=.config/remark/remarkrc.js=) pulls them in, and creates an ordered plugin pipeline. Note the absence of any =remark-preset-lint-*= entry: those presets check structure, which is PyMarkdown’s half of the work, and they disagree with it often enough to be worth leaving out. Left in, they wanted every ATX heading rewritten as setext:
#+begin_src js :tangle ~/.config/remark/.remarkrc.js
import remarkFrontmatter from 'remark-frontmatter';
import remarkWriteGood from 'remark-lint-write-good';
import remarkIgnoreCode from './ignore-code.js';
export default {
plugins: [
// 1. Recognise YAML front matter, so its metadata is not
// read as prose
remarkFrontmatter,
// 2. Erase backticks/code blocks before the prose check
remarkIgnoreCode,
// 3. Check English writing quality, the sole
// job remark has, since PyMarkdown already covers
// structure and formatting.
remarkWriteGood
]
};
#+end_src
The order matters, since plugins run as transformers in sequence: =remarkIgnoreCode= has to blank the code out before =remarkWriteGood= gets a look at what is left.
And =remarkFrontmatter= earns its place, rather than being tidiness. Without it, a =---= delimiter usually turns the metadata into a setext heading, which =write-good= happens to skip — but only by luck. Put a blank line in the front matter and the first key becomes an ordinary paragraph, at which point =title:= gets graded as prose:
#+begin_src markdown :tangle no
---
title: This value is very obviously scanned as prose
description: short
---
#+end_src
Worth knowing what =write-good= looks at, since it only visits =paragraph= nodes: headings are never checked, and blockquotes are skipped on purpose, on the reasoning that quoted words are somebody else’s.
Verify on the command line using the =rc-path= parameter:
#+begin_src sh :tangle no
remark --rc-path ~/.config/remark/.remarkrc.js README.md
#+end_src
**** Remark and Flycheck
Remark’s default report groups messages under a file name header and gives each one a =line:column-line:column= range, which takes more regular expression than I care to write. Instead, let’s hand it a [[https://github.com/vfile/vfile-reporter][vfile reporter]] of our own that prints one message per line in a shape flycheck parses with a single pattern:
#+begin_src js :tangle ~/.config/remark/flycheck-reporter.js
/**
* A vfile reporter that emits one message per line in a format that is
* trivial for Emacs' flycheck to parse with a single regular expression:
*
* LINE:COLUMN:SEVERITY:[ruleId] reason
*
* The file name is deliberately omitted; flycheck lints one buffer at a
* time and attributes patterns without a file name to that buffer, which
* avoids the mismatch between the buffer's directory and remark's cwd.
*/
export default function flycheckReporter(files) {
const lines = [];
for (const file of [files].flat()) {
for (const message of file.messages) {
// `fatal` is true for errors, false for warnings, null/undefined for info.
const severity =
message.fatal === true
? 'error'
: message.fatal === false
? 'warning'
: 'info';
const rule = message.ruleId || message.source || 'remark';
// Newlines would break the one-message-per-line contract.
const reason = String(message.reason).replace(/\s*\n\s*/g, ' ');
lines.push(
`${message.line || 1}:${message.column || 1}:${severity}:[${rule}] ${reason}`
);
}
}
return lines.join('\n');
}
#+end_src
Which we can check by hand:
#+begin_src sh
remark --no-color --no-stdout \
--rc-path ~/.config/remark/.remarkrc.js \
--report ~/.config/remark/flycheck-reporter.js README.md
#+end_src
Two flags there earn their keep. Remark writes the /transformed/ document to standard output by default, and since =remarkIgnoreCode= replaces code with whitespace, that output is a mangled copy of the file. The =--no-stdout= parameter throws it away, guaranteeing a stray =--output= can never overwrite the real file with it. Also =--no-color= keeps ANSI escapes out of what flycheck has to parse.
Note that both paths are absolute. Remark resolves a /reporter/ relative to the current directory, but a configuration file relative to the file being linted, so neither would be found from an arbitrary project directory.
Note that =flycheck-define-checker= only /defines/ the checker; the =add-to-list= is what puts it in rotation. The trailing =t= appends rather than prepends, which is the whole trick to chaining: flycheck picks the /first/ checker in =flycheck-checkers= that claims the buffer, so leaving =markdown-remark= behind the built-in =markdown-pymarkdown= lets PyMarkdown go first and remark follow it.
#+begin_src emacs-lisp
(use-package flycheck
:config
(flycheck-def-config-file-var flycheck-markdown-remark-config markdown-remark
(expand-file-name ".remarkrc.js" "~/.config/remark")
:package-version '(flycheck . "34"))
(defcustom flycheck-markdown-remark-reporter
(expand-file-name "flycheck-reporter.js" "~/.config/remark")
"Path to the vfile reporter that formats remark messages for flycheck."
:type 'string
:group 'flycheck)
(flycheck-define-checker markdown-remark
"A Markdown prose checker using remark and write-good.
See URL `https://github.com/remarkjs/remark'."
:command ("remark"
"--no-color"
"--no-stdout"
(config-file "--rc-path" flycheck-markdown-remark-config)
"--report" (eval flycheck-markdown-remark-reporter)
source)
:error-patterns
((error line-start line ":" column ":error:["
(id (one-or-more (not (any "]")))) "] " (message) line-end)
(warning line-start line ":" column ":warning:["
(id (one-or-more (not (any "]")))) "] " (message) line-end)
(info line-start line ":" column ":info:["
(id (one-or-more (not (any "]")))) "] " (message) line-end))
:modes (markdown-mode gfm-mode))
(add-to-list 'flycheck-checkers 'markdown-remark t)
;; Structure first, then prose, in one report.
(flycheck-add-next-checker 'markdown-pymarkdown 'markdown-remark)
;; Then terminology/consistency, since flycheck's built-in textlint
;; checker already declares markdown-mode/gfm-mode and picks the
;; @textlint/markdown plugin for them -- no new checker needed.
(flycheck-add-next-checker 'markdown-remark 'textlint t))
#+end_src
Naming =markdown-remark= as a plain symbol, rather than a =(level . checker)= cons cell, means the prose check runs whatever PyMarkdown found. Were it written =(warning . markdown-remark)=, a single formatting error would swallow the prose report along with it.
Since remark now runs =write-good= over the prose (and more carefully, as it skips the code), the [[file:ha-org.org::*Writegood][write-good]] checker no longer lists =markdown-mode= among its modes, and the two do not double up.
[[file:ha-org.org::*Textlint][Textlint]] runs last in the chain. Its bundled Markdown plugin parses the AST itself, so it skips fenced code without any =ignore-code.js=-style help, and =flycheck-textlint-plugin-alist= already maps =markdown-mode=/=gfm-mode= to =@textlint/markdown=.
*** Markdown and Polymode
Using [[https://polymode.github.io/][polymode]], let’s add syntax coloring to Markdown code blocks similar to what we do with Org:
#+begin_src emacs-lisp
@ -1359,16 +1502,6 @@ Integration with the [[https://github.com/bash-lsp/bash-language-server][Bash LS
#+begin_src sh
brew install bash-language-server
#+end_src
*** Fish Shell
I think the [[https://fishshell.com/][fish shell]] is an interesting experiment (and I appreciate the basics that come with [[https://github.com/emacsmirror/fish-mode][fish-mode]]).
#+begin_src emacs-lisp
(use-package fish-mode
:mode (rx ".fish" eol)
:config
(ha-auto-insert-file (rx ".fish") "fish-mode.sh")
:hook
(fish-mode . (lambda () (add-hook 'before-save-hook 'fish_indent-before-save))))
#+end_src
* Technical Artifacts :noexport:
Provide a name to =require= this code.
#+begin_src emacs-lisp :exports none

View file

@ -124,7 +124,7 @@ I'm not giving up on Eshell, but I am playing around with [[https://github.com/a
VTerm has an issue (at least for me) with ~M-Backspace~ not deleting the previous word, and yeah, I want to make sure that both keystrokes do the same thing.
#+begin_src emacs-lisp
#+begin_src emacs-lisp :tangle no
(use-package vterm
:config
(setq vterm-shell "zsh"
@ -162,7 +162,7 @@ An odd use case I have: working in a Terminal session in one buffer window, and
Now, I can type: ~s-G~ (with the shift), select the line with Avy, and type ~N~ to have it copy/paste into the buffer:
#+BEGIN_SRC emacs-lisp
#+BEGIN_SRC emacs-lisp :tangle no
(use-package vterm
:config
(defun ha-vterm-avy-paste-line ()
@ -180,7 +180,7 @@ Now, I can type: ~s-G~ (with the shift), select the line with Avy, and type ~N~
** Eat
While not as fast as [[https://github.com/akermu/emacs-libvterm][vterm]], the [[https://codeberg.org/akib/emacs-eat][Emulate a Terminal]] project (eat) is fast enough, and doesn’t require a dedicate library that requires re-compilation. While offering [[https://elpa.nongnu.org/nongnu-devel/doc/eat.html][online documentation]], I’m glad for an [[info:eat#Top][Info version]].
#+BEGIN_SRC emacs-lisp :tangle no
#+BEGIN_SRC emacs-lisp
(use-package eat
:quelpa (:fetcher codeberg :repo "akib/emacs-eat"
:files ("*.el" ("term" "term/*.el") "*.texi"
@ -192,6 +192,25 @@ While not as fast as [[https://github.com/akermu/emacs-libvterm][vterm]], the [[
:bind (:map eat-semi-char-mode-map
("C-c C-t" . ha-eat-narrow-to-shell-prompt-dwim))
:config
;; Red:
(set-face-attribute 'eat-term-color-1 nil :foreground "#b78077")
(set-face-attribute 'eat-term-color-9 nil :foreground "#d45d4c")
;; Green:
(set-face-attribute 'eat-term-color-2 nil :foreground "#879a39")
(set-face-attribute 'eat-term-color-10 nil :foreground "#66800b")
;; Yellow:
(set-face-attribute 'eat-term-color-2 nil :foreground "#d0a215")
(set-face-attribute 'eat-term-color-10 nil :foreground "#ad8301")
;; Blue
(set-face-attribute 'eat-term-color-2 nil :foreground "#4385be")
(set-face-attribute 'eat-term-color-10 nil :foreground "#205ea6")
;; Magenta:
(set-face-attribute 'eat-term-color-2 nil :foreground "#ce5d97")
(set-face-attribute 'eat-term-color-10 nil :foreground "#a02f6f")
;; Cyan
(set-face-attribute 'eat-term-color-2 nil :foreground "#3aa99f")
(set-face-attribute 'eat-term-color-10 nil :foreground "#24837b")
(defun ha-eat-narrow-to-shell-prompt-dwim ()
(interactive)
(if (buffer-narrowed-p) (widen) (eat-narrow-to-shell-prompt)))
@ -214,8 +233,6 @@ What about Evil mode?
TODO: Like =eshell=, the Bash in an EAT terminal has a command =_eat_msg= that takes a handler, and a /message/. Then set up an alist of =eat-message-handler-alist= to decide what to do with it.
TODO: Need to /subtlize/ the =eat-term-color-bright-green= and other settings as it is way too garish.
Make sure you add the following for Bash:
#+BEGIN_SRC bash :tangle no

View file

@ -330,6 +330,7 @@ Let’s make a /theme/:
`(mode-line ((t (:background ,active :foreground "white"))))
`(mode-line-active ((t (:background ,active))))
`(mode-line-inactive ((t (:background ,inactive))))
`(which-func ((t (:foreground ,orange-lt))))
`(tab-bar ((t :foreground ,default-fg :background ,inactive :inherit variable-pitch)))
`(tab-line ((t :foreground ,default-fg :background ,inactive)))
@ -437,6 +438,20 @@ Let’s make a /theme/:
`(term-color-bright-yellow ((t (:foreground ,yellow))))
`(term-color-bright-cyan ((t (:foreground ,slate))))
`(ansi-color-red ((t (:foreground ,red2-lt :background nil))))
`(ansi-color-green ((t (:foreground ,green-lt :background nil))))
`(ansi-color-blue ((t (:foreground ,blue-lt :background nil))))
`(ansi-color-magenta ((t (:foreground ,purple-lt :background nil))))
`(ansi-color-yellow ((t (:foreground ,yellow-lt :background nil))))
`(ansi-color-cyan ((t (:foreground ,slate :background nil))))
`(ansi-color-bright-red ((t (:foreground ,red2 :background nil))))
`(ansi-color-bright-green ((t (:foreground ,green :background nil))))
`(ansi-color-bright-blue ((t (:foreground ,blue :background nil))))
`(ansi-color-bright-magenta ((t (:foreground ,purple :background nil))))
`(ansi-color-bright-yellow ((t (:foreground ,yellow :background nil))))
`(ansi-color-bright-cyan ((t (:foreground ,slate :background nil))))
`(ansi-color-bright-black ((t (:foreground ,gray-50 :background nil))))
`(sh-heredoc ((t (:foreground ,almond))))
`(sh-quoted-exec ((t (:foreground ,orange2-lt))))

View file

@ -2,7 +2,7 @@
#+author: Howard X. Abrams
#+date: 2025-11-24
#+filetags: emacs hamacs
#+lastmod: [2026-06-15 Mon]
#+lastmod: [2026-10-09 Fri]
A literate programming file for configuring Hammerspoon.
@ -14,81 +14,141 @@ Simple to use. Use =hs.execute= to run a script, =ha.alert.show= to print a smal
hs.notify.new({title="Hammerspoon", informativeText="Hello World"}):send()
#+END_SRC
** The Command Line
The =hs= binary talks to a running Hammerspoon over a Mach port, and that port only exists while the =hs.ipc= module is loaded. Without this line, the tool answers every request with /can’t access Hammerspoon message port/, however well it is installed:
#+BEGIN_SRC lua
require("hs.ipc")
#+END_SRC
For instance, using the [[*Zoom][Zoom spoon]], I can toggle the mute button from a script:
#+BEGIN_SRC sh :tangle no
hs -c "spoon.Zoom:toggleMute()" # your Zoom spoon, from anywhere
#+END_SRC
Or callable from Emacs.
Other ideas:
1. Tail the Hammerspoon console in a terminal with =hs -C=, which shows anything called with =printf=.
2. While I already built out [[https://howardism.org/Technical/Emacs/beep-for-emacs.html][a notification system]], I could use Hammerspoon to replace =beep= CLI:
#+BEGIN_SRC sh
make build; hs -c 'hs.notify.new({title="Build", informativeText="done"}):send()'
#+END_SRC
3. Query Hammerspoon to query the system:
#+BEGIN_SRC bash :results replace raw output
hs -c 'return hs.wifi.currentNetwork()'
#+END_SRC
This should return =iTerm2=, or =Emacs= when running from my literate config:
#+BEGIN_SRC sh :results replace raw output
hs -c "return hs.application.frontmostApplication():name()"
#+END_SRC
Or screwing with my monitors:
#+BEGIN_SRC sh :results replace raw output
hs -c "return hs.screen.mainScreen():name()"
#+END_SRC
Or the volume level as a float value:
#+BEGIN_SRC sh :results replace raw output
hs -c "return hs.audiodevice.defaultOutputDevice():volume()"
#+END_SRC
Flags worth knowing, from the binary's usage text:
* =-i= interactive REPL
* =-q= quiet (only the result, ideal for scripting)
* =-c= repeatable
* =-A= auto-launch Hammerspoon if not running, and a bare file path to run a =.lua= file.
* Shortcut Keybindings
I’ve created left and right ~Meh~ keys on my Moonlanders:
I’ve created left and right ~Meh~ keys on my Moonlander keyboard:
- Left Meh Key: ~C-M-S-s~ (Control Option/Meta Command Shift)
- Right Meh Key: ~C-M-S~ (Control Option/Meta Shift)
To create special key bindings, I can:
To create specific key bindings for starting applications, I can:
#+BEGIN_SRC lua
----------------------------------------------------------------------
-- Launcher replaces iCanHazShortcuts
----------------------------------------------------------------------
-- Launcher replaces iCanHazShortcuts
hs.hotkey.bind({"alt", "ctrl", "shift"}, "T", function()
hs.application.launchOrFocus("iTerm")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "S", function()
hs.application.launchOrFocus("Slack")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "S", function()
hs.application.launchOrFocus("Slack")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "F", function()
hs.application.launchOrFocus("Vivaldi")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "F", function()
hs.application.launchOrFocus("Safari")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "C", function()
hs.application.launchOrFocus("Google Chrome")
-- hs.execute("~/bin/chrome.scr")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "C", function()
-- hs.osascript.applescriptFromFile("~/bin/chrome.scr")
hs.execute("~/bin/chrome.scr")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "G", function()
hs.application.launchOrFocus("Gmail")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "B", function()
hs.application.launchOrFocus("Microsoft Outlook")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "J", function()
hs.application.launchOrFocus("JIRA")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "Z", function()
hs.application.launchOrFocus("zoom.us")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "B", function()
hs.application.launchOrFocus("Google Calendar")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "Q", function()
hs.application.launchOrFocus("KeepassXC")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "Z", function()
hs.application.launchOrFocus("zoom.us")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "W", function()
hs.application.launchOrFocus("VLC")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "Q", function()
hs.application.launchOrFocus("KeepassXC")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "E", function()
hs.execute("FOR_WORK=yes open -a /Applications/Emacs.app")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "V", function()
hs.application.launchOrFocus("VLC")
end)
-- Special Emacs Guys
-- Right Meh key:
hs.hotkey.bind({"alt", "ctrl", "shift"}, "X", function()
hs.execute("~/bin/emacs-capture")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "W", function()
hs.application.launchOrFocus("Mail")
end)
-- Left Meh key:
hs.hotkey.bind({"cmd", "alt", "ctrl", "shift"}, "X", function()
hs.execute("~/bin/emacs-capture-clock")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "T", function()
hs.application.launchOrFocus("iTerm")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "M", function()
hs.execute("~/bin/emacs-capture-meeting")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "E", function()
hs.execute("FOR_WORK=yes open -a /Applications/Emacs.app")
end)
-- Current music system is actually in Emacs:
hs.hotkey.bind({"alt", "ctrl", "shift"}, "R", function()
hs.execute("/opt/homebrew/bin/emacsclient -s work -e '(ready-player-toggle-play-stop)'")
end)
-- Special Emacs Guys
-- Right Meh key:
hs.hotkey.bind({"alt", "ctrl", "shift"}, "X", function()
hs.execute("~/bin/emacs-capture")
end)
-- Left Meh key:
hs.hotkey.bind({"cmd", "alt", "ctrl", "shift"}, "X", function()
hs.execute("~/bin/emacs-capture-clock")
end)
hs.hotkey.bind({"alt", "ctrl", "shift"}, "M", function()
hs.execute("~/bin/emacs-capture-meeting")
end)
-- Current music system is actually in Emacs:
hs.hotkey.bind({"alt", "ctrl", "shift"}, "R", function()
hs.execute("/opt/homebrew/bin/emacsclient -s work -e '(ready-player-toggle-play-stop)'")
end)
#+END_SRC
#+END_SRC
* Zoom
Library extensions to Hammerspoon are called /spoons/, and most of these are a simple Lua script, =init.lua= stored in the =Spoons= subdirectory. We grab these with a =git clone=, typically. To use the Zoom spoon, clone it:
/Spoons/ are library extensions to Hammerspoon: usally small Lua scripts, like =init.lua=, stored in the =Spoons= subdirectory. Installable from a =git clone=, typically. To use the Zoom spoon, clone it:
#+BEGIN_SRC sh :dir ~/.hammerspoon/Spoons :tangle no :results silent
git clone https://github.com/jpf/Zoom.spoon.git
#+END_SRC
I noticed that it does its works by calling Zoom’s menus, and with the latest version of Zoom, they changed the /case/ of the menu, meaning that I needed to create a pull request.
I noticed that this library does most of its work by calling Zoom’s menus, and with the latest version of Zoom, they changed the /case/ of the menu, meaning that I needed to create a pull request.
From this [[https://developer.okta.com/blog/2020/10/22/set-up-a-mute-indicator-light-for-zoom-with-hammerspoon][nice essay]], we create a menu bar item that shows the status, as well as allowing me to click it to toggle:
@ -166,7 +226,8 @@ Leaving my home office and hopping on the train can be socially awkward when my
lastSSID = newSSID
end
hs.wifi.watcher.new(ssidChangedCallback):start()
wifiWatcher = hs.wifi.watcher.new(ssidChangedCallback)
wifiWatcher:start()
#+END_SRC
Why yes, I’m /looking for features/ to use Hammerspoon.
@ -182,10 +243,19 @@ I want to use Org’s task clocking ability, but I often forget to /clock out/.
end
end
sleepWatcher = hs.caffeinate.watcher.new(sleepWatch)
sleepWatcher:start()
#+END_SRC
Discovered a subtle bug, solving it meant assigning the =watcher= to a variable, rather than starting it and dropping the value. For instance, if I call the =start= this way:
#+BEGIN_SRC lua :tangle no
hs.caffeinate.watcher.new(sleepWatch):start()
#+END_SRC
Not that we could also do something for Wake:
Since nothing else refers to that object once the line finishes, Lua may collect it, and a collected watcher stops delivering events without a word about it.
Note if I want to do something for Wake:
#+BEGIN_SRC lua :tangle no
if (eventType == hs.caffeinate.watcher.systemDidWake) then
@ -243,6 +313,24 @@ My company gave me a nice monitor … maybe a little too nice, as I don’t care
hs.hotkey.bind({"cmd", "alt", "ctrl", "shift"}, "Y", centerWindow)
#+END_SRC
Similarly, I sometimes want a window as large as possible, but flushed to the edges of the monitor (a maximized frame, not macOS' native /full screen/):
#+BEGIN_SRC lua
----------------------------------------------------------------------
-- Making a window as large as possible on its current monitor:
function fullWindow()
local win = hs.window.focusedWindow()
if not win then return end -- Safety check in case no window is focused
local screen = win:screen()
win:setFrame(screen:frame())
hs.alert.show("Full Window")
end
hs.hotkey.bind({"cmd", "alt", "ctrl", "shift"}, "U", fullWindow)
#+END_SRC
* Auto Reload Configuration
Whenever my configuration file is altered (or with a ~Meh-R~ key), I reload the configuration:
@ -267,9 +355,12 @@ Whenever my configuration file is altered (or with a ~Meh-R~ key), I reload the
end
end
hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reloadConfig):start()
configWatcher = hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reloadConfig)
configWatcher:start()
#+END_SRC
Every watcher in this file now lives in a variable of its own, for the reason described under [[*Clocking out a Task][clocking out]]. This one failing is the quietest of the three, as a dead configuration watcher looks exactly like a file that saved without incident.
* Technical Artifacts :noexport:
#+BEGIN_SRC lua
hs.alert.show("Hammerspoon Configuration")
@ -285,3 +376,7 @@ Whenever my configuration file is altered (or with a ~Meh-R~ key), I reload the
#+OPTIONS: num:nil toc:nil todo:nil tasks:nil tags:nil date:nil
#+OPTIONS: skip:nil author:nil email:nil creator:nil timestamp:nil
#+INFOJS_OPT: view:nil toc:nil ltoc:t mouse:underline buttons:0 path:http://orgmode.org/org-info.js
# Local Variables:
# jinx-local-words: "Lua"
# End:

View file

@ -5,3 +5,4 @@
#+END_SRC
`yas-selected-text`
#+BEGIN_SRC `(ha-org-block-language-and)`

View file

@ -2,4 +2,4 @@
# name: title
# key: title
# --
#+title: ${0}
#+TITLE: ${0}

View file

@ -8,9 +8,6 @@
* Work Issues
$0
* Onboarding Work
See [[file:Onboarding-Work.org][Onboard-Work]] for all details.
* Distractions and Support
Anything that doesn't fit the above goes here.

View file

@ -224,6 +224,12 @@ Using the =colorize= plugin (see [[Plugins][plugins section below]]), we customi
export ZSH_COLORIZE_STYLE="coffee"
#+END_SRC
While we are at it, let’s make it easier to read the =ls= output:
#+BEGIN_SRC zsh
export LS_COLORS="rs=0:di=01;34:ln=01;36:mh=00:pi=33:so=01;35:do=01;35:bd=33;01:cd=33;01:or=31;01:mi=00:su=37:sg=30:ca=00:tw=30:ow=34:st=37:ex=01;32:*.7z=01;31:*.ace=01;31:*.alz=01;31:*.apk=01;31:*.arc=01;31:*.arj=01;31:*.bz=01;31:*.bz2=01;31:*.cab=01;31:*.cpio=01;31:*.crate=01;31:*.deb=01;31:*.drpm=01;31:*.dwm=01;31:*.dz=01;31:*.ear=01;31:*.egg=01;31:*.esd=01;31:*.gz=01;31:*.jar=01;31:*.lha=01;31:*.lrz=01;31:*.lz=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.lzo=01;31:*.pyz=01;31:*.rar=01;31:*.rpm=01;31:*.rz=01;31:*.sar=01;31:*.swm=01;31:*.t7z=01;31:*.tar=01;31:*.taz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tgz=01;31:*.tlz=01;31:*.txz=01;31:*.tz=01;31:*.tzo=01;31:*.tzst=01;31:*.udeb=01;31:*.war=01;31:*.whl=01;31:*.wim=01;31:*.xz=01;31:*.z=01;31:*.zip=01;31:*.zoo=01;31:*.zst=01;31:*.avif=01;35:*.jpg=01;35:*.jpeg=01;35:*.jxl=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.webp=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:*~=00;90:*#=00;90:*.bak=00;90:*.crdownload=00;90:*.dpkg-dist=00;90:*.dpkg-new=00;90:*.dpkg-old=00;90:*.dpkg-tmp=00;90:*.old=00;90:*.orig=00;90:*.part=00;90:*.rej=00;90:*.rpmnew=00;90:*.rpmorig=00;90:*.rpmsave=00;90:*.swp=00;90:*.tmp=00;90:*.ucf-dist=00;90:*.ucf-new=00;90:*.ucf-old=00;90:"
#+END_SRC
** Language Support
Anything special for particular languages.
@ -486,8 +492,15 @@ The =EDITOR= variable that some programs use to edit files from the command line
With these variables defined, we can create simple aliases:
#+BEGIN_SRC zsh
alias e="$EDITOR"
alias te="$EDITOR"
if [[ -n "$INSIDE_EMACS" ]]
then
# If we are already in Emacs, no need to stall the terminal:
e() { emacsclient --eval "(find-file-other-window \"$1\")" }
te() { emacsclient --eval "(find-file \"$1\")" }
else
alias e="$EDITOR"
alias te="$EDITOR"
fi
alias ee="emacsclient --create-frame"
alias eee="emacsclient --create-frame --no-wait"
#+END_SRC
@ -496,7 +509,7 @@ With these variables defined, we can create simple aliases:
To work with [[https://github.com/akermu/emacs-libvterm][VTerm in Emacs]], we need to create this function:
#+BEGIN_SRC zsh
#+BEGIN_SRC zsh :tangle no
vterm_printf() {
if [ -n "$TMUX" ] \
&& { [ "${TERM%%-*}" = "tmux" ] \
@ -515,7 +528,7 @@ To work with [[https://github.com/akermu/emacs-libvterm][VTerm in Emacs]], we ne
This allows us to execute Emacs commands:
#+BEGIN_SRC zsh
#+BEGIN_SRC zsh :tangle no
vterm_cmd() {
local vterm_elisp
vterm_elisp=""
@ -529,7 +542,7 @@ This allows us to execute Emacs commands:
For instance:
#+BEGIN_SRC zsh
#+BEGIN_SRC zsh :tangle no
if [[ "$INSIDE_EMACS" = 'vterm' ]]
then
alias clear='vterm_printf "51;Evterm-clear-scrollback";tput clear'
@ -540,6 +553,14 @@ For instance:
fi
#+END_SRC
** Eat a Terminal
To work with [[:ha-remoting.org::*Eat][Eat]], we need to load up its integration library:
#+BEGIN_SRC zsh :tangle no
[ -n "$EAT_SHELL_INTEGRATION_DIR" ] && source "$EAT_SHELL_INTEGRATION_DIR/zsh"
#+END_SRC
The problem with the Eat integration is it prepends a =0= that doesn’t seem to signify anything useful.
* Aliases
Assuming we’ve installed [[https://github.com/lsd-rs/lsd][lsd]], let’s make an alias for it: