Skip to content

Instantly share code, notes, and snippets.

@DinoChiesa
Created May 25, 2025 02:09
Show Gist options
  • Save DinoChiesa/533997d4c0c3d8963f35776e8bcc236a to your computer and use it in GitHub Desktop.
Save DinoChiesa/533997d4c0c3d8963f35776e8bcc236a to your computer and use it in GitHub Desktop.
Emacs lisp helper code for setting the path just right on Windows
;; ====================================================================
;; For tools like apheleia and flycheck, other tools that might invoke shell
;; commands (like csslint, csharpier, etc), We need to set the path
;; properly. The following functions help with that. I had some problems
;; getting it just right, so it now verbosely logs everything.
(defun my/reorder-list (list predicate)
"Reorders LIST so that elements satisfying PREDICATE come first.
Returns a new list with elements reordered according to PREDICATE.
The original list is not modified.
"
(let (matches non-matches)
(dolist (item list)
(if (funcall predicate item)
(push item matches)
(push item non-matches)))
(nconc (reverse matches) (reverse non-matches))))
(defun my/--preferred-path-entry (entry)
"returns t if the entry is to be preferred"
(or
(string-match-p (regexp-quote "Git/usr/bin") entry)
(string-match-p (regexp-quote (concat (getenv "HOME") "/bin")) entry)
))
(defun my/maybe-reorder-exec-path-entries ()
"re-orders the exec-path entries to ensure some dirs are
preferred above others."
(setq exec-path (my/reorder-list exec-path #'my/--preferred-path-entry)))
(defun my/maybe-add-to-exec-path (paths)
"Add each item from PATHS to `exec-path' and the PATH environment variable
if the item exists as a directory and is not already present."
(let (exec-path-was-modified
path-was-modified
(env-paths (split-string (getenv "PATH") ":")))
(dolist (path paths)
(when (and path (file-directory-p path))
(let (was-modified
(normalized-path (file-truename path)))
;; I am not sure if I need both `exec-path' and the PATH environment variable.
(when (not (member normalized-path exec-path))
(setq was-modified (cons "exec-path" was-modified))
(add-to-list 'exec-path normalized-path)
(setq exec-path-was-modified t))
(when (not (member normalized-path env-paths))
(setq was-modified (cons "PATH" was-modified))
(add-to-list 'env-paths normalized-path)
(setq path-was-modified t))
(if was-modified
(message (format "add %s to %s" normalized-path was-modified)))
)))
(when path-was-modified
(setenv "PATH" (mapconcat 'identity env-paths ":"))
(message (format "updated PATH %s" (getenv "PATH"))))
(when exec-path-was-modified
(if (eq system-type 'windows-nt)
(my/maybe-reorder-exec-path-entries))
(message (format "updated exec-path %s" (prin1-to-string exec-path))))
))
(provide 'my-path-helper)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment