dotfiles

My personal shell configs and stuff
git clone git://git.alex.balgavy.eu/dotfiles.git
Log | Files | Refs | Submodules | README | LICENSE

config.org (141339B)


      1 * macOS installation info
      2 On macOS, I use Homebrew to install Emacs from daviderestivo/emacs-head/emacs-head@28.
      3 I install with ~--HEAD --with-dbus --with-cocoa --with-xwidgets --with-native-comp~.
      4 
      5 * Why I choose use-package
      6 - provides bind-key by default
      7 - is mostly just macros that wrap the needed stuff from package.el. can check that with ~macroexpand~.
      8 - adds a bunch of performance improvements
      9 * Let me know when we're at a certain version
     10 #+begin_src emacs-lisp
     11   (when (version<= "30" emacs-version)
     12     (message "Check out C-x w d to make windows dedicated."))
     13 #+end_src
     14 * Install from source
     15 Emacs 29 ships with a way to install packages from source, here's a small wrapper around it.
     16 
     17 #+begin_src emacs-lisp
     18   (cl-defun za/package-vc-install (&key (fetcher "github") repo name rev backend load)
     19     "Install a package from a remote if it's not already installed.
     20   This is a thin wrapper around `package-vc-install' in order to
     21   make non-interactive usage more ergonomic.  Takes the following
     22   named arguments:
     23 
     24   - FETCHER the remote where to get the package (e.g., \"gitlab\").
     25     If omitted, this defaults to \"github\".
     26 
     27   - REPO should be the name of the repository (e.g.,
     28   \"slotThe/arXiv-citation\".
     29 
     30   - NAME, REV, and BACKEND are as in `package-vc-install' (which
     31     see).
     32 
     33   - LOAD is optionally a subdirectory that should be added to `load-path'."
     34     (let* ((url (cond ((string-match-p (rx bos "http" (? ?s) "://") repo)
     35                        repo)
     36                       (t (format "https://www.%s.com/%s" fetcher repo))))
     37            (iname (when name (intern name)))
     38            (pac-name (or iname (intern (file-name-base repo))))
     39            (to-load (when load
     40                       (format "%s/%s"
     41                               (package-desc-dir (package-get-descriptor pac-name))
     42                               load))))
     43       (unless (package-installed-p pac-name)
     44         (package-vc-install url iname rev backend))
     45       (when load
     46         (unless (file-directory-p to-load)
     47           (user-error "Not a readable dir: %s" to-load))
     48         (add-to-list 'load-path to-load))
     49       (message "%s" pac-name)))
     50 #+end_src
     51 
     52 You can use this in use-package with an ~:init~ clause.
     53 
     54 * exec-path-from-shell (macOS)
     55 In macOS, the path is not set correctly (i.e. as it is in the terminal) in the GUI app. This fixes it.
     56 Not needed when using emacs-plus, because it has a custom patch for it. It also defines a [[https://github.com/d12frosted/homebrew-emacs-plus?tab=readme-ov-file#system-appearance-change][custom variable]] which hopefully should be enough to detect if we're running emacs-plus.
     57 
     58 #+begin_src emacs-lisp
     59   (when (and (string-equal system-type "darwin")
     60              (not (boundp 'ns-system-appearance-change-functions)))
     61     (use-package exec-path-from-shell
     62       :config
     63       (add-to-list 'exec-path-from-shell-variables "NOTMUCH_CONFIG")
     64       (exec-path-from-shell-initialize)))
     65 #+end_src
     66 
     67 * Emacs file locations
     68 ** Auto-Save files
     69 By default, auto-save files ("#file#") are placed in the same directory as the file itself.
     70 I want to put this all in some unified place:
     71 
     72 #+begin_src emacs-lisp
     73   (let ((saves-directory "~/.local/share/emacs/saves/"))
     74     (unless (file-directory-p saves-directory)
     75       (make-directory saves-directory))
     76     (setq auto-save-file-name-transforms
     77           `((".*" ,saves-directory t))))
     78 #+end_src
     79 
     80 ** Backup files
     81 By default, backup files (those with a tilde) are saved in the same directory as the currently edited file.
     82 This setting puts them in ~/.local/share/emacs/backups.
     83 
     84 #+begin_src emacs-lisp
     85   (let ((backups-directory "~/.local/share/emacs/backups"))
     86     (unless (file-directory-p backups-directory)
     87       (make-directory backups-directory))
     88     (setq backup-directory-alist `(("." . ,backups-directory)))
     89     (setq backup-by-copying t))
     90 #+end_src
     91 
     92 ** Custom settings file
     93 Both commands are necessary.
     94 First one tells Emacs where to save customizations.
     95 The second one actually loads them.
     96 
     97 #+begin_src emacs-lisp
     98   (setq custom-file (expand-file-name (concat user-emacs-directory "custom.el")))
     99   (load custom-file)
    100 #+end_src
    101 ** Delete by trash
    102 #+begin_src emacs-lisp
    103   (setq delete-by-moving-to-trash t)
    104   (unless (fboundp 'system-move-file-to-trash)
    105     (setq trash-directory "~/.Trash"))
    106 #+end_src
    107 * Daemon
    108 I want to have a way to kill the Emacs daemon.
    109 So, define a function that kills the frame, and with a prefix kills emacs.
    110 
    111 #+begin_src emacs-lisp
    112   (defun za/emacsclient-c-x-c-c (&optional arg)
    113     "If running in emacsclient, make C-x C-c exit frame, and C-u C-x C-c exit Emacs."
    114     (interactive "P") ; prefix arg in raw form
    115     (if arg
    116         (save-buffers-kill-emacs)
    117       (save-buffers-kill-terminal)))
    118 #+end_src
    119 
    120 Then, if I'm in an emacsclient, I want to bind C-x C-c to that function (if not, I just want the default keybinding):
    121 
    122 #+begin_src emacs-lisp
    123   ;; If not running in emacsclient, use the default bindings
    124   (if (daemonp)
    125       (bind-key "C-x C-c" #'za/emacsclient-c-x-c-c))
    126 #+end_src
    127 
    128 Furthermore, I want to set the theme correctly whenever I connect with 'emacsclient':
    129 
    130 #+begin_src emacs-lisp
    131   (if (daemonp)
    132       (add-hook 'after-make-frame-functions #'za/auto-select-theme))
    133 #+end_src
    134 * Sound support
    135 On macOS, you can use afplay:
    136 
    137 #+begin_src emacs-lisp
    138   (defun za/play-sound-file-macos (file &optional volume device)
    139     "Play sound using `afplay` on macOS"
    140     (unless (file-readable-p file)
    141       (user-error "File %s not readable." file))
    142 
    143     ;; the `apply` is required here because I need to build a list of arguments
    144     (apply 'start-process `("afplay" nil
    145                             "afplay"
    146                             ,@(if volume (list "-v" (int-to-string volume)))
    147                             ,file)))
    148 #+end_src
    149 
    150 Then redefine the play-sound-file function where needed:
    151 
    152 #+begin_src emacs-lisp
    153   (cond ((and (not (fboundp 'play-sound-internal))
    154               (eq system-type 'darwin))
    155          (advice-add 'play-sound-file :override #'za/play-sound-file-macos)))
    156 #+end_src
    157 * DISABLED Fix non-dbus macOS notification
    158 macOS version might not be compiled with dbus support; in that case you can use e.g. terminal-notifier.
    159 If you use the ~sender~ option, notifications don't show
    160 unless the app is in the background. [[https://github.com/julienXX/terminal-notifier/issues/68][See this Github issue.]]
    161 
    162 #+begin_src emacs-lisp :tangle no
    163   ;; on mac without dbus:
    164   (org-show-notification-handler
    165    (lambda (str) (start-process "terminal-notifier" nil (executable-find "terminal-notifier")
    166                                 "-title" "Timer done"
    167                                 "-message" str
    168                                 "-group" "org.gnu.Emacs"
    169                                 "-ignoreDnD"
    170                                 "-activate" "org.gnu.Emacs")))
    171 #+end_src
    172 * Custom notification functions
    173 #+begin_src emacs-lisp
    174   (defun za/notify (title message)
    175     "Show notification with TITLE and MESSAGE."
    176     (ignore-errors (require 'notifications))
    177     (cond ((fboundp 'ns-do-applescript)
    178            (ns-do-applescript
    179             (format "display notification \"%s\" with title \"%s\""
    180                     (replace-regexp-in-string "\"" "#" message)
    181                     (replace-regexp-in-string "\"" "#" title))))
    182           ((string= system-type "gnu/linux")
    183            (require 'notifications)
    184            (notifications-notify :title title :body message))
    185           (t (error "No notification handler defined!"))))
    186 
    187   (defun za/send-notification-interactivity-required (&rest _)
    188     "Notify that a function needs action."
    189     (za/notify "Interactivity required" "A function requires interactivity."))
    190 
    191   (defun za/notify-on-interactivity (func &rest r)
    192     "Send a notification whenever FUNC requires interactivity.
    193   Used as :around advice, calling FUNC with arguments R."
    194     (advice-add #'y-or-n-p :before #'za/send-notification-interactivity-required)
    195     (advice-add #'yes-or-no-p :before #'za/send-notification-interactivity-required)
    196     (advice-add #'user-error :before #'za/send-notification-interactivity-required)
    197     (with-demoted-errors "Error in %s" (apply func r))
    198     (advice-remove #'y-or-n-p #'za/send-notification-interactivity-required)
    199     (advice-remove #'yes-or-no-p #'za/send-notification-interactivity-required)
    200     (advice-remove #'user-error #'za/send-notification-interactivity-required))
    201 #+end_src
    202 
    203 * Editing
    204 ** Everything is UTF-8
    205 #+begin_src emacs-lisp
    206   (set-language-environment 'utf-8)
    207   (setq locale-coding-system 'utf-8)
    208   (setq buffer-file-coding-system 'utf-8-unix)
    209   (set-terminal-coding-system 'utf-8)
    210   (set-keyboard-coding-system 'utf-8)
    211   (set-selection-coding-system 'utf-8)
    212   (prefer-coding-system 'utf-8)
    213 #+end_src
    214 ** Overwrite selection on typing
    215 Normally, when I select something and start typing, Emacs clears the selection, i.e. it deselects and inserts text after the cursor.
    216 I want to replace the selection.
    217 
    218 #+begin_src emacs-lisp
    219   (delete-selection-mode t)
    220 #+end_src
    221 
    222 ** Strip trailing whitespace
    223 You can show trailing whitespace by setting show-trailing-whitespace to 't'.
    224 But I want to automatically strip trailing whitespace.
    225 Luckily there's already a function for that, I just need to call it in a hook:
    226 
    227 #+begin_src emacs-lisp
    228   (add-hook 'before-save-hook #'delete-trailing-whitespace)
    229 #+end_src
    230 
    231 ** Formatting & indentation
    232 
    233 Show a tab as 8 spaces:
    234 
    235 #+begin_src emacs-lisp
    236   (setq-default tab-width 8)
    237 #+end_src
    238 
    239 Never insert tabs with indentation by default:
    240 
    241 #+begin_src emacs-lisp
    242   (setq-default indent-tabs-mode nil)
    243 #+end_src
    244 
    245 Allow switching between the two easily:
    246 
    247 #+begin_src emacs-lisp
    248   (defun indent-tabs ()
    249     (interactive)
    250     (setq indent-tabs-mode t))
    251   (defun indent-spaces ()
    252     (interactive)
    253     (setq indent-tabs-mode nil))
    254 #+end_src
    255 
    256 Indentation for various modes:
    257 
    258 #+begin_src emacs-lisp
    259   (setq-default sh-basic-offset 2
    260                 c-basic-offset 4)
    261 #+end_src
    262 
    263 ** Wrapping
    264 A function to toggle wrapping:
    265 
    266 #+begin_src emacs-lisp
    267   (defvar-local za/wrapping nil "Wrapping changes per buffer.")
    268 
    269   (defun za/toggle-wrap (&optional enable)
    270     "Toggle line wrapping settings. With ENABLE a positive number, enable wrapping. If ENABLE is negative or zero, disable wrapping."
    271     (interactive "P") ; prefix arg in raw form
    272 
    273     ;; If an argument is provided, prefix or otherwise
    274     (if enable
    275         (let ((enable (cond ((numberp enable)
    276                              enable)
    277                             ((booleanp enable)
    278                              (if enable 1 0))
    279                             ((or (listp enable) (string= "-" enable))
    280                              (prefix-numeric-value enable)))))
    281           ;; If zero or negative, we want to disable wrapping, so pretend it's currently enabled.
    282           ;; And vice versa.
    283           (cond ((<= enable 0) (setq za/wrapping t))
    284                 ((> enable 0) (setq za/wrapping nil)))))
    285 
    286 
    287     (let ((disable-wrapping (lambda ()
    288                               (visual-line-mode -1)
    289                               (toggle-truncate-lines t)))
    290           (enable-wrapping (lambda ()
    291                              (toggle-truncate-lines -1)
    292                              (visual-line-mode))))
    293 
    294       ;; If za/wrapping is not locally set, infer its values from the enabled modes
    295       (unless (boundp 'za/wrapping)
    296         (setq za/wrapping (and visual-line-mode
    297                                (not truncate-lines))))
    298 
    299       ;; Toggle wrapping based on current value
    300       (cond (za/wrapping
    301              (funcall disable-wrapping)
    302              (setq za/wrapping nil)
    303              (message "Wrapping disabled."))
    304             (t
    305              (funcall enable-wrapping)
    306              (setq za/wrapping t)
    307              (message "Wrapping enabled.")))))
    308 #+end_src
    309 
    310 And a keybinding to toggle wrapping:
    311 
    312 #+begin_src emacs-lisp
    313   (bind-key "C-c q w" #'za/toggle-wrap)
    314 #+end_src
    315 
    316 And fringe indicators:
    317 
    318 #+begin_src emacs-lisp
    319   (setopt visual-line-fringe-indicators '(left-curly-arrow right-curly-arrow))
    320 #+end_src
    321 ** Pager toggle
    322 M-x view-mode enables pager behavior.
    323 I want read-only files to automatically use pager mode:
    324 
    325 #+begin_src emacs-lisp
    326   (setq view-read-only t)
    327 #+end_src
    328 ** Prefer newer file loading
    329 #+begin_src emacs-lisp
    330   (setq load-prefer-newer t)
    331 #+end_src
    332 
    333 ** Automatically find tags file
    334 When opening a file in a git repo, try to discover the etags file:
    335 
    336 #+begin_src emacs-lisp
    337   (defun current-tags-file ()
    338     "Get current tags file"
    339     (let* ((tagspath ".git/etags")
    340            (git-root (locate-dominating-file (buffer-file-name) tagspath)))
    341       (if git-root
    342           (expand-file-name tagspath git-root))))
    343 
    344   (setq default-tags-table-function #'current-tags-file)
    345 #+end_src
    346 
    347 There's probably a better way to write this. I need to ask Reddit for feedback at some point.
    348 
    349 ** End sentences with one space
    350 Emacs uses the rather old-fashioned convention of treating a period followed by double spaces as end of sentence. However, it is more common these days to end sentences with a period followed by a single space.
    351 
    352 Let a period followed by a single space be treated as end of sentence:
    353 
    354 #+begin_src emacs-lisp
    355   (setopt sentence-end-double-space nil)
    356 #+end_src
    357 * Keybindings
    358 ** Expansion/completion
    359 Use hippie expand instead of dabbrev-expand:
    360 
    361 #+begin_src emacs-lisp
    362   (bind-key "M-/" #'hippie-expand)
    363 #+end_src
    364 
    365 ** Zap up to char
    366 It's more useful for me to be able to delete up to a character instead of to and including a character:
    367 
    368 #+begin_src emacs-lisp
    369   (defun za/zap-up-to-char-icase ()
    370     "Ignore case for zap-up-to-char"
    371     (interactive)
    372     (let ((case-fold-search nil))
    373       (call-interactively #'zap-up-to-char)))
    374   (bind-key "M-z" #'za/zap-up-to-char-icase)
    375 #+end_src
    376 
    377 ** Forward-word and forward-to-word
    378 Change M-f to stop at the start of the word:
    379 
    380 #+begin_src emacs-lisp
    381   (bind-key "M-f" #'forward-to-word)
    382 #+end_src
    383 
    384 Bind ESC M-f to the old functionality of M-f (stop at end of word)
    385 
    386 #+begin_src emacs-lisp
    387   (bind-key "ESC M-f" #'forward-word)
    388 #+end_src
    389 
    390 ** Rectangle insert string
    391 #+begin_src emacs-lisp
    392   (bind-key "C-x r I" #'string-insert-rectangle)
    393   (bind-key "C-x r R" #'replace-rectangle)
    394 #+end_src
    395 
    396 ** Toggle auto-revert-mode
    397 Sometimes I want to toggle auto reverting (or autoread) of buffer:
    398 
    399 #+begin_src emacs-lisp
    400   (bind-key "C-c q a" #'auto-revert-mode)
    401 #+end_src
    402 ** Fast access to view-mode (pager)
    403 I want to bind view-mode to a key for easy access:
    404 
    405 #+begin_src emacs-lisp
    406   (bind-key "C-c q r" 'view-mode)
    407 #+end_src
    408 
    409 ** Kill this buffer
    410 I like to be able to kill a buffer instantly:
    411 
    412 #+begin_src emacs-lisp
    413   (bind-key "s-<backspace>" 'kill-current-buffer)
    414 #+end_src
    415 
    416 ** Delete this file (and kill the buffer)
    417 #+begin_src emacs-lisp
    418   (defun za/delete-this-file ()
    419     "Kill the current buffer and delete its associated file."
    420     (interactive)
    421     (let ((fname (buffer-file-name))
    422           (buf (current-buffer)))
    423       (unless (and fname (file-exists-p fname))
    424         (user-error "Buffer has no associated file."))
    425 
    426       (unless (yes-or-no-p (format "Really delete %s and its buffer?" fname))
    427         (user-error "User cancelled."))
    428 
    429       (delete-file fname 'trash-if-enabled)
    430       (kill-buffer buf)
    431       (message "Deleted %s and killed its buffer." fname)))
    432 
    433   (bind-key "C-c s-<backspace>" #'za/delete-this-file)
    434 #+end_src
    435 
    436 ** Toggle fullscreen
    437 I'll use the keybinding that's standard on macOS:
    438 
    439 #+begin_src emacs-lisp
    440   (bind-key "C-s-f" #'toggle-frame-fullscreen)
    441 #+end_src
    442 
    443 ** Sexp manipulation
    444 When I write lisp, sometimes I want to switch two sexps (e.g. ~(one) (two)~ → ~(two) (one)~), so a key binding is nice for that:
    445 
    446 #+begin_src emacs-lisp
    447   (bind-key "C-S-t" #'transpose-sexps)
    448 #+end_src
    449 
    450 Also, to raise a sexp (e.g. ~(one (two))~ → ~(two)~):
    451 
    452 #+begin_src emacs-lisp
    453   (bind-key "C-S-u" #'raise-sexp)
    454 #+end_src
    455 
    456 ** Dedicated windows
    457 Sometimes I want to avoid Emacs overriding a window's contents.
    458 So I create a keybinding to toggle dedicated on a window:
    459 
    460 #+begin_src emacs-lisp
    461   (defun za/toggle-window-dedicated-p ()
    462     "Toggle set-window-dedicated-p on current window"
    463     (interactive)
    464     (cond ((window-dedicated-p (selected-window))
    465            (set-window-dedicated-p (selected-window) nil)
    466            (message "Window no longer dedicated"))
    467           (t
    468            (set-window-dedicated-p (selected-window) t)
    469            (message "Window marked as dedicated"))))
    470 
    471   (bind-key "C-x 9" #'za/toggle-window-dedicated-p)
    472 
    473 #+end_src
    474 
    475 ** Rotate windows horizontal ↔ vertical
    476 #+begin_src emacs-lisp
    477   (defun za/rotate-windows ()
    478     (interactive)
    479     (if (= (count-windows) 2)
    480         (let* ((this-win-buffer (window-buffer))
    481                (next-win-buffer (window-buffer (next-window)))
    482                (this-win-edges (window-edges (selected-window)))
    483                (next-win-edges (window-edges (next-window)))
    484                (this-win-2nd (not (and (<= (car this-win-edges)
    485                                            (car next-win-edges))
    486                                        (<= (cadr this-win-edges)
    487                                            (cadr next-win-edges)))))
    488                (splitter
    489                 (if (= (car this-win-edges)
    490                        (car (window-edges (next-window))))
    491                     'split-window-horizontally
    492                   'split-window-vertically)))
    493           (delete-other-windows)
    494           (let ((first-win (selected-window)))
    495             (funcall splitter)
    496             (if this-win-2nd (other-window 1))
    497             (set-window-buffer (selected-window) this-win-buffer)
    498             (set-window-buffer (next-window) next-win-buffer)
    499             (select-window first-win)
    500             (if this-win-2nd (other-window 1))))))
    501 #+end_src
    502 
    503 #+begin_src emacs-lisp
    504   (bind-key "C-x 7" #'za/rotate-windows)
    505 #+end_src
    506 
    507 ** Open line like in Vim
    508 I prefer to open-line the way o/O works in Vim:
    509 
    510 #+begin_src emacs-lisp
    511   ;; Autoindent open-*-lines
    512   (defvar za/open-line-newline-and-indent t
    513     "Modify the behavior of the open-*-line functions to cause them to autoindent.")
    514 
    515   (defun za/open-line (prefix)
    516     "Open line like `o`/`O` in Vim. Negative prefix for line above, positive for below."
    517     (interactive "p")
    518     (cond ((< prefix 0)
    519            (beginning-of-line)
    520            (open-line (abs prefix)))
    521           (t
    522            (end-of-line)
    523            (open-line prefix)
    524            (forward-line 1)))
    525     (when za/open-line-newline-and-indent
    526       (indent-according-to-mode)))
    527 
    528   (defun za/open-line-keep-point (prefix)
    529     "Open line like `o`/`O` in Vim but don't move point. Negative prefix for line above, positive for below."
    530     (interactive "p")
    531     (save-mark-and-excursion (za/open-line prefix)))
    532 #+end_src
    533 
    534 And keybindings:
    535 
    536 #+begin_src emacs-lisp
    537   (bind-key "C-o" #'za/open-line)
    538   (bind-key "C-M-o" #'za/open-line-keep-point)
    539 #+end_src
    540 
    541 ** Unfill region/paragraph
    542 Taken from here: https://www.emacswiki.org/emacs/UnfillParagraph
    543 
    544 #+begin_src emacs-lisp
    545   (defun za/unfill-paragraph (&optional region)
    546     "Takes a multi-line paragraph and makes it into a single line of text."
    547     (interactive (progn (barf-if-buffer-read-only) '(t)))
    548     (let ((fill-column (point-max))
    549           ;; This would override `fill-column' if it's an integer.
    550           (emacs-lisp-docstring-fill-column t))
    551       (fill-paragraph nil region)))
    552 
    553   (bind-key "M-Q" #'za/unfill-paragraph)
    554 #+end_src
    555 ** Easily edit my config
    556 Bind a keyboard shortcut to open my config.
    557 The "(interactive)" means that it can be called from a keybinding or from M-x.
    558 
    559 #+begin_src emacs-lisp
    560   (defun za/edit-config-org ()
    561     "Edit my config.org file"
    562     (interactive)
    563     (find-file (expand-file-name "config.org" user-emacs-directory)))
    564 #+end_src
    565 
    566 #+begin_src emacs-lisp
    567   (bind-key "C-c E" 'za/edit-config-org)
    568 #+end_src
    569 ** Visible mode
    570 #+begin_src emacs-lisp
    571   (bind-key (kbd "C-c q v") #'visible-mode)
    572 #+end_src
    573 ** Clone buffer indirectly by default
    574 #+begin_src emacs-lisp
    575   (bind-key (kbd "C-x x n") #'clone-indirect-buffer)
    576 #+end_src
    577 * Custom functions
    578 ** Make region readonly or writable
    579 #+begin_src emacs-lisp
    580   (defun za/set-region-read-only (begin end)
    581     "Sets the read-only text property on the marked region.
    582   Use `set-region-writeable' to remove this property."
    583     ;; See https://stackoverflow.com/questions/7410125
    584     (interactive "r")
    585     (with-silent-modifications
    586       (put-text-property begin end 'read-only t)))
    587 
    588   (defun za/set-region-writeable (begin end)
    589     "Removes the read-only text property from the marked region.
    590   Use `set-region-read-only' to set this property."
    591     ;; See https://stackoverflow.com/questions/7410125
    592     (interactive "r")
    593     (with-silent-modifications
    594       (remove-text-properties begin end '(read-only t))))
    595 #+end_src
    596 ** Insert macro as Lisp
    597 From here: https://www.masteringemacs.org/article/keyboard-macros-are-misunderstood
    598 
    599 #+begin_src emacs-lisp
    600   (use-package kmacro
    601     :ensure nil ; included with Emacs
    602     :bind (:map kmacro-keymap
    603                 ("I" . kmacro-insert-macro))
    604     :config
    605     (defalias 'kmacro-insert-macro 'insert-kbd-macro)
    606 
    607     ;; Add advice to ignore errors on `kmacro-keyboard-macro-p`, it was
    608     ;; messing up because of some entry in `obarray`
    609     (advice-add #'kmacro-keyboard-macro-p :around (lambda (fun sym) "Ignore errors." (ignore-errors (funcall fun sym)))))
    610 #+end_src
    611 ** Show local help at point when idling
    612 #+begin_src emacs-lisp
    613   (defun za/echo-area-tooltips ()
    614     "Show tooltips in the echo area automatically for current buffer."
    615     (setq-local help-at-pt-display-when-idle t
    616                 help-at-pt-timer-delay 0)
    617     (help-at-pt-cancel-timer)
    618     (help-at-pt-set-timer))
    619 #+end_src
    620 
    621 ** Info manual functions
    622 For some reason, these things don't show up in the index:
    623 
    624 #+begin_src emacs-lisp
    625   (defun elisp-info (&optional node)
    626     "Read documentation for Elisp in the info system.
    627   With optional NODE, go directly to that node."
    628     (interactive)
    629     (info (format "(elisp)%s" (or node ""))))
    630 #+end_src
    631 
    632 Though I can also just use ~info-display-manual~.
    633 
    634 ** Radio
    635 Just a wrapper function to my radio script:
    636 
    637 #+begin_src emacs-lisp
    638   (defun radio ()
    639     "Play an internet radio"
    640     (interactive)
    641     (ansi-term "radio" "*radio*"))
    642 #+end_src
    643 
    644 ** no-op
    645 #+begin_src emacs-lisp
    646   (defun za/no-op (&rest args))
    647 #+end_src
    648 
    649 ** Syncthing
    650 Some functions to start/stop syncthing.
    651 #+begin_src emacs-lisp
    652   (defconst za/st-buffer-name "*syncthing*" "Buffer name for the syncthing process.")
    653   (defun za/st ()
    654     "Start syncthing"
    655     (interactive)
    656     (if (get-buffer-process za/st-buffer-name)
    657         (user-error "Syncthing is already running."))
    658     (async-shell-command "syncthing serve --no-browser" za/st-buffer-name))
    659 
    660   (defun za/st-kill ()
    661     "Stop syncthing"
    662     (interactive)
    663     (unless (get-buffer-process za/st-buffer-name)
    664       (user-error "Syncthing is not running."))
    665     (async-shell-command "syncthing cli operations shutdown"))
    666 #+end_src
    667 ** Replace typographic quotes
    668 #+begin_src emacs-lisp
    669   (defun za/replace-typographic-quotes ()
    670     "Replace typographic quotes with plain quotes"
    671     (interactive)
    672     (save-mark-and-excursion
    673       (goto-char (point-min))
    674       (while (re-search-forward (rx (any ?“ ?”)) nil 'noerror)
    675         (replace-match "\""))
    676       (goto-char (point-min))
    677       (while (re-search-forward (rx (any "‘" "’")) nil 'noerror)
    678         (replace-match "'"))))
    679 #+end_src
    680 ** Distraction-free on current buffer
    681 #+begin_src emacs-lisp
    682   (defun za/buffer-focus-no-distractions ()
    683     "Focus on this buffer"
    684     (interactive)
    685     (cond ((or (not (boundp 'za/no-distractions))
    686                (not za/no-distractions))
    687            (olivetti-mode 1)
    688            (line-number-mode 0)
    689            (display-line-numbers-mode 0)
    690            (window-configuration-to-register ?w)
    691            (delete-other-windows)
    692            (setq-local za/tmp/mode-line-format mode-line-format)
    693            (setq-local mode-line-format nil)
    694            (setq-local za/tmp/internal-border-width (frame-parameter nil 'internal-border-width))
    695            (set-frame-parameter nil 'internal-border-width 20)
    696            (setq-local za/no-distractions t)
    697            (message "Window configuration stored in register W"))
    698           (za/no-distractions
    699            (set-frame-parameter nil 'internal-border-width za/tmp/internal-border-width)
    700            (line-number-mode 0)
    701            (display-line-numbers-mode 1)
    702            (setq-local mode-line-format za/tmp/mode-line-format)
    703            (jump-to-register ?w)
    704            (olivetti-mode 0)
    705            (setq-local za/no-distractions nil))))
    706 #+end_src
    707 * Interface
    708 ** Theme
    709 Icons required for some parts of the doom theme:
    710 
    711 #+begin_src emacs-lisp
    712   (use-package all-the-icons)
    713 #+end_src
    714 
    715 Load Doom Emacs themes:
    716 
    717 #+begin_src emacs-lisp
    718   (use-package doom-themes
    719     :config
    720     ;; Global settings (defaults)
    721     (setq doom-themes-enable-bold t    ; if nil, bold is universally disabled
    722           doom-themes-enable-italic t) ; if nil, italics is universally disabled
    723 
    724     ;; Enable flashing mode-line on errors
    725     (doom-themes-visual-bell-config)
    726 
    727     ;; Corrects (and improves) org-mode's native fontification.
    728     (doom-themes-org-config))
    729 #+end_src
    730 
    731 Define the themes I want:
    732 
    733 #+begin_src emacs-lisp
    734   (defconst za/dark-theme-name 'doom-one "A symbol representing the name of the dark theme I use.")
    735   (defconst za/light-theme-name 'jokull "A symbol representing the name of the light theme I use.")
    736   ;; I used to use doom-acario-light before writing my own theme
    737 
    738   (defun za/dark-theme ()
    739     "Switch to dark theme"
    740     (interactive)
    741     (mapc #'disable-theme custom-enabled-themes)
    742     (load-theme za/dark-theme-name t)
    743     (add-hook 'pdf-view-mode-hook #'pdf-view-midnight-minor-mode))
    744 
    745   (defun za/light-theme ()
    746     "Switch to light theme"
    747     (interactive)
    748     (mapc #'disable-theme custom-enabled-themes)
    749     (load-theme za/light-theme-name t)
    750     (remove-hook 'pdf-view-mode-hook #'pdf-view-midnight-minor-mode))
    751 #+end_src
    752 
    753 Change theme depending on the current system theme.
    754 The way I check for dark mode is defined in 'dark-mode-p'; currently I use the presence of the ~/.config/dark-theme file to indicate when dark theme is set.
    755 I quote the call to ~file-exists-p~ because I want to evaluate it on-demand, not immediately.
    756 A function ending in '-p' is a predicate, i.e. returns true or false.
    757 If calling a function that's in a variable, you have to use 'funcall'.
    758 To evaluate a quoted form, use 'eval'.
    759 
    760 #+begin_src emacs-lisp
    761   (defun za/auto-select-theme (&rest _)
    762     "Automatically select dark/light theme based on presence of ~/.config/dark-theme"
    763     (let ((dark-mode-p '(file-exists-p "~/.config/dark-theme")))
    764       (if (eval dark-mode-p)
    765           (za/dark-theme)
    766         (za/light-theme))))
    767 
    768   (za/auto-select-theme)
    769 #+end_src
    770 
    771 ** Font
    772 I want Menlo, size 12:
    773 
    774 #+begin_src emacs-lisp
    775   (add-to-list 'default-frame-alist '(font . "Menlo-13"))
    776   (custom-set-faces
    777    ; height = pt * 10
    778    '(fixed-pitch ((t (:family "Menlo" :height 130))))
    779    '(variable-pitch ((t (:family "ETBembo" :height 140))))
    780    '(org-block ((t (:inherit fixed-pitch))))
    781    '(org-table ((t (:foreground "#0087af" :inherit fixed-pitch))))
    782    '(org-indent ((t (:inherit (org-hide fixed-pitch))))))
    783 
    784   (set-face-font 'fixed-pitch "Menlo-13")
    785   (set-face-font 'variable-pitch "ETBembo-14")
    786 #+end_src
    787 
    788 I like nicer list bullets:
    789 
    790 #+begin_src emacs-lisp
    791   (font-lock-add-keywords
    792    'org-mode
    793    `((,(rx bol (* blank) (group ?-) " ")  ; list regexp
    794       1                                   ; first match
    795       '(face nil display "•"))))          ; replace with bullet point, keep same face
    796 #+end_src
    797 ** Cursor
    798 The default box cursor isn't really accurate, because the cursor is actually between letters, not on a letter.
    799 So, I want a bar instead of a box:
    800 
    801 #+begin_src emacs-lisp
    802   (setq-default cursor-type '(bar . 4)
    803                 cursor-in-non-selected-windows 'hollow)
    804 #+end_src
    805 
    806 (I use ~setq-default~ here because cursor-type is automatically buffer-local when it's set)
    807 
    808 And enable cursorline:
    809 
    810 #+begin_src emacs-lisp
    811   (global-hl-line-mode)
    812 #+end_src
    813 
    814 And visualize tab characters by stretching the cursor:
    815 
    816 #+begin_src emacs-lisp
    817   (setq-default x-stretch-cursor t)
    818 #+end_src
    819 ** Matching parentheses
    820 Don't add a delay to show matching parenthesis.
    821 Must come before show-paren-mode enable.
    822 
    823 #+begin_src emacs-lisp
    824   (setq show-paren-delay 0)
    825 #+end_src
    826 
    827 Show matching parentheses:
    828 
    829 #+begin_src emacs-lisp
    830   (show-paren-mode t)
    831 #+end_src
    832 ** Line numbers
    833 Relative line numbers:
    834 
    835 #+begin_src emacs-lisp
    836   (setq display-line-numbers-type 'relative)
    837   (global-display-line-numbers-mode)
    838 #+end_src
    839 
    840 Function to hide them:
    841 
    842 #+begin_src emacs-lisp
    843   (defun za/hide-line-numbers ()
    844     "Hide line numbers"
    845     (display-line-numbers-mode 0))
    846 #+end_src
    847 Don't display them in specific modes.  For each of the modes in
    848 'mode-hooks', add a function to hide line numbers when the mode
    849 activates (which triggers the 'mode'-hook).
    850 
    851 #+begin_src emacs-lisp
    852   (let ((mode-hooks '(doc-view-mode-hook vterm-mode-hook mpc-status-mode-hook mpc-tagbrowser-mode-hook)))
    853     (mapc
    854      (lambda (mode-name)
    855        (add-hook mode-name #'za/hide-line-numbers))
    856      mode-hooks))
    857 #+end_src
    858 ** Modeline
    859 I want to show the time and date in the modeline:
    860 
    861 #+begin_src emacs-lisp
    862   (setq display-time-day-and-date t           ; also the date
    863         display-time-default-load-average nil ; don't show load average
    864         display-time-format "%I:%M%p %e %b (%a)")   ; "HR:MIN(AM/PM) day-of-month Month (Day)"
    865   (display-time-mode 1)                  ; enable time mode
    866 #+end_src
    867 
    868 And to set the modeline format:
    869 
    870 #+begin_src emacs-lisp
    871   (setq-default mode-line-format '("%e" mode-line-front-space mode-line-mule-info mode-line-client mode-line-modified mode-line-remote mode-line-frame-identification mode-line-buffer-identification "   " mode-line-position
    872                                    (vc-mode vc-mode)
    873                                    "  " mode-line-modes mode-line-misc-info mode-line-end-spaces))
    874 #+end_src
    875 
    876 I want to hide certain modes from the modeline.
    877 For that, ~delight~ is a useful package; unlike ~diminish~, it can also change the display of /major/ modes (~diminish~ only does minor modes).
    878 
    879 #+begin_src emacs-lisp
    880     (use-package delight
    881       :config
    882       (delight 'visual-line-mode " ↩" 'simple)
    883       (delight 'auto-revert-mode " AR" 'autorevert)
    884       (delight 'abbrev-mode " Abv" 'abbrev))
    885 #+end_src
    886 ** Transparent title bar
    887 #+begin_src emacs-lisp
    888   (add-to-list 'default-frame-alist '(ns-transparent-titlebar . t))
    889 #+end_src
    890 ** Frame title
    891 #+begin_src emacs-lisp
    892   (setopt frame-title-format "%F--%b-[%f]--%Z")
    893 #+end_src
    894 
    895 ** Tab bar
    896 Only show tab bar if there's more than 1 tab:
    897 
    898 #+begin_src emacs-lisp
    899   (setq tab-bar-show 1)
    900 #+end_src
    901 ** Buffer displaying
    902 
    903 So, this is a bit hard to grok. But basically the alist contains a
    904 regular expression to match a buffer name, then a list of functions to
    905 use in order for displaying the list, and then options for those functions (each of which is an alist).
    906 
    907 #+begin_src emacs-lisp
    908   (setq
    909    ;; Maximum number of side-windows to create on (left top right bottom)
    910    window-sides-slots '(0   ;; left
    911                         1   ;; top
    912                         3   ;; right
    913                         1 ) ;; bottom
    914 
    915    display-buffer-alist `(
    916                           ;; Right side
    917                           (,(rx (or "*Help*" (seq "*helpful " (* anything) "*")))
    918                            (display-buffer-reuse-window display-buffer-in-side-window)
    919                            (side . right)
    920                            (slot . -1)
    921                            (inhibit-same-window . t))
    922                           (,(rx "*Async Shell " (* anything) "*")
    923                            (display-buffer-reuse-window display-buffer-in-side-window)
    924                            (side . right)
    925                            (slot . 0)
    926                            (inhibit-same-window . t))
    927                           (,(rx "magit-process: " (* anything))
    928                            (display-buffer-reuse-window display-buffer-in-side-window)
    929                            (side . right)
    930                            (slot . 0)
    931                            (inhibit-same-window . t))
    932 
    933                           ;; Top side
    934                           (,(rx "*Info*")
    935                            (display-buffer-reuse-window display-buffer-in-side-window)
    936                            (side . top)
    937                            (slot . 0))
    938                           (,(rx "*Man " (* anything) "*")
    939                            (display-buffer-reuse-window display-buffer-in-side-window)
    940                            (side . top)
    941                            (slot . 0))
    942 
    943                           ;; Bottom
    944                           (,(rx "*Flycheck errors*")
    945                            (display-buffer-reuse-window display-buffer-in-side-window)
    946                            (side . bottom)
    947                            (slot . 0))))
    948 #+end_src
    949 
    950 And a way to toggle those side windows:
    951 
    952 #+begin_src emacs-lisp
    953   (bind-key "C-c W" #'window-toggle-side-windows)
    954 #+end_src
    955 
    956 ** Eldoc
    957 When editing Elisp and other supported major-modes, Eldoc will display useful information about the construct at point in the echo area.
    958 
    959 #+begin_src emacs-lisp
    960   (use-package eldoc
    961     :ensure nil ; installed with Emacs
    962     :delight
    963     :config
    964     (global-eldoc-mode 1))
    965 #+end_src
    966 
    967 ** Pulse line
    968 When you switch windows, Emacs can flash the cursor briefly to guide your eyes; I like that.
    969 Set some options for pulsing:
    970 
    971 #+begin_src emacs-lisp
    972   (setq pulse-iterations 10)
    973   (setq pulse-delay 0.05)
    974 #+end_src
    975 
    976 Define the pulse function:
    977 
    978 #+begin_src emacs-lisp
    979   (defun pulse-line (&rest _)
    980     "Pulse the current line."
    981     (pulse-momentary-highlight-one-line (point)))
    982 #+end_src
    983 
    984 Run it in certain cases: scrolling up/down, recentering, switching windows.
    985 'dolist' binds 'command' to each value in the list in turn, and runs the body.
    986 'advice-add' makes the pulse-line function run after 'command'.
    987 
    988 #+begin_src emacs-lisp
    989   (dolist (command '(scroll-up-command scroll-down-command recenter-top-bottom other-window))
    990     (advice-add command :after #'pulse-line))
    991 #+end_src
    992 
    993 And set the pulse color:
    994 
    995 #+begin_src emacs-lisp
    996   (custom-set-faces '(pulse-highlight-start-face ((t (:background "CadetBlue2")))))
    997 #+end_src
    998 
    999 ** Enable all commands
   1000 By default, Emacs disables some commands.
   1001 I want to have these enabled so I don't get a prompt whenever I try to use a disabled command.
   1002 
   1003 #+begin_src emacs-lisp
   1004   (setq disabled-command-function nil)
   1005 #+end_src
   1006 ** More extensive apropos
   1007 #+begin_src emacs-lisp
   1008   (setq apropos-do-all t)
   1009 #+end_src
   1010 ** Enable recursive minibuffers
   1011 #+begin_src emacs-lisp
   1012   (setq enable-recursive-minibuffers t
   1013         minibuffer-depth-indicate-mode t)
   1014 #+end_src
   1015 ** View webp and other formats
   1016 Emacs handles common image formats internally, but for stuff like webp, you need an external converter:
   1017 
   1018 #+begin_src emacs-lisp
   1019   (setq image-use-external-converter t)
   1020 #+end_src
   1021 
   1022 You also need imagemagick installed.
   1023 
   1024 ** Repeat mode: easy repeating of commands
   1025 #+begin_src emacs-lisp
   1026   (repeat-mode 1)
   1027 #+end_src
   1028 
   1029 ** Messages
   1030 Hide some messages I don't need.
   1031 
   1032 #+begin_src emacs-lisp
   1033   (recentf-mode)
   1034   (setq inhibit-startup-message t)
   1035 #+end_src
   1036 
   1037 ** Start buffer (dashboard)
   1038 #+begin_src emacs-lisp
   1039   (use-package dashboard
   1040     :custom
   1041     (dashboard-startup-banner 'logo)
   1042     (dashboard-items '((gtd-inbox-counts . 3)
   1043                        (syncthing-status . 3)
   1044                        (recents . 5)
   1045                        (bookmarks . 5)))
   1046 
   1047 
   1048     :bind (:map dashboard-mode-map
   1049                 ("ss" . za/st)
   1050                 ("sk" . za/st-kill)
   1051                 ("J" . org-clock-goto))
   1052     :config
   1053     (add-to-list 'dashboard-item-generators '(gtd-inbox-counts . dashboard-insert-gtd-inbox-counts))
   1054     (add-to-list 'dashboard-item-generators '(syncthing-status . dashboard-insert-syncthing-status))
   1055 
   1056     (defun za/quotes-from-my-site ()
   1057       (let* ((quotes-file (concat za/my-website-dir "content/quotes.md"))
   1058              ;; Reformat quotes for display in dashboard
   1059              (file-contents (with-temp-buffer
   1060                               (insert-file-contents quotes-file)
   1061                               (re-search-forward (rx bol "> "))
   1062                               (delete-region (point-min) (pos-bol))
   1063                               (goto-char (point-min))
   1064                               (save-excursion (replace-regexp (rx bol ">" (* " ") (? "\n")) ""))
   1065                               (save-excursion (replace-regexp (rx eol "\n") "  "))
   1066                               (buffer-substring-no-properties (point-min) (point-max)))))
   1067         ;; Split file into individual quotes
   1068         (split-string file-contents "  ---  ")))
   1069 
   1070     (defun za/quotes-manual ()
   1071       '("The Universe is under no obligation to make sense to you."
   1072         "I would like to die on Mars. Just not on impact."
   1073         "That's one small step for a man, one giant leap for mankind."
   1074         "We choose to go to the moon in this decade and do the other things, not because they are easy, but because they are hard, because that goal will serve to organize and measure the best of our energies and skills, because that challenge is one that we are willing to accept, one we are unwilling to postpone, and one which we intend to win."
   1075         "Space is for everybody. It’s not just for a few people in science or math, or for a select group of astronauts. That’s our new frontier out there, and it’s everybody’s business to know about space."
   1076         "On one side are those who believe space travel is difficult work, but who go for it anyway. On the other are those who believe caring for a goldfish is, and who don’t go after much of anything. Where we choose to seed ourselves on the spectrum of what’s possible is what will ultimately define the size of our lives."))
   1077 
   1078     ;; Have to redefine this, original one has wrong type
   1079     (defcustom dashboard-footer-messages
   1080     '("The one true editor, Emacs!"
   1081       "Who the hell uses VIM anyway? Go Evil!"
   1082       "Free as free speech, free as free Beer"
   1083       "Happy coding!"
   1084       "Vi Vi Vi, the editor of the beast"
   1085       "Welcome to the church of Emacs"
   1086       "While any text editor can save your files, only Emacs can save your soul"
   1087       "I showed you my source code, pls respond")
   1088     "A list of messages, one of which dashboard chooses to display."
   1089     :type '(repeat string)
   1090     :group 'dashboard)
   1091 
   1092     ;; Use my saved quotes in the dashboard (https://alex.balgavy.eu/quotes/)
   1093     (setopt dashboard-footer-messages
   1094           (let* ((quotes (if (boundp 'za/my-website-dir) (za/quotes-from-my-site) (za/quotes-manual))))
   1095             ;; Run each quote through fill-region for better display
   1096             (require 's)
   1097             (mapcar (lambda (quote-line)
   1098                       (with-temp-buffer
   1099                         (insert (s-trim quote-line))
   1100                         (fill-region (point-min) (point-max))
   1101                         (buffer-substring-no-properties (point-min) (point-max))))
   1102                     quotes))))
   1103 
   1104   (defun dashboard-insert-gtd-inbox-counts (list-size)
   1105     (require 'org-roam)
   1106     (let* ((lines-inbox (za/org-count-headlines-in-file 1 za/org-life-inbox))
   1107            (lines-mobile (if (boundp 'za/org-life-inbox-mobile) (za/org-count-headlines-in-file 1 za/org-life-inbox-mobile) 0))
   1108            (count-docs (length (directory-files za/org-life-doc-inbox nil (rx bos (not ?.)))))
   1109            (item-list))
   1110 
   1111       (when (> lines-inbox 0)
   1112         (push (list :name "Inbox" :count lines-inbox :file za/org-life-inbox) item-list))
   1113       (when (> lines-mobile 0)
   1114         (push (list :name "Mobile" :count lines-mobile :file za/org-life-inbox-mobile) item-list))
   1115       (when (> count-docs 0)
   1116         (push (list :name "Docs" :count count-docs :file za/org-life-doc-inbox) item-list))
   1117 
   1118       (dashboard-insert-section
   1119        ;; Widget title
   1120        "GTD:"
   1121        ;; list generated for dashboard
   1122        item-list
   1123        list-size
   1124        'gtd
   1125        "t"
   1126        ;; decide what to do when clicked ("el" is automatically assigned)
   1127        `(lambda (&rest _)
   1128           (message "%s" (find-file (plist-get ',el :file))))
   1129        ;; show how list is shown in dashboard ("el" is automatically assigned)
   1130        (format "%s: %s" (plist-get el :name) (plist-get el :count)))))
   1131 
   1132   (defun dashboard-insert-syncthing-status (list-size)
   1133     (when (and (get-buffer-process za/st-buffer-name)
   1134                (boundp 'za/syncthing-api-key))
   1135       (let* ((syncstatus (json-parse-string
   1136                           (shell-command-to-string
   1137                            (format "curl -sH 'Authorization: Bearer %s' 'http://localhost:8384/rest/db/completion'" za/syncthing-api-key))))
   1138              (completion (gethash "completion" syncstatus))
   1139              (folders (json-parse-string
   1140                        (shell-command-to-string
   1141                         (format "curl -sH 'Authorization: Bearer %s' 'http://localhost:8384/rest/stats/folder'" za/syncthing-api-key))
   1142                        :false-object nil
   1143                        :null-object nil))
   1144              (org-lastsync (format-time-string "%H:%M:%S (%F)" (date-to-time (gethash "lastScan" (gethash "lifeorg" folders)))))
   1145              (devices (json-parse-string
   1146                        (shell-command-to-string
   1147                         (format "curl -sH 'Authorization: Bearer %s' 'http://localhost:8384/rest/system/connections'" za/syncthing-api-key))
   1148                        :object-type 'alist
   1149                        :false-object nil
   1150                        :null-object nil))
   1151              (connected-devices (length (seq-filter
   1152                                          (lambda (a)
   1153                                            (alist-get 'connected (cdr a))) (alist-get 'connections devices))))
   1154              (item-list `(,(format "Completion: %s%%" completion)
   1155                           ,(format "Connected devices: %s" connected-devices)
   1156                           ,(format "Org last sync: %s" org-lastsync))))
   1157 
   1158         (dashboard-insert-section
   1159          ;; Widget title
   1160          "Syncthing:"
   1161          ;; list generated for dashboard
   1162          item-list
   1163          list-size
   1164          'syncthing-status
   1165          ;; shortcut key for section
   1166          nil
   1167          ;; when clicked
   1168          (lambda (&rest _) ())
   1169          ;; show how list is shown in dashboard ("el" is automatically assigned)
   1170          (format "%s" el)))))
   1171 
   1172   (dashboard-setup-startup-hook)
   1173   (setq initial-buffer-choice (lambda () (get-buffer-create "*dashboard*")))
   1174 #+end_src
   1175 
   1176 ** Scrolling
   1177 #+begin_src emacs-lisp
   1178   (setopt scroll-step 1)
   1179   ;; Marker distance from center
   1180   (setopt scroll-conservatively 100000)
   1181   ;; Keep screen position on scroll
   1182   (setopt scroll-preserve-screen-position 1)
   1183   ;; Start scrolling when marker at top/bottom
   1184   (setopt scroll-margin 0)
   1185 
   1186   ;; Mouse scrolls 1 line at a time
   1187   (setopt mouse-wheel-scroll-amount '(1))
   1188 
   1189   ;; On a long mouse scroll keep scrolling by 1 line
   1190   (setq mouse-wheel-progressive-speed nil)
   1191 
   1192   ;; Enable pixel scroll precision mode
   1193   (unless (version< emacs-version "29")
   1194     (pixel-scroll-precision-mode))
   1195 
   1196   ;; Speed up cursor movement.
   1197   ;; https://emacs.stackexchange.com/questions/28736/emacs-pointcursor-movement-lag/28746
   1198   (setopt auto-window-vscroll nil)
   1199 #+end_src
   1200 * General packages
   1201 
   1202 ** which-key
   1203 Minor mode for Emacs that displays the key bindings following your currently entered incomplete command (a prefix) in a popup.
   1204 
   1205 #+BEGIN_SRC emacs-lisp
   1206   (use-package which-key
   1207     :delight
   1208     :config
   1209     (which-key-mode))
   1210 #+end_src
   1211 
   1212 ** counsel + ivy + swiper + prescient
   1213 Better incremental completion and selection narrowing.
   1214 And a bunch more.
   1215 Generally makes for nicer interactivity, like ido mode on steroids.
   1216 Switched to this from Helm, it's more lightweight.
   1217 
   1218 *** ivy: generic completion mechanism
   1219 #+begin_src emacs-lisp
   1220   (use-package ivy
   1221     :delight
   1222     :custom
   1223     (ivy-use-virtual-buffers t "extend searching to bookmarks")
   1224     (ivy-height 20 "set height of the ivy window")
   1225     (ivy-count-format "(%d/%d) " "count format, from the ivy help page")
   1226     (ivy-display-style 'fancy)
   1227     (ivy-format-function 'ivy-format-function-line)
   1228     (ivy-use-selectable-prompt t "to let me select exactly what I'm typing as a candidate")
   1229 
   1230     :bind (("C-x b" . ivy-switch-buffer)
   1231            ("C-c v" . ivy-push-view)
   1232            ("C-c V" . ivy-pop-view)
   1233 
   1234            ;; accidentally pressing shift-space deletes input, because
   1235            ;; by default, shift-space is bound to
   1236            ;; ~ivy-restrict-to-matches~ in the ivy minibuffer.
   1237            :map ivy-minibuffer-map
   1238            ("S-SPC" . (lambda () (interactive) (insert ?\s)))
   1239            ("<backtab>" . ivy-restrict-to-matches))
   1240     :config
   1241     (ivy-add-actions
   1242      'counsel-dired
   1243      '(("f" (lambda (dir) (counsel-fzf nil dir)) "Fzf in directory")
   1244        ("g" (lambda (dir) (counsel-ag nil dir)) "Ag in directory")))
   1245     (ivy-add-actions
   1246      'dired
   1247      '(("f" (lambda (dir) (ivy-exit-with-action (counsel-fzf nil dir))) "Fzf in directory")
   1248        ("g" (lambda (dir) (ivy-exit-with-action (counsel-ag nil dir))) "Ag in directory")))
   1249     (ivy-add-actions
   1250      'counsel-describe-function
   1251      '(("d" (lambda (fun) (ivy-exit-with-action (edebug-instrument-function (intern fun)))) "Edebug instrument function")))
   1252     (ivy-mode)
   1253 
   1254     (defun edit-script ()
   1255       "Edit a file in ~/.scripts/"
   1256       (interactive)
   1257       (let ((input (ivy--input)))
   1258         (ivy-quit-and-run (counsel-file-jump nil "~/.scripts/"))))
   1259 
   1260     (defun edit-config ()
   1261       "Edit a file in ~/.dotfiles/"
   1262       (interactive)
   1263       (let ((input (ivy--input)))
   1264         (ivy-quit-and-run (counsel-file-jump nil "~/.dotfiles/")))))
   1265 #+end_src
   1266 
   1267 *** counsel: collection of common Emacs commands enhanced using ivy
   1268 #+begin_src emacs-lisp
   1269   (use-package counsel
   1270     :demand
   1271     :delight
   1272     :config
   1273     (counsel-mode)
   1274     :bind (("M-x" . counsel-M-x)
   1275            ("C-x C-f" . counsel-find-file)
   1276            ("M-y" . counsel-yank-pop)
   1277            ("C-c c" . counsel-compile)
   1278            ("M-s g" . counsel-rg)
   1279            ("M-s f" . counsel-fzf)
   1280            ("C-c b" . counsel-bookmark)
   1281            ("C-c p" . counsel-recentf)
   1282            ("C-c o" . counsel-outline)
   1283            ("C-h f" . counsel-describe-function)
   1284            ("C-h v" . counsel-describe-variable)
   1285            ("C-h o" . counsel-describe-symbol)
   1286            ("C-c g j" . counsel-org-agenda-headlines)))
   1287 #+end_src
   1288 *** swiper: search enhanced using ivy
   1289 #+begin_src emacs-lisp
   1290   (use-package swiper
   1291     :bind (("C-s" . swiper-isearch)
   1292            ("C-r" . swiper-isearch-backward)))
   1293 #+end_src
   1294 *** prescient: scoring system for M-x
   1295 #+begin_src emacs-lisp
   1296   (use-package prescient
   1297     :config (prescient-persist-mode))
   1298 
   1299   (use-package ivy-prescient
   1300     :after counsel
   1301     :custom (ivy-prescient-retain-classic-highlighting t)
   1302     :config (ivy-prescient-mode))
   1303 #+end_src
   1304 
   1305 *** ivy-posframe: ivy in a popup
   1306 I like having ivy in a popup.
   1307 Problem: posframe does not work if emacs is too old and on macos.
   1308 See here: https://github.com/tumashu/posframe/issues/30
   1309 On Mac, ~brew install --HEAD emacs~ doesn't work either.
   1310 Solution: ~brew tap daviderestivo/emacs-head && brew install emacs-head@28 --with-cocoa~
   1311 
   1312 #+begin_src emacs-lisp
   1313   (if (and (version< emacs-version "28") (equal system-type 'darwin))
   1314       (message "ivy-posframe won't work properly, run `brew install daviderestivo/emacs-head/emacs-head@28 --with-cocoa`")
   1315     (use-package ivy-posframe
   1316       :delight
   1317       :custom
   1318       (ivy-posframe-display-functions-alist '((t . ivy-posframe-display-at-frame-center)))
   1319       (ivy-posframe-parameters
   1320        '((left-fringe . 8)
   1321          (right-fringe . 8)))
   1322       (ivy-posframe-border-width 3)
   1323       (ivy-truncate-lines nil) ;; otherwise the cursor gets hidden by long lines in posframe
   1324       :custom-face
   1325       (ivy-posframe-border ((t (:inherit mode-line-inactive))))
   1326       :config
   1327       (ivy-posframe-mode 1)))
   1328 #+end_src
   1329 
   1330 [[https://github.com/tumashu/ivy-posframe/issues/123][See here]] for cursor going offscreen in the posframe. Currently 'solved' with ~ivy-truncate-lines~ nil.
   1331 
   1332 ** DISABLED vertico + consult + marginalia + embark + posframe + prescient
   1333 Alternative to counsel/ivy/swiper, will probably switch to this at some point.
   1334 [[https://old.reddit.com/r/emacs/comments/qfrxgb/using_emacs_episode_80_vertico_marginalia_consult/hi6mfh7/][Here]] is a good comparison.
   1335 
   1336 A [[https://old.reddit.com/r/emacs/comments/11lqkbo/weekly_tips_tricks_c_thread/jbe06qv/][comment here to follow]] when I switch to vertico.
   1337 #+begin_src emacs-lisp :tangle no
   1338   (dolist (pack '(vertico consult marginalia embark vertico-posframe vertico-prescient))
   1339     (unless (package-installed-p pack)
   1340       (package-install pack))
   1341     (require pack))
   1342 
   1343   (vertico-mode 1)
   1344   (vertico-posframe-mode 1)
   1345   (marginalia-mode 1)
   1346   (vertico-prescient-mode 1)
   1347   (setq completion-styles '(basic substring partial-completion flex))
   1348 
   1349   (global-set-key (kbd "M-o") #'embark-act)
   1350   (global-set-key (kbd "C-s") #'consult-line)
   1351 
   1352 #+end_src
   1353 ** company: completion mechanism
   1354 #+begin_src emacs-lisp
   1355   (use-package company)
   1356 #+end_src
   1357 
   1358 ** wgrep: writable grep
   1359 #+begin_src emacs-lisp
   1360   (use-package wgrep)
   1361 #+end_src
   1362 ** avy: jump to any position
   1363 This lets me jump to any position in Emacs rather quickly, sometimes it's useful.
   1364 ~avy-goto-char-timer~ lets me type a part of the text before avy kicks in.
   1365 
   1366 #+begin_src emacs-lisp
   1367   (use-package avy
   1368     :custom
   1369     (avy-single-candidate-jump nil "Often I want to perform an action, never jump automatically")
   1370     :bind
   1371     (("C-:" . avy-goto-char-timer)))
   1372 #+end_src
   1373 
   1374 ** calendar
   1375 #+begin_src emacs-lisp
   1376   (use-package calendar
   1377     :ensure nil ; comes with Emacs
   1378     :custom
   1379     (calendar-week-start-day 1))
   1380 #+end_src
   1381 ** calfw: graphical calendar
   1382 Basically provides a way to show the org agenda as a standard GUI calendar app would.
   1383 
   1384 #+begin_src emacs-lisp
   1385   (use-package calfw
   1386     :config
   1387     (use-package calfw-org)
   1388     :custom
   1389     (cfw:org-overwrite-default-keybinding t))
   1390 #+end_src
   1391 
   1392 ** vanish: hide parts of the file
   1393 #+begin_src emacs-lisp
   1394   (use-package vanish
   1395     :init
   1396     (za/package-vc-install :repo "thezeroalpha/vanish.el" :rev "develop")
   1397     (require 'vanish)
   1398     :ensure nil
   1399     :bind (:map vanish-mode-map
   1400                 ("C-c q h h" . vanish-hide-dwim)
   1401                 ("C-c q h u r" . vanish-show-all-regions)
   1402                 ("C-c q h u e" . vanish-elt-unhide)
   1403                 ("C-c q h u u" . vanish-show-all)))
   1404 #+end_src
   1405 ** magit
   1406 #+begin_src emacs-lisp
   1407   (use-package magit)
   1408 #+end_src
   1409 ** vterm
   1410 Emacs has a bunch of built-in terminal emulators.
   1411 And they all suck.
   1412 (OK not really, eshell is alright, but not for interactive terminal programs like newsboat/neomutt)
   1413 
   1414 Also use emacsclient inside vterm as an editor, because that'll open documents in the existing Emacs session.
   1415 And I'm not gonna be a heretic and open Vim inside of Emacs.
   1416 
   1417 #+begin_src emacs-lisp
   1418   (use-package vterm
   1419     :hook
   1420     (vterm-mode . (lambda () (unless server-process (server-start))))
   1421     :bind (("C-c t" . switch-to-vterm))
   1422     :config
   1423     (defun switch-to-vterm ()
   1424       "Switch to a running vterm, or start one and switch to it."
   1425       (interactive)
   1426       (if (get-buffer vterm-buffer-name)
   1427           (switch-to-buffer vterm-buffer-name)
   1428         (vterm))))
   1429 #+end_src
   1430 ** sr-speedbar
   1431 Make speed bar show in the current frame.
   1432 
   1433 #+begin_src emacs-lisp
   1434   (use-package sr-speedbar
   1435     :bind (("C-c F" . za/jump-to-speedbar-or-open)
   1436            :map speedbar-mode-map
   1437            ("q" . sr-speedbar-close))
   1438     :custom
   1439     (sr-speedbar-right-side nil)
   1440 
   1441     :config
   1442     (defun za/jump-to-speedbar-or-open ()
   1443       "Open a speedbar or jump to it if already open."
   1444       (interactive)
   1445       (if (or (not (boundp 'sr-speedbar-exist-p))
   1446               (not (sr-speedbar-exist-p)))
   1447           (sr-speedbar-open))
   1448       (sr-speedbar-select-window)))
   1449 #+end_src
   1450 ** expand-region
   1451 Expand the selected region semantically.
   1452 
   1453 #+begin_src emacs-lisp
   1454   (use-package expand-region
   1455     :bind ("C-=" . er/expand-region))
   1456 #+end_src
   1457 ** flycheck
   1458 Install flycheck:
   1459 
   1460 #+begin_src emacs-lisp
   1461   (use-package flycheck)
   1462 #+end_src
   1463 ** rainbow-mode: visualise hex colors
   1464 'rainbow-mode' lets you visualise hex colors:
   1465 
   1466 #+begin_src emacs-lisp
   1467   (use-package rainbow-mode)
   1468 #+end_src
   1469 ** hl-todo: highlight TODO keywords
   1470 I want to highlight TODO keywords in comments:
   1471 
   1472 #+begin_src emacs-lisp
   1473   (use-package hl-todo
   1474     :custom-face
   1475     (hl-todo ((t (:inherit hl-todo :underline t))))
   1476     :custom
   1477     (hl-todo-keyword-faces '(("TODO"   . "#ff7060")
   1478                              ("FIXME"  . "#caa000")))
   1479     :config
   1480     (global-hl-todo-mode t))
   1481 #+end_src
   1482 ** undo-tree
   1483 Sometimes it's better to look at undo history as a tree:
   1484 
   1485 #+begin_src emacs-lisp
   1486   (use-package undo-tree
   1487     :delight
   1488     :custom
   1489     (undo-tree-history-directory-alist
   1490      (progn (let ((undo-tree-dir (concat user-emacs-directory "undo-tree/")))
   1491               (unless (file-directory-p undo-tree-dir) (make-directory undo-tree-dir))
   1492               `(("." . ,undo-tree-dir)))))
   1493 
   1494     :config
   1495     (global-undo-tree-mode))
   1496 #+end_src
   1497 
   1498 *** TODO undo tree dir should be configurable
   1499 ** eglot
   1500 A good LSP plugin.
   1501 
   1502 #+begin_src emacs-lisp
   1503   (use-package eglot)
   1504 #+end_src
   1505 ** crdt
   1506 Collaborative editing in Emacs:
   1507 
   1508 #+begin_src emacs-lisp
   1509   (use-package crdt)
   1510 #+end_src
   1511 ** git gutter
   1512 General git gutter:
   1513 
   1514 #+begin_src emacs-lisp
   1515   (use-package git-gutter
   1516     :bind (("C-c d n" . git-gutter:next-hunk)
   1517            ("C-c d p" . git-gutter:previous-hunk))
   1518     :config
   1519     (global-git-gutter-mode 1))
   1520 #+end_src
   1521 ** keycast
   1522 In case I want to show what keys I'm pressing.
   1523 
   1524 #+begin_src emacs-lisp
   1525   (use-package keycast)
   1526 #+end_src
   1527 ** ace-window: better window switching
   1528 Window switching with ~other-window~ sucks when I have more than 2 windows open. Too much cognitive load.
   1529 This lets me select a window to jump to using a single key, sort of like ~avy~.
   1530 
   1531 #+begin_src emacs-lisp
   1532   (use-package ace-window
   1533     :custom
   1534     (aw-keys '(?a ?s ?d ?f ?g ?h ?j ?k ?l) "I prefer using home-row keys instead of numbers")
   1535 
   1536     :custom-face
   1537     ;; I want something a little more contrasty
   1538     (aw-leading-char-face ((t (:inherit font-lock-keyword-face :height 2.0))))
   1539 
   1540     :bind ("M-o" . ace-window))
   1541 #+end_src
   1542 ** decide-mode for dice rolling
   1543 #+begin_src emacs-lisp
   1544   (use-package decide
   1545     :init (za/package-vc-install :repo "lifelike/decide-mode" :name "decide")
   1546     :ensure nil
   1547     :bind ("C-c q ?" . decide-mode))
   1548 #+end_src
   1549 
   1550 ** try: try out different packages
   1551 #+begin_src emacs-lisp
   1552   (use-package try)
   1553 #+end_src
   1554 ** dumb-jump
   1555 "jump to definition" package, minimal configuration with no stored indexes.
   1556 Uses The Silver Searcher ag, ripgrep rg, or grep to find potential definitions of a function or variable under point.
   1557 
   1558 #+begin_src emacs-lisp
   1559   (use-package dumb-jump)
   1560 #+end_src
   1561 
   1562 Enable xref backend:
   1563 
   1564 #+begin_src emacs-lisp
   1565   (add-hook 'xref-backend-functions #'dumb-jump-xref-activate)
   1566   (setq xref-show-definitions-function #'xref-show-definitions-completing-read)
   1567 #+end_src
   1568 ** DISABLED command-log-mode
   1569 Simple real-time logger of commands.
   1570 
   1571 #+begin_src emacs-lisp :tangle no
   1572   (use-package command-log-mode)
   1573 #+end_src
   1574 ** package-lint
   1575 Linter for the metadata in Emacs Lisp files which are intended to be packages.
   1576 
   1577 #+begin_src emacs-lisp
   1578   (use-package package-lint)
   1579   (use-package flycheck-package)
   1580   (eval-after-load 'flycheck
   1581     '(flycheck-package-setup))
   1582 #+end_src
   1583 ** prism: change color of text depending on depth
   1584 Prism changes the color of text depending on their depth. Makes it easier to see where something is at a glance.
   1585 
   1586 #+begin_src emacs-lisp
   1587   (use-package prism)
   1588 #+end_src
   1589 ** olivetti: distraction-free writing
   1590 #+begin_src emacs-lisp
   1591   (use-package olivetti
   1592     :diminish)
   1593 #+end_src
   1594 ** nov.el: EPUB support
   1595 #+begin_src emacs-lisp
   1596   (use-package nov)
   1597   (add-to-list 'auto-mode-alist '("\\.epub\\'" . nov-mode))
   1598 #+end_src
   1599 ** god-mode: reduce the need to hold down modifier keys
   1600 - All commands are assumed to use the control modifier (C-) unless otherwise indicated.
   1601 - g is used to indicate the meta modifier
   1602 - G is used to indicate both the control and meta modifiers
   1603 #+begin_src emacs-lisp
   1604   (use-package god-mode
   1605     :bind
   1606     (("s-<escape>" . god-mode-all)
   1607      :map god-local-mode-map
   1608      ("z" . repeat)
   1609      ("i" . god-local-mode))
   1610     :hook    (post-command . za/god-mode-update-mode-line)
   1611     :config
   1612     (defun za/god-mode-update-mode-line ()
   1613       "Update the color of the modeline depending on god-mode."
   1614       (cond (god-local-mode
   1615              (set-face-attribute 'mode-line nil :background "#770085"))
   1616             (t
   1617              (let* ((current-theme (car custom-enabled-themes))
   1618                      (theme-settings (get current-theme 'theme-settings)))
   1619                 (dolist (theme-setting theme-settings)
   1620                   (if (and (eq (car theme-setting) 'theme-face)
   1621                            (eq (cadr theme-setting) 'mode-line))
   1622                       (let* ((face-def (caar (last theme-setting)))
   1623                              (properties (car (last face-def)))
   1624                              (bg (plist-get properties :background)))
   1625                         (set-face-attribute 'mode-line nil :background bg)))))))))
   1626 #+end_src
   1627 ** devil: alternative to god-mode that uses a comma
   1628 #+begin_src emacs-lisp
   1629   (use-package devil
   1630     :init
   1631     (za/package-vc-install :repo "susam/devil")
   1632     (require 'devil)
   1633     :custom
   1634     (devil-lighter " \u272A")
   1635     (devil-prompt "\u272A %t")
   1636     :config (global-devil-mode)
   1637     :bind ("C-," . global-devil-mode))
   1638 #+end_src
   1639 ** academic-phrases
   1640 Gives ideas for phrases to use in academic writing.
   1641 #+begin_src emacs-lisp
   1642   (use-package academic-phrases)
   1643 #+end_src
   1644 ** ediff
   1645 #+begin_src emacs-lisp
   1646   (use-package ediff
   1647     :custom
   1648     ((ediff-keep-variants nil "Prompt to remove unmodifid buffers after session")
   1649      (ediff-make-buffers-readonly-at-startup nil "Don't make all buffers read-only at startup")
   1650      (ediff-show-clashes-only t "Only show diff regions where both buffers disagree with ancestor")
   1651      (ediff-split-window-function 'split-window-horizontally "I want long vertical side-by-side windows")
   1652      (ediff-window-setup-function 'ediff-setup-windows-plain "Everything in one frame please")))
   1653 #+end_src
   1654 ** highlight-indent-guides
   1655 #+begin_src emacs-lisp
   1656   (use-package highlight-indent-guides
   1657     :hook (yaml-mode . highlight-indent-guides-mode)
   1658     :custom
   1659     ((highlight-indent-guides-method 'character))
   1660     :custom-face
   1661     (highlight-indent-guides-character-face ((t (:foreground "#adadad")))))
   1662 #+end_src
   1663 ** cc-avy
   1664 #+begin_src emacs-lisp
   1665   (use-package cc-avy
   1666     :ensure nil ; local
   1667     :bind ("C-M-:" . cc/avy-menu))
   1668 #+end_src
   1669 ** annotate
   1670 #+begin_src emacs-lisp
   1671   (use-package annotate
   1672     :custom (annotate-annotation-position-policy :margin)
   1673     :config
   1674     (defun za/annotate-initialize-extra-hooks ()
   1675       (add-hook 'after-save-hook #'annotate-save-annotations t t))
   1676     (defun za/annotate-shutdown-extra-hooks ()
   1677       (remove-hook 'after-save-hook #'annotate-save-annotations t))
   1678     (advice-add 'annotate-initialize :after #'za/annotate-initialize-extra-hooks)
   1679     (advice-add 'annotate-shutdown :after #'za/annotate-shutdown-extra-hooks))
   1680 
   1681 #+end_src
   1682 ** yasnippet
   1683 #+begin_src emacs-lisp
   1684   (use-package yasnippet
   1685     :config (yas-global-mode)
   1686     :delight)
   1687 #+end_src
   1688 * Mode/language specific packages
   1689 ** Org
   1690 *** Custom functions
   1691 **** Get number of headlines in a file
   1692 #+begin_src emacs-lisp
   1693   (defun za/org-count-headlines-in-file (level filename)
   1694     "Count number of level LEVEL headlines in FILENAME. If LEVEL is 0, count all."
   1695     (let ((headline-str (cond ((zerop level) "^\*+")
   1696                               (t (format "^%s " (apply 'concat (make-list level "\\*")))))))
   1697       (save-mark-and-excursion
   1698         (with-temp-buffer
   1699           (insert-file-contents filename)
   1700           (count-matches headline-str (point-min) (point-max))))))
   1701 #+end_src
   1702 
   1703 **** Yank URL
   1704 #+begin_src emacs-lisp
   1705   (defun org-yank-link-url ()
   1706     (interactive)
   1707     (kill-new (org-element-property :raw-link (org-element-context)))
   1708     (message "Link copied to clipboard"))
   1709 #+end_src
   1710 *** Installation
   1711 Install Org and require additional components that I use.
   1712 
   1713 #+begin_src emacs-lisp
   1714   (use-package org
   1715     :custom
   1716     (org-outline-path-complete-in-steps nil "Complete path all at once (needed for completion frameworks")
   1717     (org-format-latex-options (plist-put org-format-latex-options :scale 2.0) "Larger latex previews")
   1718     (org-goto-interface 'outline-path-completion "Use outline path completion for org-goto, instead of its weird interface")
   1719     (org-insert-heading-respect-content t "Insert headings after current subtree")
   1720     (org-clock-report-include-clocking-task t "Include currently active task in clocktable")
   1721     (org-id-link-to-org-use-id 'create-if-interactive "If org-store-link is called directly, create an ID.")
   1722     (org-clock-mode-line-total 'today)
   1723     (org-return-follows-link t "Easier link following. Actual enter is still possible with ~C-q C-j~.")
   1724     (org-hide-emphasis-markers t "Don't show italics/bold markers")
   1725     (org-babel-python-command "python3")
   1726     (org-confirm-babel-evaluate nil)
   1727     (org-file-apps '((auto-mode . emacs)
   1728                      (directory . emacs)
   1729                      ("\\.mm\\'" . default)
   1730                      ("\\.x?html?\\'" . default)
   1731                      ("\\.pdf\\'" . emacs)))
   1732     (org-link-elisp-confirm-function #'y-or-n-p)
   1733     (org-link-elisp-skip-confirm-regexp "^org-noter$")
   1734     (org-clock-sound (concat user-emacs-directory "notification.wav"))
   1735     (org-export-backends '(ascii html icalendar latex md odt org pandoc jira))
   1736     (org-catch-invisible-edits 'show-and-error
   1737                                "Sometimes when text is folded away, I might accidentally edit text inside of it. This option prevents that. I wanted to do 'smart', but that has a 'fixme' so it might change in the future...Instead, show what's being edited, but don't perform the edit.")
   1738     (org-src-tab-acts-natively t "a tab in a code block indents the code as it should")
   1739     (org-attach-store-link-p 'attached)
   1740     (org-attach-archive-delete 'query)
   1741     (org-archive-subtree-add-inherited-tags t)
   1742     (org-stuck-projects '("/PROJ"
   1743                           ("NEXT" "STARTED")
   1744                           nil nil)
   1745                         "List projects that are stuck (don't have a next action)")
   1746     (org-tag-alist (let ((za/org-tag-energy-levels
   1747                           '((:startgroup)
   1748                             ("sport" . ?h) ; Sport (deep focus, long tasks, no interruptions, at least an hour)
   1749                             ("cruise" . ?l) ; Cruise (shallow focus, can be interrupted, can batch lots of quick tasks together)
   1750                             ("parked" . ?e) ; Parked (take a break, look into the distance, walk the dog, stretch, etc.)
   1751                             ("errand" . ?o) ; Errand (anything that involves me being out of the house)
   1752                             (:endgroup)))
   1753                          (za/org-tag-1-3-5
   1754                           '(; 1-3-5 tagging
   1755                             (:startgroup)
   1756                             ("_1" . ?1) ; 1 big task, 3-4 hrs
   1757                             ("_3" . ?3) ; 3 medium tasks, 1-2 hrs
   1758                             ("_5" . ?5) ; 5 small tasks, 30min-1hr
   1759                             (:endgroup))))
   1760                      `(,@za/org-tag-contexts ,@za/org-tag-energy-levels ,@za/org-tag-1-3-5)))
   1761 
   1762     :bind (("C-c a" . org-agenda)
   1763            ("C-c n" . org-capture)
   1764            ("C-c l" . org-store-link)
   1765            :map org-mode-map
   1766            ("C-M-<return>" . org-insert-todo-heading)
   1767            ("C-c M-y" . org-yank-link-url)
   1768            ("C-c N" . org-noter)
   1769            ("C-M-i" . completion-at-point)
   1770            ("C-c SPC" . org-table-blank-field)
   1771            ("C-c C-w" . za/org-refile-wrapper))
   1772     :hook ((org-mode . abbrev-mode)
   1773            (org-mode . za/echo-area-tooltips)
   1774            (org-mode . org-superstar-mode)
   1775            (org-mode . org-indent-mode)
   1776            (org-mode . za/settings-on-org-mode)
   1777            (org-mode . org-pretty-table-mode)
   1778            (org-mode . variable-pitch-mode))
   1779     :config
   1780     (za/package-vc-install :repo "Fuco1/org-pretty-table")
   1781     (require 'org-pretty-table)
   1782     (delight 'org-pretty-table nil)
   1783 
   1784 
   1785     (za/package-vc-install :repo "https://git.sr.ht/~bzg/org-contrib" :load "lisp/")
   1786     (require 'org-contrib)
   1787     (require 'org-checklist)
   1788     (delight 'org-indent-mode nil 'org-indent)
   1789     (defun za/settings-on-org-mode ()
   1790       "Settings on enabling org mode"
   1791       (za/toggle-wrap t))
   1792 
   1793     (defcustom za/org-inline-images-desired-screen-proportion (/ (float 3) 4)
   1794       "Percentage of the window (as a float) that Org inline images should take up."
   1795       :type 'float)
   1796 
   1797     (defun za/org-display-inline-images-set-width (&rest _)
   1798       "Set `org-image-actual-width` dynamically before displaying images."
   1799       (if (window-system)
   1800           (let* ((total-width (window-pixel-width))
   1801                  (image-width (round (* total-width za/org-inline-images-desired-screen-proportion))))
   1802             (setq-local org-image-actual-width image-width))))
   1803 
   1804     (advice-add 'org-display-inline-images :before #'za/org-display-inline-images-set-width)
   1805 
   1806     (defun za/org-attach-tag (old/org-attach-tag &rest args)
   1807       "Wraps :around org-attach-tag (as OLD/ORG-ATTACH-TAG) with ARGS.
   1808   When inside capture for org-roam, attaching fails at
   1809   org-attach-tag. This function prevents that error interrupting
   1810   org-attach."
   1811       (if ; there's no heading
   1812           (not (org-element-lineage (org-element-at-point)
   1813                                     '(headline inlinetask)
   1814                                     'include-self))
   1815           nil ; there's no point attaching a tag
   1816                                           ; otherwise, normal attach
   1817         (apply old/org-attach-tag args)))
   1818 
   1819     (advice-add #'org-attach-tag :around #'za/org-attach-tag)
   1820     (defun za/org-clear-1-3-5 ()
   1821       "Clears the _1/_3/_5 daily tags from all antries."
   1822       (interactive)
   1823       (let ((number-of-entries
   1824              (length (org-map-entries
   1825                       (lambda ()
   1826                         (let* ((tags-1-3-5 '("_1" "_3" "_5"))
   1827                                (tags-without-1-3-5 (seq-remove (lambda (e) (member e tags-1-3-5))
   1828                                                                org-scanner-tags)))
   1829                           (org-set-tags tags-without-1-3-5)))
   1830                       "_1|_3|_5"
   1831                       'agenda-with-archives))))
   1832         (message "Modified %d entries." number-of-entries)))
   1833     (defun za/archive-finished-tickler ()
   1834       (interactive)
   1835       (progn
   1836         (find-file-other-window za/org-life-tickler)
   1837         (length (org-map-entries
   1838                  (lambda ()
   1839                    (org-fold-show-subtree)
   1840                    (when (y-or-n-p "Archive? ")
   1841                      (org-archive-subtree-default)
   1842                      (save-buffer)))
   1843                  "TIMESTAMP<*\"<today>\""
   1844                  'file))))
   1845 
   1846     (require 'org-tempo)
   1847     (require 'org-habit)
   1848     (require 'org-id)
   1849     (use-package ob-async)
   1850     (use-package ob-rust)
   1851     (org-babel-do-load-languages
   1852      'org-babel-load-languages
   1853      '((emacs-lisp . t)
   1854        (R . t)
   1855        (python . t)
   1856        (ruby . t)
   1857        (shell . t)
   1858        (sqlite . t)
   1859        (rust . t)))
   1860     (use-package inf-ruby)
   1861     (use-package org-superstar
   1862       :custom
   1863       (org-superstar-leading-bullet ?\s))
   1864 
   1865     ;; Linking to emails via notmuch
   1866     (use-package ol-notmuch)
   1867 
   1868     ;; Improved search
   1869     (use-package org-ql)
   1870 
   1871     ;; My override for org clock resolve
   1872     (require 'org-clock-override)
   1873 
   1874     ;; Tempo expansions
   1875     (add-to-list 'org-structure-template-alist '("se" . "src emacs-lisp"))
   1876     (add-to-list 'org-structure-template-alist '("sb" . "src bibtex"))
   1877     (add-to-list 'org-structure-template-alist '("ss" . "src sh"))
   1878     (add-to-list 'org-structure-template-alist '("sy" . "src yaml")))
   1879 #+end_src
   1880 *** Agenda & GTD
   1881 **** Agenda mode settings
   1882 #+begin_src emacs-lisp
   1883   (use-package org-agenda
   1884     :ensure org
   1885     :bind (:map org-agenda-mode-map
   1886                 ("C-c TAB" . za/org-agenda-goto-narrowed-subtree)
   1887                 ("@" . za/org-agenda-show-context-tags))
   1888     :custom
   1889     (org-agenda-files (list za/org-life-main
   1890                             za/org-life-inbox
   1891                             za/org-life-tickler))
   1892     (org-agenda-text-search-extra-files
   1893      (directory-files za/org-life-dir t (rx bol (not ?.) (* anything) ".org"))
   1894      "I want to search all Org files in the life directory")
   1895 
   1896     :config
   1897     (defun za/org-agenda-show-context-tags ()
   1898       "Show the context tags (e.g. @computer) applicable to the current item."
   1899       (interactive)
   1900       (let* ((tags (org-get-at-bol 'tags))
   1901              (context-tag-p (lambda (tag) (string-prefix-p "@" tag)))
   1902              (context-tags (seq-filter context-tag-p tags)))
   1903         (if context-tags
   1904             (message "Contexts are :%s:"
   1905                      (org-no-properties (mapconcat #'identity context-tags ":")))
   1906           (message "No contexts associated with this line"))))
   1907     (defun za/org-agenda-goto-narrowed-subtree ()
   1908       "Jump to current agenda item and narrow to its subtree."
   1909       (interactive)
   1910       (delete-other-windows)
   1911       (org-agenda-goto)
   1912       (org-narrow-to-subtree)
   1913       (outline-hide-subtree)
   1914       (org-show-children 1)
   1915       (other-window 1)))
   1916 #+end_src
   1917 
   1918 Fix tag display by dynamically calculating the column.
   1919 
   1920 #+begin_src emacs-lisp
   1921   (defun za/settings-org-agenda-mode ()
   1922     "My settings for org agenda mode"
   1923     )
   1924   (add-hook 'org-agenda-mode-hook #'za/settings-org-agenda-mode)
   1925 #+end_src
   1926 
   1927 **** Opening files
   1928 Convenience functions to make opening the main file faster:
   1929 
   1930 #+begin_src emacs-lisp
   1931   (defun gtd () "GTD: main file" (interactive) (find-file za/org-life-main))
   1932   (defun gtd-inbox ()
   1933     "GTD: inbox"
   1934     (interactive)
   1935     (let ((count-docs (length (directory-files za/org-life-doc-inbox nil (rx bos (not ?.))))))
   1936       (find-file za/org-life-inbox)
   1937       (when (> count-docs 0)
   1938         (dired-other-window za/org-life-doc-inbox)
   1939         (dired-revert)
   1940         (other-window 1))))
   1941   (defun gtd-inbox-mobile () "GTD: mobile inbox" (interactive) (find-file za/org-life-inbox-mobile))
   1942   (defun gtd-archive () "GTD: archive" (interactive) (find-file za/org-life-archive))
   1943   (defun gtd-someday () "GTD: someday" (interactive) (find-file za/org-life-someday))
   1944   (defun gtd-tickler () "GTD: tickler" (interactive) (find-file za/org-life-tickler))
   1945 #+end_src
   1946 
   1947 Bind keys to those functions:
   1948 
   1949 #+begin_src emacs-lisp
   1950   (bind-keys :prefix "M-g t"
   1951              :prefix-map za/gtd-files-map
   1952              :prefix-docstring "Visit GTD file"
   1953              ("i" . gtd-inbox)
   1954              ("l" . gtd)
   1955              ("a" . gtd-archive)
   1956              ("s" . gtd-someday)
   1957              ("t" . gtd-tickler))
   1958 #+end_src
   1959 
   1960 To improve jumping to any headline via counsel, filter returned candidates to include source file.
   1961 
   1962 #+begin_src emacs-lisp
   1963   (defun za/counsel-org-agenda-headlines--candidates-with-filename (candidates)
   1964     "Convert CANDIDATES to include source filename for each candidate."
   1965     (mapcar (lambda (candidate)
   1966               (let ((name (nth 0 candidate))
   1967                     (path (nth 1 candidate))
   1968                     (pos (nth 2 candidate)))
   1969                 (list (format "%s/%s" (file-name-nondirectory path) name)
   1970                       path
   1971                       pos)))
   1972             candidates))
   1973 
   1974   (advice-add #'counsel-org-agenda-headlines--candidates :filter-return #'za/counsel-org-agenda-headlines--candidates-with-filename)
   1975 #+end_src
   1976 
   1977 *** Processing inbox
   1978 I made a function for processing the inbox, focusing on one item at a time:
   1979 
   1980 #+begin_src emacs-lisp
   1981   (defun za/gtd-inbox-next-item ()
   1982     (interactive)
   1983     (unless (string= (buffer-file-name) (file-truename za/org-life-inbox))
   1984       (user-error "You're not in your GTD inbox file."))
   1985     (widen)
   1986     (org-first-headline-recenter)
   1987     (org-narrow-to-subtree))
   1988 #+end_src
   1989 
   1990 And a conditional binding:
   1991 
   1992 #+begin_src emacs-lisp
   1993   (bind-key "C-c g n" #'za/gtd-inbox-next-item 'org-mode-map (string= (buffer-file-name) (file-truename za/org-life-inbox)))
   1994 #+end_src
   1995 
   1996 And a function for importing other inboxes:
   1997 
   1998 #+begin_src emacs-lisp
   1999   (defun za/gtd-inbox-import ()
   2000     (interactive)
   2001     (unless (string= (buffer-file-name) (file-truename za/org-life-inbox))
   2002       (user-error "You're not in your GTD inbox file"))
   2003     (when (directory-files za/org-life-dir nil "\\.sync-conflict-")
   2004         (user-error "Sync conflicts found, please fix them"))
   2005     (let ((mobile (if (boundp 'za/org-life-inbox-mobile) (file-truename za/org-life-inbox-mobile) nil))
   2006           (calendar (if (boundp 'za/org-life-calendar-inbox) (file-truename za/org-life-calendar-inbox) nil)))
   2007       (save-mark-and-excursion
   2008         (goto-char (point-max))
   2009         (when mobile
   2010           (insert-file mobile)
   2011           (goto-char (point-max))
   2012           (write-region "" nil mobile))
   2013         (when calendar
   2014           (insert-file calendar)
   2015           (write-region "" nil calendar)
   2016           (goto-char (point-max)))
   2017         (message "Imported other inboxes."))))
   2018 #+end_src
   2019 
   2020 Also with a conditional binding:
   2021 
   2022 #+begin_src emacs-lisp
   2023   (bind-key "C-c g i" #'za/gtd-inbox-import 'org-mode-map (string= (buffer-file-name) (file-truename za/org-life-inbox)))
   2024 #+end_src
   2025 *** Refiling & archiving
   2026 #+begin_src emacs-lisp
   2027   (use-package org-refile
   2028     :ensure org
   2029     :custom
   2030     (org-refile-targets `((,za/org-life-main :maxlevel . 3)
   2031                           (,za/org-life-someday :level . 1)
   2032                           (,za/org-life-tickler :maxlevel . 3))
   2033                         "Where I want to be able to move subtrees (doesn't include inbox because I never refile to that, and the archive has its own keybining)")
   2034     (org-archive-location (concat za/org-life-archive "::datetree/")
   2035                           "I want to archive to a specific file, in a date tree")
   2036     (org-refile-use-outline-path 'file
   2037                                  "Include the destination file as an element in the path to a heading, and to use the full paths as completion targets rather than just the heading text itself")
   2038     (org-outline-path-complete-in-steps nil
   2039                                         "Tell Org that I don’t want to complete in steps; I want Org to generate all of the possible completions and present them at once (necessary for Helm/Ivy)")
   2040     (org-refile-allow-creating-parent-nodes 'confirm
   2041                                             "Allow me to tack new heading names onto the end of my outline path, and if I am asking to create new ones, make me confirm it"))
   2042 #+end_src
   2043 
   2044 *** Quick capture
   2045 Quick capture lets me send something to my inbox very quickly, without thinking about where it should go.
   2046 The inbox is processed later.
   2047 
   2048 Templates for quick capture:
   2049 
   2050 #+begin_src emacs-lisp
   2051   (use-package org-capture
   2052     :ensure org
   2053     :custom
   2054     (org-capture-templates `(("t" "Todo [inbox]" entry
   2055                               (file ,za/org-life-inbox)
   2056                               "* TODO %i%?")
   2057 
   2058                              ("s" "Save for read/watch/listen" entry
   2059                               (file+headline ,za/org-life-someday "Read/watch/listen")
   2060                               "* %?[[%^{link}][%^{description}]] %^g"))))
   2061 #+end_src
   2062 
   2063 *** Todo & custom agenda views
   2064 Todo keywords based on the GTD system (pipe separates incomplete from complete).
   2065 Apart from the logging-on-done configured [[*Logging][below]], I also want to log a note & timestamp when I start waiting on something.
   2066 In ~org-todo-keywords~, ~@~ means note+timestamp, ~!~ means timestamp, ~@/!~ means note+timestamp on state entry and timestamp on leave.
   2067 
   2068 #+begin_src emacs-lisp
   2069   (custom-set-variables '(org-todo-keywords '((sequence "TODO(t)" "NEXT(n)" "STARTED(s)" "WAITING(w@)" "PROJ(p)" "|" "DONE(d)" "CANCELLED(c)")))
   2070                         '(org-todo-keyword-faces '(("TODO" . org-todo)
   2071                                                    ("NEXT" . org-todo)
   2072                                                    ("WAITING" . org-todo)
   2073                                                    ("STARTED" . org-todo)
   2074                                                    ("PROJ" . org-todo)
   2075                                                    ("DONE" . org-done)
   2076                                                    ("CANCELLED" . org-done))))
   2077 #+end_src
   2078 
   2079 
   2080 Something is a habit if: it has a HABIT tag, STYLE is habit, LOGGING is logrepeat, it has a scheduled repeater from today.
   2081 
   2082 #+begin_src emacs-lisp
   2083   (defun za/mark-as-habit ()
   2084     "This function makes sure that the current heading has:
   2085   (1) a HABIT tag
   2086   (2) todo set to TODO
   2087   (3) LOGGING property set to logrepeat
   2088   (4) a scheduled repeater from today"
   2089     (interactive)
   2090     (org-back-to-heading t)
   2091     (org-set-property "TODO" "TODO")
   2092     (org-set-property "LOGGING" "logrepeat")
   2093     (org-set-property "STYLE" "habit")
   2094     (org-toggle-tag "HABIT" 'on)
   2095     (org-schedule nil))
   2096 #+end_src
   2097 
   2098 +I decided that projects will not be TODO items, but their progress will be tracked with a progress cookie ([x/y]). This function converts an item to a project: it adds a PROJECT tag, sets the progress indicator to count all checkboxes in sub-items (only TODO items), and removes any existing TODO keywords. Finally, PROJECT tags shouldn't be inherited (i.e. subtasks shouldn't be marked as projects).+
   2099 In the end, I want NEXT items that are part of a project to be shown as such (so inherit that PROJECT tag), but projects themselves will have a PROJ todo keyword.
   2100 This function converts an item to a project.
   2101 
   2102 #+begin_src emacs-lisp
   2103   (defun za/mark-as-project ()
   2104     "This function makes sure that the current heading has
   2105       (1) the tag PROJECT
   2106       (2) the todo keyword PROJ
   2107       (3) the property COOKIE_DATA set to \"todo recursive\"
   2108       (4) a progress indicator"
   2109     (interactive)
   2110     (org-back-to-heading t)
   2111     ;; Step 1: clear out everything
   2112     (org-set-property "TODO" "")
   2113 
   2114     ;; org-set-property errors via org-priority if you try to clear
   2115     ;; priority of an item that doesn't have priority. Stupid design,
   2116     ;; but I can't change that so we gotta jump through hoops:
   2117     (let ((have-priority (org-element-property :priority (org-element-at-point))))
   2118       (when have-priority
   2119         (org-set-property "PRIORITY" "")))
   2120 
   2121     ;; Step 2: set info (stats cookie, todo, tag, properties drawer)
   2122     (forward-whitespace 1)
   2123     (insert "[/] ")
   2124     (org-set-property "TODO" "PROJ")
   2125     (org-toggle-tag "PROJECT" 'on)
   2126     (org-set-property "COOKIE_DATA" "todo recursive")
   2127     (org-update-statistics-cookies nil))
   2128 #+end_src
   2129 
   2130 And a keybinding for it:
   2131 
   2132 #+begin_src emacs-lisp
   2133   (bind-key "C-c g p" #'za/mark-as-project 'org-mode-map)
   2134 #+end_src
   2135 
   2136 Want all tags to be inherited:
   2137 
   2138 #+begin_src emacs-lisp
   2139   (custom-set-variables '(org-tags-exclude-from-inheritance nil))
   2140 #+end_src
   2141 
   2142 Define a function to skip items if they're part of a project (i.e. one of their parents has a "PROJECT" tag).
   2143 +The problem is, the "PROJECT" tag isn't inherited. So, we temporarily disable excluding from inheritance, just for the ~org-get-tags~ call. Then check if "PROJECT" is one of the tags.+ That tag is now inherited.
   2144 
   2145 #+begin_src emacs-lisp
   2146   (defun za/skip-if-in-project ()
   2147     "Skip items that are part of a project but not a project themselves."
   2148     (let ((skip (save-excursion (org-end-of-subtree t)))
   2149           (keep nil)
   2150           (item-tags (let ((org-use-tag-inheritance t)) (org-get-tags)))
   2151           (item-tags-without-inherited (let ((org-use-tag-inheritance nil)) (org-get-tags))))
   2152       (if (and (member "PROJECT" item-tags)
   2153                (not (member "PROJECT" item-tags-without-inherited)))
   2154           skip
   2155         keep)))
   2156 #+end_src
   2157 
   2158 Also, define a function to skip tasks (trees) that are not habits (i.e. don't have the STYLE property ~habit~):
   2159 
   2160 #+begin_src emacs-lisp
   2161   (defun za/skip-unless-habit ()
   2162     "Skip trees that are not habits"
   2163     (let ((skip (save-excursion (org-end-of-subtree t)))
   2164           (keep nil))
   2165       (if (string= (org-entry-get nil "STYLE") "habit")
   2166           keep
   2167         skip)))
   2168 #+end_src
   2169 
   2170 And one to skip tasks that /are/ habits:
   2171 
   2172 #+begin_src emacs-lisp
   2173   (defun za/skip-if-habit ()
   2174     "Skip trees that are not habits"
   2175     (let ((skip (save-excursion (org-end-of-subtree t)))
   2176           (keep nil))
   2177       (if (string= (org-entry-get nil "STYLE") "habit")
   2178           skip
   2179         keep)))
   2180 #+end_src
   2181 
   2182 Skip ones with a habit tag:
   2183 
   2184 #+begin_src emacs-lisp
   2185   (defun za/skip-if-has-habit-tag ()
   2186     (let ((skip (save-excursion (org-end-of-subtree t)))
   2187           (keep nil)
   2188           (item-tags-without-inherited (let ((org-use-tag-inheritance nil)) (org-get-tags))))
   2189       (if (or (member "HABIT" item-tags-without-inherited)
   2190               (member "flatastic" item-tags-without-inherited))
   2191           skip
   2192         keep)))
   2193 #+end_src
   2194 
   2195 And another function, to skip tasks that are blocked:
   2196 
   2197 #+begin_src emacs-lisp
   2198   (defun za/skip-if-blocked ()
   2199     "Skip trees that are blocked by previous tasks"
   2200     (let ((skip (save-excursion (org-end-of-subtree t)))
   2201           (keep nil))
   2202       (if (org-entry-blocked-p)
   2203           skip
   2204         keep)))
   2205 #+end_src
   2206 
   2207 For listing tasks without a context - skip if it has a context tag:
   2208 
   2209 #+begin_src emacs-lisp
   2210   (defun za/skip-if-has-context ()
   2211     (let ((skip (save-excursion (org-end-of-subtree t)))
   2212           (keep nil)
   2213           (item-tags-without-inherited (let ((org-use-tag-inheritance nil)) (org-get-tags)))
   2214           (context-tag-p (lambda (s) (eq (aref s 0) ?@))))
   2215       (if (cl-some context-tag-p item-tags-without-inherited)
   2216           skip
   2217         keep)))
   2218 #+end_src
   2219 
   2220 For listing tasks without an energy level - skip if it has an energy level:
   2221 
   2222 #+begin_src emacs-lisp
   2223   (defun za/skip-if-has-energy-level ()
   2224     (let ((skip (save-excursion (org-end-of-subtree t)))
   2225           (keep nil)
   2226           (item-tags-without-inherited (let ((org-use-tag-inheritance nil)) (org-get-tags)))
   2227           (energy-tag-p (lambda (s) (member s '("sport" "cruise" "parked" "errand")))))
   2228       (if (cl-some energy-tag-p item-tags-without-inherited)
   2229           skip
   2230         keep)))
   2231 #+end_src
   2232 
   2233 #+begin_src emacs-lisp
   2234   (defun za/skip-if-scheduled-in-future ()
   2235     (let* ((skip (save-excursion (org-end-of-subtree t)))
   2236            (keep nil)
   2237            (scheduled-time (org-get-scheduled-time (point))))
   2238       (if (and scheduled-time (time-less-p (current-time) scheduled-time))
   2239           skip
   2240         keep)))
   2241 #+end_src
   2242 
   2243 #+begin_src emacs-lisp
   2244   (defun za/skip-if-scheduled ()
   2245     (let* ((skip (save-excursion (org-end-of-subtree t)))
   2246            (keep nil)
   2247            (scheduled-time (org-get-scheduled-time (point))))
   2248       (if scheduled-time
   2249           skip
   2250         keep)))
   2251 #+end_src
   2252 
   2253 Create custom agenda view based on those keywords.
   2254 Agenda views are made up of blocks, appearing in the order that you declare them.
   2255 The first two strings are what shows up in the agenda dispatcher (the key to press and the description).
   2256 
   2257 #+begin_src emacs-lisp
   2258   (setq org-agenda-custom-commands
   2259         '(("n" "Next actions"
   2260            todo "NEXT" ((org-agenda-overriding-header "Next actions:")
   2261                         (org-agenda-sorting-strategy '(priority-down alpha-up))
   2262                         (org-agenda-skip-function #'za/skip-if-scheduled)))
   2263           ("q" "Query" (lambda (&rest _) (call-interactively #'org-ql-search)))
   2264 
   2265           ("W" "Waiting"
   2266            ((todo "WAITING" ((org-agenda-overriding-header "Waiting:")))))
   2267           ("S" . "Saved for later...")
   2268           ("Sw" "Saved to watch"
   2269            ((tags-todo "WATCH" ((org-agenda-overriding-header "To watch:")
   2270                                 (org-agenda-files `(,za/org-life-someday ,@org-agenda-files))))))
   2271 
   2272           ("Sr" "Saved to read"
   2273            ((tags-todo "READ" ((org-agenda-overriding-header "To read:")
   2274                                (org-agenda-files `(,za/org-life-someday ,@org-agenda-files))))))
   2275           ("Sl" "Saved to listen"
   2276            ((tags-todo "LISTEN" ((org-agenda-overriding-header "To listen:")
   2277                                  (org-agenda-files `(,za/org-life-someday ,@org-agenda-files))))))
   2278 
   2279           ("a" . "Agenda with schedule only...")
   2280           ("aw" "This week"
   2281            ((agenda "" ((org-agenda-span 'week)))))
   2282           ("aD" "Today"
   2283            ((agenda "" ((org-agenda-span 'day)))))
   2284           ("ad" "Today (no habits)"
   2285            ((agenda "" ((org-agenda-span 'day)
   2286                         (org-agenda-skip-function 'za/skip-if-has-habit-tag)))))
   2287           ("at" "Tomorrow (no habits)"
   2288            ((agenda "" ((org-agenda-span 'day)
   2289                         (org-agenda-start-day "+1d")
   2290                         (org-agenda-skip-function 'za/skip-if-has-habit-tag)))))
   2291           ("aT" "Tomorrow"
   2292            ((agenda "" ((org-agenda-span 'day)
   2293                         (org-agenda-start-day "+1d")))))
   2294 
   2295           ("w" "Week Agenda + Next Actions"
   2296            ((agenda "" ((org-agenda-overriding-header "Week agenda:")))
   2297             (todo "NEXT" ((org-agenda-overriding-header "Next actions:")))))
   2298 
   2299           ("o" "Month agenda"
   2300            ((agenda "" ((org-agenda-overriding-header "Month agenda:")
   2301                         (org-agenda-span 'month)))))
   2302 
   2303           ("d" "Day Agenda + Habits graph + Waiting"
   2304            ((agenda "" ((org-agenda-overriding-header "Day:")
   2305                         (org-agenda-span 'day)
   2306                         (org-habit-show-habits nil)
   2307                         (org-agenda-skip-function 'za/skip-if-has-habit-tag)))
   2308             (todo "STARTED" ((org-agenda-overriding-header "In progress:")))
   2309             (todo "WAITING" ((org-agenda-overriding-header "Waiting:")))
   2310             (agenda "" ((org-agenda-overriding-header "Habits:")
   2311                         (org-agenda-span 'day)
   2312                         (org-agenda-use-time-grid nil)
   2313                         (org-agenda-skip-function 'za/skip-unless-habit)
   2314                         (org-habit-show-habits t) (org-habit-show-habits-only-for-today nil)
   2315                         (org-habit-show-all-today t)))))
   2316           ("D" "Day Agenda with habit tags + Habits + Waiting"
   2317            ((agenda "" ((org-agenda-overriding-header "Day:")
   2318                         (org-agenda-span 'day)
   2319                         (org-habit-show-habits nil)))
   2320             (todo "STARTED" ((org-agenda-overriding-header "In progress:")))
   2321             (todo "WAITING" ((org-agenda-overriding-header "Waiting:")))
   2322             (agenda "" ((org-agenda-overriding-header "Habits:")
   2323                         (org-agenda-span 'day)
   2324                         (org-agenda-use-time-grid nil)
   2325                         (org-agenda-skip-function 'za/skip-unless-habit)
   2326                         (org-habit-show-habits t) (org-habit-show-habits-only-for-today nil)
   2327                         (org-habit-show-all-today t)))))
   2328 
   2329 
   2330           ("k" "Kanban view"
   2331            ((todo "DONE" ((org-agenda-overriding-header "Done:") (org-agenda-sorting-strategy '(deadline-up priority-down alpha-up))))
   2332             (todo "STARTED" ((org-agenda-overriding-header "In progress:") (org-agenda-sorting-strategy '(deadline-up priority-down alpha-up))))
   2333             (todo "NEXT" ((org-agenda-overriding-header "To do:") (org-agenda-sorting-strategy '(deadline-up priority-down alpha-up))))))
   2334 
   2335           ("p" "Projects"
   2336            ((todo "PROJ" ((org-agenda-overriding-header "Projects:")
   2337                           (org-agenda-prefix-format '((todo . " %i %-22(let ((deadline (org-entry-get nil \"DEADLINE\"))) (if deadline deadline \"\"))")))
   2338                           (org-agenda-dim-blocked-tasks nil)
   2339                           (org-agenda-sorting-strategy '((todo deadline-up alpha-down)))))))
   2340           ("1" "1-3-5"
   2341            ((tags "_1" ((org-agenda-overriding-header "Big tasks:")
   2342                         (org-agenda-skip-function 'za/skip-if-scheduled-in-future)
   2343                         (org-agenda-sorting-strategy '(todo-state-down deadline-up priority-down alpha-up))))
   2344             (tags "_3" ((org-agenda-overriding-header "Medium tasks:")
   2345                         (org-agenda-skip-function 'za/skip-if-scheduled-in-future)
   2346                         (org-agenda-sorting-strategy '(todo-state-down deadline-up priority-down alpha-up))))
   2347             (tags "_5" ((org-agenda-overriding-header "Small tasks:")
   2348                         (org-agenda-skip-function 'za/skip-if-scheduled-in-future)
   2349                         (org-agenda-sorting-strategy '(todo-state-down deadline-up priority-down alpha-up))))))
   2350 
   2351           ;; Useful thread for opening calfw: https://github.com/kiwanami/emacs-calfw/issues/18
   2352           ("c" "Calendar view" (lambda (&rest _)
   2353                                  (interactive)
   2354                                  (let ((org-agenda-skip-function 'za/skip-if-habit))
   2355                                    (cfw:open-org-calendar))))
   2356           ("f" . "Find & fix...")
   2357           ("f@" "Next actions missing context"
   2358            todo "NEXT" ((org-agenda-overriding-header "Missing context:")
   2359                         (org-agenda-sorting-strategy '(priority-down alpha-up))
   2360                         (org-agenda-skip-function 'za/skip-if-has-context)))
   2361           ("fe" "Next actions missing energy"
   2362            todo "NEXT" ((org-agenda-overriding-header "Missing energy level:")
   2363                         (org-agenda-sorting-strategy '(priority-down alpha-up))
   2364                         (org-agenda-skip-function 'za/skip-if-has-energy-level)))
   2365           ("ff" "Finished tasks that aren't in a project"
   2366            ((tags "TODO=\"DONE\"|TODO=\"CANCELLED\"" ((org-agenda-overriding-header "Finished tasks:")
   2367                                                       (org-agenda-skip-function 'za/skip-if-in-project)))))
   2368           ("ft" "Tasks without a scheduled time"
   2369            alltodo "" ((org-agenda-overriding-header "Missing scheduled time:")
   2370                        (org-agenda-skip-function '(org-agenda-skip-entry-if 'scheduled 'deadline 'timestamp))))))
   2371 #+end_src
   2372 
   2373 In calfw, I don't want to show habits:
   2374 
   2375 #+begin_src emacs-lisp
   2376   (add-hook 'cfw:calendar-mode-hook (setq-local org-agenda-skip-function 'za/skip-if-habit))
   2377 #+end_src
   2378 
   2379 *** Automatically mark next project item as NEXT
   2380 Unless the current item is a project, when a project item is done, the next item in the project should be marked "NEXT".
   2381 I tried org-edna but I couldn't get it working after an hour of effort. So a bit of lisp is the easier solution.
   2382 
   2383 #+begin_src emacs-lisp
   2384   (defun za/gtd-auto-next ()
   2385     "Automatically mark project item as next."
   2386     (save-excursion
   2387       (org-back-to-heading)
   2388       (when (buffer-narrowed-p)
   2389         (widen))
   2390       (when (and (member org-state org-done-keywords)
   2391                  (not (member "PROJECT" (org-get-tags nil 'local)))
   2392                  (member "PROJECT" (let ((org-use-tag-inheritance t))
   2393                                      (org-get-tags nil))))
   2394         (when (org-goto-sibling)
   2395           (org-entry-put (point) "TODO" "NEXT")))))
   2396 
   2397   (add-hook #'org-after-todo-state-change-hook #'za/gtd-auto-next)
   2398 #+end_src
   2399 
   2400 *** Logging for tasks
   2401 I want to log into the LOGBOOK drawer (useful when I want to take quick notes):
   2402 
   2403 #+begin_src emacs-lisp
   2404   (setq org-log-into-drawer "LOGBOOK")
   2405 #+end_src
   2406 
   2407 I also want to log when I finish a task (useful for archiving).
   2408 Furthermore, when I'm done, I want to add a note (any important
   2409 workarounds/tips). And when I reschedule, I want to know the reason.
   2410 I can disable logging on state change for a specific task by adding ~:LOGGING: nil~ to the ~:PROPERTIES:~ drawer.
   2411 
   2412 #+begin_src emacs-lisp
   2413   (setq org-log-done 'time
   2414         org-log-reschedule 'note)
   2415 #+end_src
   2416 
   2417 I want to hide drawers on startup. This variable has options:
   2418 - 'overview': Top-level headlines only.
   2419 - 'content': All headlines.
   2420 - 'showall': No folding on any entry.
   2421 - 'show2levels: Headline levels 1-2.
   2422 - 'show3levels: Headline levels 1-3.
   2423 - 'show4levels: Headline levels 1-4.
   2424 - 'show5levels: Headline levels 1-5.
   2425 - 'showeverything: Show even drawer contents.
   2426 
   2427 #+begin_src emacs-lisp
   2428   (setq org-startup-folded 'content)
   2429 #+end_src
   2430 
   2431 *** Task ordering
   2432 Some tasks should be ordered, i.e. they should be done in steps.
   2433 Those have the ~:ORDERED: t~ setting in ~:PROPERTIES:~, and it should be enforced:
   2434 
   2435 #+begin_src emacs-lisp
   2436   (setq org-enforce-todo-dependencies t)
   2437 #+end_src
   2438 
   2439 Furthermore, tasks that are ordered and can't be done yet because of previous steps should be dimmed in the agenda:
   2440 
   2441 #+begin_src emacs-lisp
   2442   (setq org-agenda-dim-blocked-tasks t)
   2443 #+end_src
   2444 
   2445 I might also want to set ~org-enforce-todo-checkbox-dependencies~, but not convinced on that one yet.
   2446 
   2447 *** Time tracking & effort
   2448 Time tracking should be done in its own drawer:
   2449 
   2450 #+begin_src emacs-lisp
   2451   (setq org-clock-into-drawer "CLOCK")
   2452 #+end_src
   2453 
   2454 And to customize how clock tables work:
   2455 
   2456 #+begin_src emacs-lisp
   2457   (setq org-clocktable-defaults '(:lang "en" :scope agenda-with-archives  :wstart 1 :mstart 1 :compact t :maxlevel nil))
   2458   (setq org-agenda-clockreport-parameter-plist '(:link t :maxlevel nil))
   2459 #+end_src
   2460 
   2461 I want to set effort in hours:minutes:
   2462 
   2463 #+begin_src emacs-lisp
   2464   (add-to-list 'org-global-properties '("Effort_ALL" . "0:05 0:10 0:15 0:20 0:30 0:45 1:00 1:30 2:00 4:00 6:00 8:00"))
   2465 #+end_src
   2466 
   2467 I want column view to look like this:
   2468 
   2469 | To do        | Task      | Tags | Sum of time elapsed | Sum of time estimated (effort) |
   2470 |--------------+-----------+------+---------------------+--------------------------------|
   2471 | todo keyword | task name | tags | sum of clock        | sum of estimated time          |
   2472 | ...          | ...       | ...  | ...                 | ...                            |
   2473 
   2474 #+begin_src emacs-lisp
   2475   (setq org-columns-default-format "%7TODO (To Do) %32ITEM(Task) %TAGS(Tags) %11CLOCKSUM_T(Clock) %10Difficulty(Difficulty) %8Effort(Effort){:}")
   2476 #+end_src
   2477 
   2478 Fix column alignment in agenda.
   2479 
   2480 #+begin_src emacs-lisp
   2481   (set-face-attribute 'org-column nil
   2482                       :height (face-attribute 'default :height)
   2483                       :family (face-attribute 'default :family))
   2484   (set-face-attribute 'org-agenda-date-today nil
   2485                       :height (face-attribute 'default :height))
   2486 #+end_src
   2487 
   2488 *** Calculate time since timestamp
   2489 #+begin_src emacs-lisp
   2490   (defun za/org-time-since ()
   2491     "Print the amount of time between the timestamp at point and the current date and time."
   2492     (interactive)
   2493     (unless (org-at-timestamp-p 'lax)
   2494       (user-error "Not at timestamp"))
   2495 
   2496     (when (org-at-timestamp-p 'lax)
   2497       (let ((timestamp (match-string 0)))
   2498         (with-temp-buffer
   2499           (insert timestamp
   2500                   "--"
   2501                   (org-time-stamp '(16)))
   2502           (org-evaluate-time-range)))))
   2503 #+end_src
   2504 
   2505 Also a method to add overlays with that timestamp:
   2506 
   2507 #+begin_src emacs-lisp
   2508   (defvar-local za/org-timestamp-overlays--list nil "Buffer-local list of overlays with timestamps")
   2509   (defvar-local za/org-timestamp-overlays--show nil "Buffer-local boolean to show overlays.")
   2510   (defun za/org-timestamp-overlays-clear ()
   2511     "Clear all overlays with timestamps in current buffer."
   2512     (dolist (ov za/org-timestamp-overlays--list)
   2513       (delete-overlay ov))
   2514     (setq-local za/org-timestamp-overlays--list nil))
   2515 
   2516   (defun za/org-timestamp-overlays-add ()
   2517     "Add overlays for active timestamps in current buffer."
   2518     (let ((markup-string (lambda (s) (propertize (format "{%s}" s)
   2519                                                  'face 'org-habit-ready-future-face))))
   2520       (save-excursion
   2521         (let* ((beg (point-min))
   2522                (end (point-max)))
   2523           (goto-char beg)
   2524           (while (re-search-forward (org-re-timestamp 'active) end t)
   2525             (let ((ov (make-overlay (point) (point))))
   2526               (overlay-put ov 'before-string (funcall markup-string (za/org-time-since)))
   2527               (add-to-list 'za/org-timestamp-overlays--list ov)))))))
   2528 
   2529   (defun za/org-timestamp-overlays-redraw ()
   2530     "Redraw all overlays for active timestamps."
   2531     (za/org-timestamp-overlays-clear)
   2532     (za/org-timestamp-overlays-add))
   2533 
   2534   (defun za/org-timestamp-hook-fn (&rest _)
   2535     (za/org-timestamp-overlays-redraw))
   2536 
   2537   (bind-key "C-c q p" #'tmp/p)
   2538   (defun za/org-timestamp-overlays-toggle (&optional prefix)
   2539     "With no prefix, toggle showing timestamp overlay.
   2540   With PREFIX = 0, redraw overlays.
   2541   With PREFIX > 0, show overlays.
   2542   With PREFIX < 0, hide overlays."
   2543     (interactive "P")
   2544     (let ((overlays-hide (lambda ()
   2545                            (za/org-timestamp-overlays-clear)
   2546                            (remove-hook 'org-cycle-hook #'za/org-timestamp-hook-fn)
   2547                            (setq za/org-timestamp-overlays--show nil)
   2548                            (message "Overlays hidden.")))
   2549           (overlays-show (lambda ()
   2550                            (za/org-timestamp-overlays-redraw)
   2551                            (add-hook 'org-cycle-hook #'za/org-timestamp-hook-fn)
   2552                            (setq za/org-timestamp-overlays--show t)
   2553                            (message "Overlays showing.")))
   2554           (overlays-redraw-maybe (lambda ()
   2555                                    (when za/org-timestamp-overlays--show
   2556                                      (za/org-timestamp-overlays-redraw)
   2557                                      (message "Redrawing overlays."))))
   2558           (prefix-num (prefix-numeric-value prefix)))
   2559       (cond ((not prefix)
   2560              (cond (za/org-timestamp-overlays--show
   2561                     (funcall overlays-hide))
   2562                    (t
   2563                     (funcall overlays-show))))
   2564             ((zerop prefix-num)
   2565              )
   2566             ((> prefix-num 0)
   2567              (funcall overlays-show))
   2568             ((< prefix-num 0)
   2569              (funcall overlays-hide)))))
   2570 
   2571 #+end_src
   2572 
   2573 Bind a key:
   2574 
   2575 #+begin_src emacs-lisp
   2576   (bind-key "C-c q d" #'za/org-timestamp-overlays-toggle 'org-mode-map)
   2577   (bind-key "C-c q d" #'za/org-timestamp-overlays-toggle 'org-agenda-mode-map)
   2578 #+end_src
   2579 *** Priorities: how important something is
   2580 I usually have a lot of 'next' actions, so I prefer 4 priority levels instead of the default 3: A (urgent, ASAP), B (important),  C (if you have nothing else, do this), D (do in free time):
   2581 
   2582 #+begin_src emacs-lisp
   2583   (setq org-priority-highest ?A
   2584         org-priority-lowest ?D
   2585         org-priority-default ?C)
   2586 #+end_src
   2587 
   2588 Faces for priorities in agenda:
   2589 
   2590 #+begin_src emacs-lisp
   2591   (setq org-priority-faces `((?A . (:foreground ,(face-foreground 'error)))
   2592                              (?B . (:foreground ,(face-foreground 'org-todo)))
   2593                              (?C . (:foreground ,(face-foreground 'font-lock-constant-face) :weight semi-light))
   2594                              (?D . (:foreground ,(face-foreground 'font-lock-string-face) :slant italic :weight light))))
   2595 #+end_src
   2596 
   2597 And to be able to bulk-set priorities in agenda:
   2598 
   2599 #+begin_src emacs-lisp
   2600   (setq org-agenda-bulk-custom-functions '((?P (lambda nil (org-agenda-priority 'set)))))
   2601 #+end_src
   2602 *** Energy requirement: how difficult something is
   2603 #+begin_src emacs-lisp
   2604   (add-to-list 'org-global-properties '("Difficulty_ALL" . "low medium high"))
   2605 #+end_src
   2606 *** Org export backends
   2607 #+begin_src emacs-lisp
   2608   (use-package ox-pandoc)
   2609 #+end_src
   2610 
   2611 *** org publishing
   2612 I decided, after trying many different things, to settle on org-publish.
   2613 
   2614 #+begin_src emacs-lisp
   2615   (defconst za/org-roam-top-name "Top" "The name of the top-level Org-roam node.")
   2616   (defun za/org-roam-sitemap-function (title list)
   2617     "Customized function to generate sitemap for org-roam, almost the same as `org-publish-sitemap-default`."
   2618     (concat "#+TITLE: " title "\n\n"
   2619             (format "[[file:%s][%s]]\n\n"
   2620                     (file-name-nondirectory (org-roam-node-file
   2621                                              (org-roam-node-from-title-or-alias za/org-roam-top-name)))
   2622                     "Click here for entrypoint.")))
   2623   ;; (org-list-to-org list)))  <-- this is taken care of by Zola
   2624 
   2625 #+end_src
   2626 
   2627 To make this work with Zola, I need to export Github-flavored markdown (fenced code blocks with language):
   2628 
   2629 #+begin_src emacs-lisp
   2630   (require 'ox-publish)
   2631   (require 'ox-md)
   2632 
   2633   (use-package ox-gfm
   2634     :init
   2635     (with-eval-after-load 'org (require 'ox-gfm)))
   2636 #+end_src
   2637 
   2638 First difficulty: Zola needs front matter with ~+++...+++~.
   2639 The default Markdown backend doesn't provide that, so need to customize it by advising the default ~org-md-template~.
   2640 
   2641 #+begin_src emacs-lisp
   2642   (defun za/org-md-template-zola (contents info)
   2643     "Markdown template compatible with Zola (generates the necessary front matter from CONTENTS and INFO)."
   2644     (let ((title (org-md-plain-text (org-element-interpret-data (plist-get info :title)) info)))
   2645       (concat "+++\n"
   2646               (format "title = \"%s\"\n" (string-replace "\"" "'" title))
   2647 
   2648               ;; If the note contains a math org-roam tag
   2649               (when (member "math" (plist-get info :filetags))
   2650                 "template = \"page-math.html\"\n")
   2651 
   2652               "+++\n"
   2653               (format "# %s\n" title)
   2654               contents)))
   2655 #+end_src
   2656 
   2657 Second difficulty: links need to be reformatted and changed for static data (like images).
   2658 This function filters the return value of ~org-md-link~.
   2659 
   2660 #+begin_src emacs-lisp
   2661   (defun za/org-md-link-zola (linkstr)
   2662     "A filter function for the return value of
   2663           `org-md-link` (LINKSTR) to generate a link compatible with Zola."
   2664     (cond ((string-match-p (rx ".md") linkstr)
   2665            (string-replace "](" "](@/org-roam/" linkstr))
   2666           ((string-match-p (rx "](" (? (* alnum) "://") "/") linkstr)
   2667            (replace-regexp-in-string (rx "](" (? (* alnum) "://") "/" (* any) "/org-roam/data") "](/org-roam-data" linkstr))
   2668           (t linkstr)))
   2669 #+end_src
   2670 
   2671 A wrapper to set the right image link:
   2672 
   2673 #+begin_src emacs-lisp
   2674   (defun za/org-html--format-image (args)
   2675     "Modify source image link to work with my Org roam setup"
   2676     (let ((source (nth 0 args))
   2677           (_attributes (nth 1 args))
   2678           (_info (nth 2 args)))
   2679       (list (replace-regexp-in-string (rx bos "data/") "/org-roam-data/" source)
   2680             _attributes
   2681             _info)))
   2682 #+end_src
   2683 
   2684 And here's the custom publish function that adds/removes the necessary advice:
   2685 
   2686 #+begin_src emacs-lisp
   2687   (defun za/org-gfm-publish-to-gfm-zola (plist filename pub-dir)
   2688     "Run `org-gfm-publish-to-gfm`, advising the necessary
   2689   functions to generate Zola-compatible markdown."
   2690     (let* ((org-export-output-file-name-locked (lambda (extension &rest _)
   2691                                                  (concat (plist-get plist :publishing-directory)
   2692                                                          "locked-"
   2693                                                          (file-name-base filename)
   2694                                                          extension)))
   2695            (node (car (seq-filter
   2696                        (lambda (node) (file-equal-p (org-roam-node-file node) filename))
   2697                        (org-roam-node-list))))
   2698            (locked-p (cond ((file-equal-p filename
   2699                                           (file-name-concat (plist-get plist :base-directory) (plist-get plist :sitemap-filename)))
   2700                             nil)
   2701                            (t
   2702                             (member "locked" (org-roam-node-tags node)))))
   2703            (advice '((org-gfm-inner-template :override za/org-md-template-zola)
   2704                      (org-md-link :filter-return za/org-md-link-zola)
   2705                      (org-html--format-image :filter-args za/org-html--format-image)
   2706                      (org-gfm-table :override org-md--convert-to-html)))) ; Zola uses CommonMark, so doesn't support Markdown tables
   2707 
   2708       (dolist (orig-type-new advice) (apply #'advice-add orig-type-new))
   2709       (unwind-protect
   2710           (cond (locked-p
   2711                  (advice-add #'org-export-output-file-name :override org-export-output-file-name-locked)
   2712                  (unwind-protect
   2713                      (org-gfm-publish-to-gfm plist filename pub-dir)
   2714                    (advice-remove #'org-export-output-file-name org-export-output-file-name-locked)))
   2715                 (t
   2716                  (org-gfm-publish-to-gfm plist filename pub-dir)))
   2717         (dolist (orig-type-new advice)
   2718           (advice-remove (nth 0 orig-type-new)
   2719                          (nth 2 orig-type-new))))))
   2720 #+end_src
   2721 
   2722 Finally, the list of things we can publish with their respective publishin functions:
   2723 
   2724 #+begin_src emacs-lisp
   2725   (if (boundp 'za/my-website-dir)
   2726       (setq org-publish-project-alist
   2727             `(
   2728               ("org-notes"
   2729                :base-directory ,za/org-roam-dir
   2730                :base-extension "org"
   2731                :publishing-directory ,(concat za/my-website-dir "content/org-roam/")
   2732                :publishing-function za/org-gfm-publish-to-gfm-zola
   2733                :recursive t
   2734                :sitemap-filename "_index.md"
   2735                :sitemap-title "Org Roam"
   2736                :sitemap-function za/org-roam-sitemap-function
   2737                :auto-sitemap t)
   2738 
   2739               ("org-notes-data"
   2740                :base-directory ,(concat za/org-roam-dir "/data")
   2741                :base-extension any
   2742                :publishing-directory ,(concat za/my-website-dir "static/org-roam-data/")
   2743                :recursive t
   2744                :publishing-function org-publish-attachment)
   2745 
   2746               ("org-roam" :components ("org-notes" "org-notes-data"))))
   2747     (warn "za/my-website-dir not bound, not setting org publishing targets."))
   2748 #+end_src
   2749 
   2750 And a function to rsync to my VPS:
   2751 
   2752 #+begin_src emacs-lisp
   2753   (defun za/publish-upload-to-website ()
   2754     "Upload my website to my VPS"
   2755     (interactive)
   2756     (async-shell-command (format "cd %s && zola build && yes|publish" za/my-website-dir) "*Async Shell publish*"))
   2757 #+end_src
   2758 *** Rebuild org cache
   2759 
   2760 #+begin_src emacs-lisp
   2761   (defun za/force-org-rebuild-cache ()
   2762     "Rebuild the `org-mode' and `org-roam' cache."
   2763     (interactive)
   2764     (org-id-update-id-locations)
   2765     ;; Note: you may need `org-roam-db-clear-all'
   2766     ;; followed by `org-roam-db-sync'
   2767     (org-roam-db-sync)
   2768     (org-roam-update-org-id-locations))
   2769 #+end_src
   2770 *** Sync with Flatastic
   2771 API work is handled via an external ruby script.
   2772 
   2773 #+begin_src emacs-lisp
   2774   (defun za/org-flatastic-sync-tasks ()
   2775     "Add tasks from flatastic to inbox"
   2776     (interactive)
   2777     (unless (json-available-p)
   2778       (user-error "JSON not available"))
   2779     (unless (boundp 'za/org-life-inbox)
   2780       (user-error "Please set za/org-life-inbox"))
   2781     (let* ((api-data (json-parse-string
   2782                       (progn
   2783                         (require 'exec-path-from-shell)
   2784                         (exec-path-from-shell-copy-envs
   2785                          '("FLATASTIC_API_KEY" "FLATASTIC_USER_ID"))
   2786                         (shell-command-to-string "~/.local/share/rbenv/shims/ruby ~/.scripts/flatastic.rb"))
   2787                       :object-type 'alist))
   2788            (format-data-as-org (lambda (l)
   2789                                  (format "* TODO %s :flatastic:\n  SCHEDULED: <%s>\n  Points: %d\n"
   2790                                          (alist-get 'description l)
   2791                                          (alist-get 'scheduled_due_date l)
   2792                                          (alist-get 'point_value l))))
   2793            (org-flatastic-items (mapcar format-data-as-org api-data)))
   2794       (with-current-buffer (find-file-noselect za/org-life-inbox)
   2795         (goto-char (point-max))
   2796         (insert "\n" (string-join org-flatastic-items "\n")))
   2797       (message "Synced %d Flatastic tasks to inbox" (length api-data))))
   2798 #+end_src
   2799 *** Link to Thunderbird messages
   2800 Create a custom link to open thunderbird emails by ID:
   2801 
   2802 #+begin_src emacs-lisp
   2803   (org-link-set-parameters
   2804    "thunderbird"
   2805    :follow #'za/org-link-thunderbird-follow)
   2806 
   2807   (defun za/org-link-thunderbird-follow (messageid)
   2808     "Open the message with id `messageid` in Thunderbird"
   2809     (shell-command (format "thunderbird mid:%s" (shell-quote-argument messageid))))
   2810 #+end_src
   2811 *** Inverse refile
   2812 #+begin_src emacs-lisp
   2813   (defun za/org-refile-to-point (refloc)
   2814     "Prompt for a heading and refile it to point."
   2815     (interactive (list (org-refile-get-location "Heading: ")))
   2816     (let* ((file (nth 1 refloc))
   2817            (pos (nth 3 refloc)))
   2818       (save-excursion
   2819         (with-current-buffer (find-file-noselect file 'noward)
   2820           (save-excursion
   2821             (save-restriction
   2822               (widen)
   2823               (goto-char pos)
   2824               (org-copy-subtree 1 t))))
   2825         (org-paste-subtree nil nil nil t))))
   2826 
   2827 
   2828   (defun za/org-refile-wrapper (arg)
   2829     "Wrap org-refile so that it does the inverse with a negative argument"
   2830     (interactive "P")
   2831     (if (minusp (prefix-numeric-value arg))
   2832         (call-interactively #'za/org-refile-to-point)
   2833       (org-refile arg)))
   2834 
   2835 #+end_src
   2836 
   2837 *** org-caldav
   2838 This lets me sync my Org agenda to my CalDAV server.
   2839 The main reason is because Orgzly doesn't have a calendar view and can't (yet) search for events on a specific day, so if someone asks "are you free on that day", it's a bit hard for me to answer if I don't have my computer with me.
   2840 This way, I can just check my calendar.
   2841 
   2842 #+begin_src emacs-lisp
   2843   (if (and (boundp 'za/caldav-url)
   2844            (boundp 'za/caldav-org-calendar-id)
   2845            (boundp 'za/org-life-calendar-inbox))
   2846       (use-package org-caldav
   2847         :init
   2848         (defconst za/org-life-calendar-inbox (concat za/org-life-dir "calendar-inbox.org"))
   2849         :custom
   2850         (org-caldav-url za/caldav-url)
   2851         (org-caldav-calendar-id za/caldav-org-calendar-id)
   2852         (org-caldav-inbox za/org-life-calendar-inbox)
   2853         (org-caldav-files (cons (car (split-string org-archive-location "::")) org-agenda-files))
   2854         (org-caldav-sync-todo nil)
   2855         (org-icalendar-include-todo nil)
   2856         (org-icalendar-use-deadline '(event-if-todo event-if-not-todo todo-due))
   2857         (org-icalendar-use-scheduled '(todo-start event-if-todo event-if-not-todo))
   2858         (org-caldav-exclude-tags '("HABIT")
   2859                                  "I don't want to export habits, because those will just clutter up my calendar. The calendar is supposed to be for one-off stuff, or rarely repeating stuff. Yes, I have to manually add the HABIT tag to every habit. Perhaps nicer would be to exclude based on the property ~:STYLE: habit~, but I haven't figured that one out yet.")
   2860         (org-caldav-todo-percent-states '((0 "TODO")
   2861                                           (0 "WAITING")
   2862                                           (1 "NEXT")
   2863                                           (2 "STARTED")
   2864                                           (0 "PROJ")
   2865                                           (100 "DONE")
   2866                                           (100 "CANCELLED")))
   2867         :config
   2868         (defun za/caldav-after-sync-notify () (za/notify "org-caldav sync complete" "Finished syncing"))
   2869         (advice-add #'org-caldav-sync :after #'za/caldav-after-sync-notify)
   2870         (advice-add #'org-caldav-sync :around #'za/notify-on-interactivity))
   2871     (warn "za/caldav-url, za/caldav-org-calendar-id, za/org-life-calendar-inbox not bound, not using org-caldav."))
   2872 #+end_src
   2873 
   2874 Maybe check [[https://old.reddit.com/r/orgmode/comments/8rl8ep/making_orgcaldav_useable/e0sb5j0/][this]] for a way to sync on save.
   2875 
   2876 *** org-ref
   2877 #+begin_src emacs-lisp
   2878   (use-package org-ref)
   2879 #+end_src
   2880 *** org-roam
   2881 #+begin_src emacs-lisp
   2882   (use-package org-roam
   2883     :custom
   2884     (org-roam-directory za/org-roam-dir)
   2885     (org-roam-completion-everywhere t)
   2886     (org-roam-dailies-capture-templates
   2887      '(("d" "default" entry
   2888         "* %U\n%?"
   2889         :target (file+head "%<%Y-%m-%d>.org"
   2890                            "#+title: %<%Y-%m-%d>\n"))))
   2891     :config
   2892                                           ; can't use nil because org-roam-ui checks for boundp on this and
   2893                                           ; errors if bound but nil.
   2894     (with-eval-after-load 'org-roam-dailies
   2895       (makunbound 'org-roam-dailies-directory))
   2896     (defun za/org-roam-dailies-goto-latest-note ()
   2897       (interactive)
   2898       (unless (boundp 'org-roam-dailies-directory)
   2899         (za/org-roam-dailies-select-dir))
   2900       (let* ((dailies (org-roam-dailies--list-files))
   2901              (latest-note (car (last dailies))))
   2902         (unless latest-note
   2903           (user-error "Can't find latest note"))
   2904         (find-file latest-note)
   2905         (run-hooks 'org-roam-dailies-find-file-hook)))
   2906     (org-roam-setup)
   2907     (bind-keys :prefix "C-c w"
   2908                :prefix-map za/org-roam-map
   2909                :prefix-docstring "Org roam"
   2910                ("n" . org-roam-capture)
   2911                ("f" . org-roam-node-find)
   2912                ("w" . org-roam-buffer-toggle)
   2913                ("i" . org-roam-node-insert))
   2914     (bind-keys :prefix "C-c j"
   2915                :prefix-map za/org-roam-dailies-map
   2916                :prefix-docstring "Org roam dailies"
   2917                ("s" . za/org-roam-dailies-select-dir)
   2918                ("n" . org-roam-dailies-capture-today)
   2919                ("j" . org-roam-dailies-goto-today)
   2920                ("+" . org-roam-dailies-goto-tomorrow)
   2921                (">" . org-roam-dailies-goto-next-note)
   2922                ("-" . org-roam-dailies-goto-yesterday)
   2923                ("<" . org-roam-dailies-goto-previous-note)
   2924                ("g" . org-roam-dailies-goto-date)
   2925                ("l" . za/org-roam-dailies-goto-latest-note)
   2926                ("." . org-roam-dailies-find-directory))
   2927 
   2928     (defun za/org-roam-dailies--daily-note-p (&optional file)
   2929       "Replacement of default function. Return t if FILE is an Org-roam daily-note, nil otherwise.
   2930   If FILE is not specified, use the current buffer's file-path."
   2931       (when-let ((path (expand-file-name
   2932                         (or file
   2933                             (buffer-file-name (buffer-base-buffer)))))
   2934                  (directory (expand-file-name org-roam-dailies-directory org-roam-directory)))
   2935         (setq path (expand-file-name path))
   2936         (save-match-data
   2937           (and
   2938            ;; (org-roam-file-p path) ; don't want this, dailies might not be in org-roam path
   2939            (org-roam-descendant-of-p path directory)))))
   2940     (advice-add #'org-roam-dailies--daily-note-p :override #'za/org-roam-dailies--daily-note-p)
   2941 
   2942     (defun za/org-roam-dailies-select-dir ()
   2943       "Select an org-roam-dailies folder."
   2944       (interactive)
   2945       (let* ((choices (cons '(?0 nil) za/org-roam-dailies-dirs))
   2946              (choice (nth 1 (read-multiple-choice "org-roam-dailies dir" choices))))
   2947         (if choice
   2948             (progn (setq org-roam-dailies-directory choice)
   2949                    (message "Selected org-roam-dailies directory: %s" org-roam-dailies-directory))
   2950           (makunbound 'org-roam-dailies-directory))))
   2951 
   2952     (defun za/org-roam-dailies-calendar-mark-entries-p ()
   2953       "Only mark dailies entries in calendar if a dailies directory is set."
   2954       (boundp 'org-roam-dailies-directory))
   2955     (advice-add #'org-roam-dailies-calendar-mark-entries :before-while #'za/org-roam-dailies-calendar-mark-entries-p)
   2956 
   2957     ;; Before doing anything journal-related, check that a journal is
   2958     ;; selected, or prompt for one.
   2959     (defun za/org-roam-dailies--capture-check-non-nil-dailies-dir (&rest _)
   2960       (unless (boundp 'org-roam-dailies-directory)
   2961         (za/org-roam-dailies-select-dir))
   2962       (unless (boundp 'org-roam-dailies-directory)
   2963         (user-error "No org-roam-dailies-directory selected!")))
   2964 
   2965     (advice-add #'org-roam-dailies--capture :before #'za/org-roam-dailies--capture-check-non-nil-dailies-dir)
   2966     (advice-add #'org-roam-dailies-goto-date :before #'za/org-roam-dailies--capture-check-non-nil-dailies-dir)
   2967     (require 'org-roam-export))
   2968 #+end_src
   2969 
   2970 *** org-roam-ui
   2971 #+begin_src emacs-lisp
   2972   (use-package org-roam-ui)
   2973 #+end_src
   2974 *** org-download
   2975 Drag-and-drop images to Emacs Org mode.
   2976 
   2977 #+begin_src emacs-lisp
   2978   (use-package org-download
   2979     :custom
   2980     (org-download-method 'attach)
   2981     (org-download-backend t))
   2982 #+end_src
   2983 
   2984 *** org-sticky-header
   2985 Displays in the header-line the Org heading for the node that’s at the top of the window.
   2986 
   2987 #+begin_src emacs-lisp
   2988   (use-package org-sticky-header)
   2989 #+end_src
   2990 *** org-timestone
   2991 #+begin_src emacs-lisp
   2992   (use-package org-timestone
   2993     :init (za/package-vc-install :repo "thezeroalpha/org-timestone.el")
   2994     :ensure nil
   2995     :after org
   2996     :bind (:map org-mode-map
   2997                 ("C-c C-t" . org-timestone-org-todo-wrapper)))
   2998 #+end_src
   2999 *** org-noter
   3000 #+begin_src emacs-lisp
   3001   (use-package org-noter
   3002     :config
   3003     ;; Fix disabling of line wrap by no-opping set-notes-scroll
   3004     (advice-add 'org-noter--set-notes-scroll :override 'za/no-op))
   3005 #+end_src
   3006 *** el-easydraw
   3007 Lets you draw stuff in org mode documents.
   3008 
   3009 #+begin_src emacs-lisp :tangle no
   3010   (za/package-vc-install :repo "misohena/el-easydraw" :name "edraw")
   3011   (with-eval-after-load 'org
   3012     (require 'edraw-org)
   3013     (edraw-org-setup-default)
   3014     (bind-key "C-c q c" #'edraw-color-picker-insert-color))
   3015 #+end_src
   3016 *** ox-jira
   3017 #+begin_src emacs-lisp
   3018   (use-package ox-jira)
   3019 #+end_src
   3020 *** org-confluence
   3021 ox-confluence with some custom code to remove the theme & create expandable drawers.
   3022 Add to confluence by pressing ~ctrl + shift + d~ when editing a page and inserting confluence wiki text.
   3023 
   3024 #+begin_src emacs-lisp
   3025   (require 'ox-confluence)
   3026   (org-export-define-derived-backend 'confluence-ext 'confluence
   3027     :translate-alist '((drawer . za/org-confluence-drawer))
   3028     :filters-alist '((:filter-src-block . za/org-confluence--code-block-remove-theme))
   3029     :menu-entry
   3030     '(?F "Export to Confluence (ext)"
   3031          ((?F "As Confluence buffer (ext)" za/org-confluence-export-as-confluence))))
   3032 
   3033   (defun za/org-confluence-export-as-confluence
   3034       (&optional async subtreep visible-only body-only ext-plist)
   3035     (interactive)
   3036     (org-export-to-buffer 'confluence-ext "*org CONFLUENCE Export*"
   3037       async subtreep visible-only body-only ext-plist (lambda () (text-mode))))
   3038 
   3039   (defun za/org-confluence--code-block-remove-theme (block _backend _info)
   3040     "Remove the theme from the block"
   3041     (replace-regexp-in-string (rx "\{code:theme=Emacs" (? "|")) "\{code:" block))
   3042 
   3043 
   3044   (defun za/org-confluence-drawer (drawer contents info)
   3045     "Handle custom drawers"
   3046     (let* ((name (org-element-property :drawer-name drawer)))
   3047       (concat
   3048        (format "\{expand:%s\}\n" name)
   3049        contents
   3050        "\{expand\}")))
   3051 #+end_src
   3052 *** TODO the path for org-roam export and data export should be configurable, not hard-coded
   3053 ** Mail mode for neomutt
   3054 When editing a message from neomutt, I want to use mail mode.
   3055 Even though I won't be sending the email from there, I like the syntax highlighting :)
   3056 
   3057 #+begin_src emacs-lisp
   3058   (add-to-list 'auto-mode-alist '("/neomutt-" . mail-mode))
   3059 #+end_src
   3060 ** DISABLED Semantic mode
   3061 Disabled for now, don't use it much.
   3062 SemanticDB is written into ~/.emacs.d/semanticdb/.
   3063 
   3064 #+begin_src emacs-lisp :tangle no
   3065   (use-package semantic
   3066     :bind (:map semantic-mode-map
   3067                 ("C-c , ." . semantic-ia-show-summary))
   3068     :custom
   3069     (semantic-default-submodes '(global-semantic-idle-scheduler-mode ; reparse buffer when idle
   3070                                  global-semanticdb-minor-mode ; maintain database
   3071                                  global-semantic-idle-summary-mode  ; show information (e.g. types) about tag at point
   3072                                  global-semantic-stickyfunc-mode))) ; show current func in header line
   3073 
   3074 
   3075 #+end_src
   3076 
   3077 ** Bib(la)tex
   3078 #+begin_src emacs-lisp
   3079   (use-package bibtex
   3080     :config
   3081     (bibtex-set-dialect "biblatex"))
   3082 #+end_src
   3083 
   3084 ** Python
   3085 In Python, I want to enable flycheck and semantic mode:
   3086 
   3087 #+begin_src emacs-lisp
   3088   (add-hook 'python-mode-hook #'flycheck-mode)
   3089   ;;(add-hook 'python-mode-hook #'semantic-mode)
   3090 #+end_src
   3091 
   3092 ** Elisp
   3093 #+begin_src emacs-lisp
   3094   (use-package emacs-lisp
   3095     :ensure nil ; preinstalled
   3096     :hook ((emacs-lisp-mode . flycheck-mode)
   3097            (emacs-lisp-mode . rainbow-mode)
   3098            (emacs-lisp-mode . outline-minor-mode)
   3099            (emacs-lisp-mode . company-mode)))
   3100 #+end_src
   3101 ** lean-mode
   3102 Specifically for the Lean prover.
   3103 I also install company-lean and helm-lean, which are suggested on the [[https://github.com/leanprover/lean-mode][Github page]].
   3104 Then I map company-complete only for lean-mode.
   3105 
   3106 #+begin_src emacs-lisp
   3107   (use-package lean-mode
   3108     :config
   3109     (use-package company-lean)
   3110     :bind (:map lean-mode-map
   3111                 ("S-SPC" . company-complete)))
   3112 #+end_src
   3113 
   3114 ** sh-mode
   3115 #+begin_src emacs-lisp :results value
   3116   (use-package sh-script
   3117     :hook (sh-mode . flycheck-mode))
   3118 #+end_src
   3119 
   3120 ** anki-editor
   3121 Some extra keybindings that are not set up by default.
   3122 anki-editor doesn't provide a keymap so I have to set one up here:
   3123 
   3124 #+begin_src emacs-lisp
   3125   (use-package anki-editor
   3126     :init
   3127     (defvar anki-editor-mode-map (make-sparse-keymap))
   3128     (add-to-list 'minor-mode-map-alist (cons 'anki-editor-mode
   3129                                              anki-editor-mode-map))
   3130     :custom
   3131     (anki-editor-use-math-jax t)
   3132 
   3133     :bind (:map anki-editor-mode-map
   3134                 ("C-c t" . org-property-next-allowed-value)
   3135                 ("C-c i" . anki-editor-insert-note)
   3136                 ("C-c p" . anki-editor-push-notes)
   3137                 ("C-c c" . anki-editor-cloze-dwim)))
   3138 #+end_src
   3139 ** pdf-tools
   3140 A better replacement for DocView:
   3141 
   3142 #+begin_src emacs-lisp
   3143   (use-package pdf-tools
   3144     :init
   3145     (pdf-tools-install)
   3146 
   3147     :custom
   3148     (pdf-annot-default-annotation-properties '((t
   3149                                                 (label . "Alex Balgavy"))
   3150                                                (text
   3151                                                 (icon . "Note")
   3152                                                 (color . "#0088ff"))
   3153                                                (highlight
   3154                                                 (color . "yellow"))
   3155                                                (squiggly
   3156                                                 (color . "orange"))
   3157                                                (strike-out
   3158                                                 (color . "red"))
   3159                                                (underline
   3160                                                 (color . "blue"))))
   3161     :bind (:map pdf-isearch-minor-mode-map
   3162                 ("C-s" . isearch-forward)
   3163                 :map pdf-view-mode-map
   3164                 ;; Save position & jump back
   3165                 ("C-SPC" . (lambda () (interactive) (message "Position saved") (pdf-view-position-to-register ?x)))
   3166                 ("C-u C-SPC" . (lambda () (interactive) (pdf-view-jump-to-register ?x))))
   3167     :hook
   3168     (pdf-annot-list-mode . pdf-annot-list-follow-minor-mode)
   3169     (pdf-annot-edit-contents-minor-mode . org-mode)
   3170     (pdf-view-mode . (lambda () (display-line-numbers-mode 0)))
   3171 
   3172     :config
   3173     ;; The arrow tooltip does not show properly when jumping to a
   3174     ;; location. Maybe this is a Mac-only thing. See here:
   3175     ;; https://github.com/politza/pdf-tools/issues/145
   3176     ;; This ~:override~ advice fixes it, color is customized via ~tooltip~ face
   3177     (advice-add #'pdf-util-tooltip-arrow :override #'za/pdf-util-tooltip-arrow)
   3178     (defun za/pdf-util-tooltip-arrow (image-top &optional timeout)
   3179       "Fix up `pdf-util-tooltip-arrow`, the original doesn't show the arrow."
   3180       (pdf-util-assert-pdf-window)
   3181       (when (floatp image-top)
   3182         (setq image-top
   3183               (round (* image-top (cdr (pdf-view-image-size))))))
   3184       (let* (x-gtk-use-system-tooltips ;allow for display property in tooltip
   3185              (dx (+ (or (car (window-margins)) 0)
   3186                     (car (window-fringes))))
   3187              (dy image-top)
   3188              (pos (list dx dy dx (+ dy (* 2 (frame-char-height)))))
   3189              (vscroll
   3190               (pdf-util-required-vscroll pos))
   3191              (tooltip-frame-parameters
   3192               `((border-width . 0)
   3193                 (internal-border-width . 0)
   3194                 ,@tooltip-frame-parameters))
   3195              (tooltip-hide-delay (or timeout 3)))
   3196         (when vscroll
   3197           (image-set-window-vscroll vscroll))
   3198         (setq dy (max 0 (- dy
   3199                            (cdr (pdf-view-image-offset))
   3200                            (window-vscroll nil t)
   3201                            (frame-char-height))))
   3202         (when (overlay-get (pdf-view-current-overlay) 'before-string)
   3203           (let* ((e (window-inside-pixel-edges))
   3204                  (xw (pdf-util-with-edges (e) e-width)))
   3205             (cl-incf dx (/ (- xw (car (pdf-view-image-size t))) 2))))
   3206         (pdf-util-tooltip-in-window "\u2192" dx dy))))
   3207 #+end_src
   3208 
   3209 *** TODO this clobbers register x. Find a way to not clobber a register
   3210 ** virtualenvwrapper
   3211 Like virtualenvwrapper.sh, but for Emacs.
   3212 
   3213 #+begin_src emacs-lisp
   3214   (use-package virtualenvwrapper
   3215     :custom
   3216     (venv-location "~/.config/virtualenvs")
   3217 
   3218     :config
   3219     (venv-initialize-interactive-shells)
   3220     (venv-initialize-eshell))
   3221 #+end_src
   3222 
   3223 ** ledger
   3224 #+begin_src emacs-lisp
   3225   (use-package ledger-mode
   3226     :mode ("\\.ledger\\'")
   3227     :hook (ledger-mode . company-mode)
   3228     :custom
   3229     (ledger-clear-whole-transactions t)
   3230     (ledger-reconcile-default-commodity "eur")
   3231     (ledger-reports
   3232      '(("unreconciled" "%(binary) [[ledger-mode-flags]] -f %(ledger-file) --start-of-week=1 reg --uncleared")
   3233        ("net-worth-changes" "%(binary) [[ledger-mode-flags]] -f %(ledger-file) reg ^Assets ^Liabilities -R -M -X eur --effective -n")
   3234        ("budget-last-month" "%(binary) -f %(ledger-file) --start-of-week=1 --effective -X eur --period \"last month\" budget ^expenses:budgeted")
   3235        ("budget-this-month" "%(binary) -f %(ledger-file) --start-of-week=1 --effective -X eur --period \"this month\" budget ^expenses:budgeted")
   3236        ("expenses-this-month-vs-budget" "%(binary) -f %(ledger-file) --start-of-week=1 --effective --period \"this month\" --period-sort \"(amount)\" bal ^expenses:budgeted --budget -R")
   3237        ("expenses-last-month-vs-budget" "%(binary) -f %(ledger-file) --start-of-week=1 --effective --period \"last month\" --period-sort \"(amount)\" bal ^expenses:budgeted --budget -R")
   3238        ("expenses-last-month" "%(binary) -f %(ledger-file) --start-of-week=1 --effective --period \"last month\" --period-sort \"(amount)\" bal ^expenses -X eur -R")
   3239        ("expenses-this-month" "%(binary) -f %(ledger-file) --start-of-week=1 --effective --period \"this month\" --period-sort \"(amount)\" bal ^expenses -X eur -R")
   3240        ("expenses-vs-income-this-month" "%(binary) -f %(ledger-file) --start-of-week=1 --effective --period \"this month\" --period-sort \"(amount)\" bal ^income ^expenses -X eur -R")
   3241        ("expenses-vs-income-last-month" "%(binary) -f %(ledger-file) --start-of-week=1 --effective --period \"last month\" --period-sort \"(amount)\" bal ^expenses ^income -X eur -R")
   3242        ("bal-assets-czk" "%(binary) -f %(ledger-file) --start-of-week=1 bal Assets Liabilities -X czk -R")
   3243        ("bal-assets" "%(binary) -f %(ledger-file) --start-of-week=1 bal Assets Liabilities -R")
   3244        ("bal" "%(binary) -f %(ledger-file) --start-of-week=1 bal -B -R")
   3245        ("bal-assets-eur" "%(binary) -f %(ledger-file) --start-of-week=1 bal Assets Liabilities -X eur -R")
   3246        ("monthly-balance-abn-checking" "%(binary) -f %(ledger-file) --start-of-week=1 --effective reg --monthly 'Assets:ABN Checking' -R")
   3247        ("monthly-expenses" "%(binary) -f %(ledger-file) --monthly register ^expenses --effective --collapse -X eur -R")
   3248        ("reg" "%(binary) -f %(ledger-file) --start-of-week=1 reg -R")
   3249        ("payee" "%(binary) -f %(ledger-file) --start-of-week=1 reg @%(payee) -R")
   3250        ("account" "%(binary) -f %(ledger-file) --start-of-week=1 reg %(account) -R")
   3251        ("reg-org-table" "%(binary) -f %(ledger-file) csv --csv-format '|%(scrub(date))|%(scrub(display_account))|%(scrub(payee))|%(scrub(display_amount))|%(scrub(display_total))|
   3252   ' %(account) -R")))
   3253     :config
   3254     (with-eval-after-load 'ledger-mode
   3255       (setq ledger-amount-regex
   3256             (rx
   3257              (group (or (= 2 " ") ?\t (seq " " ?\t)))
   3258              (zero-or-more (any " " ?\t))
   3259              (opt "=")
   3260              (zero-or-more space)
   3261              (opt "-")
   3262              (opt "(")
   3263              (one-or-more (opt (group
   3264                                 (one-or-more (any "A-Z" "$(_£€₹"))
   3265                                 (zero-or-more blank)))
   3266                           (group (opt "-")
   3267                                  (or (one-or-more (any "0-9"))
   3268                                      (+\? (any "0-9" ",."))))
   3269                           (opt (group (any ",.")
   3270                                       (one-or-more (any "0-9" ")"))))
   3271                           (opt (group (zero-or-more blank)
   3272                                       (one-or-more (any "\"_£€₹" word))))
   3273                           (opt (zero-or-more (any blank))
   3274                                (any "*+/-")
   3275                                (zero-or-more (any blank))))
   3276              (opt ")")
   3277              (opt (group (zero-or-more (any blank))
   3278                          (any "=@{")
   3279                          (opt "@")
   3280                          (+? (not (any ?\xA ";")))))
   3281              (opt (group (or (seq (one-or-more (any blank)) ";" (+\? nonl))
   3282                              (zero-or-more (any blank)))))
   3283              eol))))
   3284 #+end_src
   3285 
   3286 org-capture lets me add transactions from anywhere in Emacs:
   3287 
   3288 Budget throws an error when there's multiple commodities involved.
   3289 See discussion here: https://github.com/ledger/ledger/issues/1450#issuecomment-390067165
   3290 
   3291 #+begin_src emacs-lisp
   3292   (defconst za/ledger-budget-fix-string
   3293     "-X eur -F '%(justify(scrub(get_at(display_total, 0)), 20, -1, true, false)) %(justify(get_at(display_total, 1) ? -scrub(get_at(display_total, 1)) : 0.0, 20,            20 + 1 + 20, true, false)) %(justify(get_at(display_total, 1) ? (get_at(display_total, 0) ?           -(scrub(get_at(display_total, 1) + get_at(display_total, 0))) :           -(scrub(get_at(display_total, 1)))) : -(scrub(get_at(display_total, 0))), 20,            20 + 1 + 20 + 1 + 20, true, false))%(get_at(display_total, 1) and (abs(quantity(scrub(get_at(display_total, 0))) /           quantity(scrub(get_at(display_total, 1)))) >= 1) ?  \" \" : \" \")%(justify((get_at(display_total, 1) ?           (100% * (get_at(display_total, 0) ? scrub(get_at(display_total, 0)) : 0.0)) /              -scrub(get_at(display_total, 1)) : \"na\"),            5, -1, true, false))  %(!options.flat ? depth_spacer : \"\")%-(partial_account(options.flat))\n%/%$2 %$3 %$4 %$6\n%/%(prepend_width ? \" \" * int(prepend_width) : \"\")    ----------------     ----------------     ---------------- -----\n'"
   3294     "Append this to a ledger budget to fix errors with multiple commodities.")
   3295 #+end_src
   3296 
   3297 ** Notmuch
   3298 #+begin_src emacs-lisp
   3299   (use-package notmuch
   3300     :custom
   3301     (notmuch-saved-searches
   3302      `((:name "inbox: personal" :query ,(format "folder:/%s/ tag:inbox" za/email-personal) :key ,(kbd "ip") :search-type 'tree)
   3303        (:name "inbox: school" :query ,(format "folder:/%s/ tag:inbox" za/email-vu) :key ,(kbd "is") :search-type 'tree)
   3304        (:name "archive: personal" :query ,(format "folder:/%s/ tag:archive" za/email-personal) :key ,(kbd "ap") :search-type 'tree)
   3305        (:name "archive: school" :query ,(format "folder:/%s/ tag:archive" za/email-vu) :key ,(kbd "as") :search-type 'tree))
   3306      "Define some saved searches (i.e. mailboxes)")
   3307     (notmuch-hello-sections
   3308      '(notmuch-hello-insert-header
   3309        notmuch-hello-insert-saved-searches
   3310        notmuch-hello-insert-search
   3311        notmuch-hello-insert-alltags
   3312        notmuch-hello-insert-footer)
   3313      "Define the main screen sections")
   3314     (notmuch-search-oldest-first nil "Show newest mail first")
   3315     (notmuch-archive-tags '("-inbox" "+archive"))
   3316     (notmuch-tagging-keys '(("a" notmuch-archive-tags "Archive")
   3317                             ("r" notmuch-show-mark-read-tags "Mark read")
   3318                             ("u" notmuch-show-mark-unread-tags "Mark unread")
   3319                             ("d" notmuch-delete-tags "Delete")))
   3320 
   3321     :bind (("C-c m" . notmuch)
   3322            :map notmuch-show-mode-map
   3323            ("C-c M-y" . shr-copy-url))
   3324     ;; Run notmuch-hook script on hello refresh, to move messages to
   3325     ;; folders according to their tags:
   3326     :hook (notmuch-hello-refresh . za/notmuch-hook-tags2folders)
   3327     :init (setenv "NOTMUCH_CONFIG" "/Users/alex/.config/notmuch/config")
   3328     :config
   3329     (setq notmuch-show-mark-unread-tags '("+unread"))
   3330     (setq notmuch-delete-tags '("-inbox" "+trash"))
   3331     (defun za/notmuch-hook-tags2folders ()
   3332       "Run notmuch-hook to organise email in folders based on tags."
   3333       (start-process "notmuch-hook" nil "notmuch-hook" "--tags2folders")))
   3334 #+end_src
   3335 
   3336 ** MPC
   3337 #+begin_src emacs-lisp
   3338   (use-package mpc
   3339     :custom
   3340     (mpc-browser-tags '(AlbumArtist Album Genre Playlist)
   3341                       "Set the windows I want to show")
   3342 
   3343     :bind (:map mpc-mode-map
   3344                 ("a" . mpc-playlist-add)
   3345                 ("P" . mpc-playlist)
   3346                 ("x" . mpc-playlist-delete)
   3347                 ("p" . mpc-toggle-play)
   3348                 ("t" . mpc-select-toggle)
   3349                 ("f" . za/mpc-seek-forward-20-seconds)
   3350                 ("b" . za/mpc-seek-backward-20-seconds))
   3351     :config
   3352     (defun za/mpc-seek-forward-20-seconds ()
   3353       "Seek forward 20 seconds"
   3354       (interactive)
   3355       (mpc-seek-current "+20"))
   3356 
   3357     (defun za/mpc-seek-backward-20-seconds ()
   3358       "Seek backward 20 seconds"
   3359       (interactive)
   3360       (mpc-seek-current "-20")))
   3361 #+end_src
   3362 ** Dired
   3363 #+begin_src emacs-lisp
   3364   (use-package dired
   3365     :ensure nil ; installed with Emacs
   3366     :bind (:map dired-mode-map
   3367                 ;; 'i' expands subdirs, so I want to be able to close them too.
   3368                 ("M-k" . dired-kill-subdir))
   3369     :custom
   3370     (dired-listing-switches "-alhv")
   3371     (dired-dwim-target t "If I have another dired window open, use that as target")
   3372     ;; By default, hide details (show again by pressing oparen):
   3373     :hook (dired-mode . dired-hide-details-mode))
   3374 #+end_src
   3375 
   3376 ** ess: statistics (R, SAS...)
   3377 #+begin_src emacs-lisp
   3378   (use-package ess)
   3379 #+end_src
   3380 
   3381 ** help mode
   3382 #+begin_src emacs-lisp
   3383   (use-package help-mode
   3384     :ensure nil ; included with Emacs
   3385     :hook (help-mode . za/settings-on-help-mode)
   3386     :config
   3387     (defun za/settings-on-help-mode ()
   3388       "Settings on enabling help mode"
   3389       (za/toggle-wrap t)))
   3390 #+end_src
   3391 ** helpful
   3392 An alternative to the built-in Emacs help that provides much more contextual information.
   3393 I use counsel, so I use the keybindings in [[*counsel + ivy + swiper]].
   3394 I just augment the functions counsel uses.
   3395 Also, counsel doesn't provide some keybindings that I can get from helpful.
   3396 
   3397 #+begin_src emacs-lisp
   3398   (use-package helpful
   3399     :custom
   3400     (counsel-describe-symbol-function #'helpful-symbol)
   3401     (counsel-describe-function-function #'helpful-callable)
   3402     (counsel-describe-variable-function #'helpful-variable)
   3403 
   3404     :bind (("C-h k" . helpful-key)
   3405            ("C-h C" . helpful-command)
   3406            :map helpful-mode-map
   3407            ("l" . za/helpful-previous)
   3408            ("r" . za/helpful-next))
   3409 
   3410     :hook (helpful-mode . za/settings-on-helpful-mode)
   3411     :config
   3412 
   3413     (defun za/settings-on-helpful-mode ()
   3414       "Settings on enabling helpful mode"
   3415       (za/toggle-wrap t))
   3416 
   3417     ;; Then, a way to jump forward and backward in the window:
   3418     (defvar za/helpful-buffer-ring-size 20
   3419       "How many buffers are stored for use with `helpful-next'.")
   3420 
   3421     (defvar za/helpful--buffer-ring (make-ring za/helpful-buffer-ring-size)
   3422       "Ring that stores the current Helpful buffer history.")
   3423 
   3424     (defun za/helpful--buffer-index (&optional buffer)
   3425       "If BUFFER is a Helpful buffer, return it’s index in the buffer ring."
   3426       (let ((buf (or buffer (current-buffer))))
   3427         (and (eq (buffer-local-value 'major-mode buf) 'helpful-mode)
   3428              (seq-position (ring-elements za/helpful--buffer-ring) buf #'eq))))
   3429 
   3430     (defun za/helpful--new-buffer-a (help-buf)
   3431       "Update the buffer ring according to the current buffer and HELP-BUF."
   3432       :filter-return #'helpful--buffer
   3433       (let ((buf-ring za/helpful--buffer-ring))
   3434         (let ((newer-buffers (or (za/helpful--buffer-index) 0)))
   3435           (dotimes (_ newer-buffers) (ring-remove buf-ring 0)))
   3436         (when (/= (ring-size buf-ring) za/helpful-buffer-ring-size)
   3437           (ring-resize buf-ring za/helpful-buffer-ring-size))
   3438         (ring-insert buf-ring help-buf)))
   3439 
   3440     (advice-add #'helpful--buffer :filter-return #'za/helpful--new-buffer-a)
   3441 
   3442     (defun za/helpful--next (&optional buffer)
   3443       "Return the next live Helpful buffer relative to BUFFER."
   3444       (let ((buf-ring za/helpful--buffer-ring)
   3445             (index (or (za/helpful--buffer-index buffer) -1)))
   3446         (cl-block nil
   3447           (while (> index 0)
   3448             (cl-decf index)
   3449             (let ((buf (ring-ref buf-ring index)))
   3450               (if (buffer-live-p buf) (cl-return buf)))
   3451             (ring-remove buf-ring index)))))
   3452 
   3453 
   3454     (defun za/helpful--previous (&optional buffer)
   3455       "Return the previous live Helpful buffer relative to BUFFER."
   3456       (let ((buf-ring za/helpful--buffer-ring)
   3457             (index (1+ (or (za/helpful--buffer-index buffer) -1))))
   3458         (cl-block nil
   3459           (while (< index (ring-length buf-ring))
   3460             (let ((buf (ring-ref buf-ring index)))
   3461               (if (buffer-live-p buf) (cl-return buf)))
   3462             (ring-remove buf-ring index)))))
   3463 
   3464     (defun za/helpful-next ()
   3465       "Go to the next Helpful buffer."
   3466       (interactive)
   3467       (when-let (buf (za/helpful--next))
   3468         (funcall helpful-switch-buffer-function buf)))
   3469 
   3470     (defun za/helpful-previous ()
   3471       "Go to the previous Helpful buffer."
   3472       (interactive)
   3473       (when-let (buf (za/helpful--previous))
   3474         (funcall helpful-switch-buffer-function buf))))
   3475 #+end_src
   3476 ** Tex-mode
   3477 #+begin_src emacs-lisp
   3478   (use-package tex-mode
   3479     :ensure nil ; installed with Emacs
   3480     :hook (tex-mode . za/settings-on-tex-mode)
   3481     :config
   3482     (defun za/settings-on-tex-mode ()
   3483       "Settings on enabling helpful mode"
   3484       (setq comment-add 0)))
   3485 #+end_src
   3486 ** Quail
   3487 #+begin_src emacs-lisp
   3488   (use-package quail
   3489     :ensure nil) ; provided by Emacs
   3490 #+end_src
   3491 ** Markdown
   3492 #+begin_src emacs-lisp
   3493   (use-package markdown-mode)
   3494 #+end_src
   3495 ** vdirel (contacts)
   3496 #+begin_src emacs-lisp
   3497   (use-package vdirel
   3498     :config
   3499     (vdirel-switch-repository "~/.local/share/contacts/default"))
   3500 #+end_src
   3501 ** Yaml
   3502 #+begin_src emacs-lisp
   3503   (use-package yaml-mode
   3504     :commands yaml-mode
   3505     :init
   3506     (add-hook 'yaml-mode-hook
   3507               (lambda ()
   3508                 (setq-local outline-regexp (rx (* blank)))
   3509                 (outline-minor-mode))))
   3510 #+end_src
   3511 ** calc
   3512 #+begin_src emacs-lisp
   3513   (use-package calc
   3514     :config
   3515     (setq math-additional-units
   3516      ;; elements:
   3517      ;; - symbol identifying the unit,
   3518      ;; - expression indicatingv alue of unit or nil for fundamental units
   3519      ;; - textual description
   3520      '((b nil "Bit")
   3521        (B "b * 8" "Bytes")
   3522        (KiB "1024 * B" "Kibibyte")
   3523        (MiB "1024 * KiB" "Mebibyte")
   3524        (GiB "1024 * MiB" "Gibibyte")
   3525        (TiB "1024 * GiB" "Tebibyte")
   3526        (PiB "1024 * TiB" "Pebibyte")
   3527        (EiB "1024 * PiB" "Exbibyte")
   3528        (ZiB "1024 * EiB" "Zebibyte")
   3529        (YiB "1024 * ZiB" "Yobibyte")
   3530        (KB "1000 * B" "Kilobyte")
   3531        (MB "1000 * KB" "Megabyte")
   3532        (GB "1000 * MB" "Gigabyte")
   3533        (TB "1000 * GB" "Terabyte")
   3534        (PB "1000 * TB" "Petabyte")
   3535        (EB "1000 * PB" "Exabyte")
   3536        (ZB "1000 * EB" "Zettabyte")
   3537        (YB "1000 * ZB" "Yottabyte")
   3538        (Kib "1024 * b" "Kibibit")
   3539        (Mib "1024 * Kib" "Mebibit")
   3540        (Gib "1024 * Mib" "Gibibit")
   3541        (Kb "1000 * b" "Kilobit")
   3542        (Mb "1000 * Kb" "Megabit")
   3543        (Gb "1000 * Mb" "Gigabit")))
   3544     (setq math-units-table nil))
   3545 #+end_src
   3546 ** casual
   3547 #+begin_src emacs-lisp
   3548   (use-package casual
   3549     :config
   3550     (require 'casual-image)
   3551     :bind (:map calc-mode-map
   3552            ("C-o" . 'casual-calc-tmenu)
   3553            :map dired-mode-map
   3554            ("C-o" . 'casual-dired-tmenu)
   3555            ("C-u C-o" . 'dired-display-file)
   3556            :map calendar-mode-map
   3557            ("C-o" . 'casual-calendar-tmenu)
   3558            :map image-mode-map
   3559            ("C-o" . 'casual-image-tmenu)))
   3560 #+end_src
   3561 ** json
   3562 #+begin_src emacs-lisp
   3563   (use-package json-mode)
   3564 #+end_src
   3565 ** rust
   3566 #+begin_src emacs-lisp
   3567   (use-package rust-mode)
   3568 #+end_src
   3569 ** artist mode
   3570 #+begin_src emacs-lisp
   3571   (use-package artist
   3572     :ensure nil ; included with emacs
   3573     :custom (artist-figlet-default-font "term"))
   3574 #+end_src
   3575 * Override some faces
   3576 #+begin_src emacs-lisp
   3577   (with-eval-after-load 'org-faces
   3578     (set-face-attribute 'org-table nil :inherit 'fixed-pitch)
   3579     (set-face-attribute 'org-block nil :inherit 'fixed-pitch))
   3580 #+end_src
   3581 * Shortdoc
   3582 Set a better keybinding (I'm never gonna use ~view-hello-file~ anyways):
   3583 
   3584 #+begin_src emacs-lisp
   3585   (bind-key "C-h h" #'shortdoc-display-group)
   3586 #+end_src
   3587 * Upcoming new features
   3588 In a new version of use-package, I can use the :vc keyword, so check for when that's available.
   3589 See [[https://git.savannah.gnu.org/cgit/emacs.git/commit/?id=2ce279680bf9c1964e98e2aa48a03d6675c386fe][commit]] and [[https://tony-zorman.com/posts/use-package-vc.html][article]].
   3590 
   3591 #+begin_src emacs-lisp
   3592   (when (fboundp 'use-package-vc-install)
   3593     (user-error "use-package :vc keyword now available!"))
   3594 #+end_src
   3595 * References
   3596 Here's a list of good articles I encountered about configging emacs:
   3597 - [[https://karthinks.com/software/batteries-included-with-emacs/][Batteries included with Emacs]]
   3598 - [[https://karthinks.com/software/more-batteries-included-with-emacs/][More batteries included with emacs]]
   3599 
   3600 For Org mode, [[https://www.youtube.com/playlist?list=PLVtKhBrRV_ZkPnBtt_TD1Cs9PJlU0IIdE][Rainer König's tutorials]] are the best.
   3601 [[https://emacs.cafe/emacs/orgmode/gtd/2017/06/30/orgmode-gtd.html][Here's a good reference for setting up gtd in org mode]]