Wai Hon's Blog

Emacs Config

This is my public Emacs configuration.


Using a custom-file

(setq custom-file (locate-user-emacs-file "custom.el"))
;; create custom.el if it does not exists.
(unless (file-exists-p custom-file)
  (write-region "" nil custom-file))
(load custom-file)

Package Management

For use-package keywords: https://jwiegley.github.io/use-package/keywords/

;; MELPA package
(require 'package)
(add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t)

;; Ensure for all packages
(require 'use-package-ensure)
(setq use-package-always-ensure t)

;; See https://github.com/slotThe/vc-use-package
;; TODO: remove when vc-use-package is merged.
(unless (package-installed-p 'vc-use-package)
  (package-vc-install "https://github.com/slotThe/vc-use-package"))



;; Increase the garbage collection threshold to 100MB to reduced startup time.
;; See https://www.reddit.com/r/emacs/comments/3kqt6e
(setq gc-cons-threshold (* 1024 1024 100))

;; Turn off mouse interface early in startup to avoid momentary display.
(menu-bar-mode -1)

(tooltip-mode -1)

;; On Emacs without X, tool-bar-mode and scroll-bar-mode are not defined.
(when (fboundp 'tool-bar-mode)
  (tool-bar-mode -1))
(when (fboundp 'scroll-bar-mode)
  (scroll-bar-mode -1))

;; Show column number in the mode line.

;; Inhibit the startup screen and shorten the scratch buffer's message.
(setq inhibit-startup-screen t)
(setq initial-scratch-message ";; scratch buffer\n\n")


A popular recommendation is to bind <escape> with keyboard-escape-quit. However, it closes all the other windows at the same time and it is annoying to me. Instead, I map <escape> to keyboard-quit.

;; Don't forget to handle minibuffer with "minibuffer-keyboard-quit".
(global-set-key (kbd "<escape>") 'keyboard-quit)

;; Avoid entering the ~repeat-complex-cammand~ when quiting everything with ~C-x~.
(global-unset-key (kbd "C-x <escape> <escape>")) ; repeat-complex-command

An even better way is to build muscle memory to use the standard C-g to “quit” and C-] to “abort”.


I don’t use backup files often as I use git to manage most of my org files. However, I still feel safer when having a backup. I follow the backup configuration from Sacha Chua to enable Emacs’s backups aggressively.

;; Save backup files to a dedicated directory.
(setq backup-directory-alist `(("." . ,(expand-file-name "backups" user-emacs-directory))))
(setq delete-old-versions -1)

;; The default is nil, which means Emacs moves file to backup and then copy it back.
;; First seen on https://idiomdrottning.org/bad-emacs-defaults.
(setq backup-by-copying t)

;; Make numeric backup versions unconditionally.
(setq version-control t)
(setq vc-make-backup-files t)
(setq auto-save-file-name-transforms `((".*" ,(expand-file-name "auto-save-list" user-emacs-directory) t)))

;; Do not create lock files.
(setq create-lockfiles nil)

Disable Native Compilation Warnings

(setq native-comp-async-report-warnings-errors nil)


;; Use year/month/day
(setq calendar-date-style 'iso)

(xterm-mouse-mode +1)

;; Remember and restore the last cursor location of opened files
(save-place-mode 1)

;; Remeber recent files.
(recentf-mode +1)

;; Don't pop up UI dialogs when prompting
(setq use-dialog-box nil)

;; Disable the alarm bell (https://www.emacswiki.org/emacs/AlarmBell).
(setq ring-bell-function 'ignore)

;; Use shorter "y" or "n" to confirm killing emacs.
(setq confirm-kill-emacs 'y-or-n-p)


Remove Key Bindings

I disable most Emacs’s default keybinding because I am not able to get my muscle memory to work with it. Even if I do, that muscle memory probably will cause trouble when editing in other applications.

;; Disabe some Emacs's default keybindings.
(global-unset-key (kbd "C-v"))  ; scroll-up-command
(global-unset-key (kbd "M-v"))  ; scroll-down-command
(global-unset-key (kbd "C-n"))  ; next line
(global-unset-key (kbd "C-p"))  ; previous line
(global-unset-key (kbd "C-b"))  ; previous char
(global-unset-key (kbd "C-f"))  ; next char
(global-unset-key (kbd "C-t"))  ; switch char
(global-unset-key (kbd "C-l"))  ; recenter
(global-unset-key (kbd "C-j"))  ; (electric-newline-and-maybe-indent)
(global-unset-key (kbd "M-l"))  ; downcase-word
(global-unset-key (kbd "M-u"))  ; upcase-wrod
(global-unset-key (kbd "C-z"))  ; suspend-frame

;; Disable the "numeric argument". When used, I use the =C-u= prefix.
(dolist (prefix '("M-" "C-M-"))
  (global-unset-key (kbd (concat prefix "-")))
  (dotimes (i 10)
    (global-unset-key (kbd (concat prefix (number-to-string i))))))

Text Mode and Prog Mode

I defined my own my/text-mode and my/prog-mode which enable several minor modes and key bindings.

I avoid global settings like global-display-line-numbers-mode and only enable stuff when I need to, like in prog-mode. I use global settings only if that is globally applicable everywhere.

(defun my/edit-mode ()
  ;; (hl-line-mode +1)
  (local-set-key (kbd "C-S-s") 'write-file)
  (setq cursor-type 'bar)
  (setq show-trailing-whitespace t))

(defun my/text-mode ()
  (visual-line-mode +1)               ; enable "word-wrap"
  (toggle-truncate-lines -1)
  (goto-address-mode +1)

(defun my/prog-mode ()
  (display-line-numbers-mode +1)
  (show-paren-mode +1)
  (goto-address-prog-mode +1)

(add-hook 'text-mode-hook 'my/text-mode)
(add-hook 'prog-mode-hook 'my/prog-mode)
(add-hook 'conf-mode-hook 'my/prog-mode)

;; Removes the overlay properties which flyspell uses on incorrect words for mouse operations.
;; https://emacs.stackexchange.com/a/55708
(defun make-flyspell-overlay-return-mouse-stuff (overlay)
  (overlay-put overlay 'help-echo nil)
  (overlay-put overlay 'keymap nil)
  (overlay-put overlay 'mouse-face nil))
(advice-add 'make-flyspell-overlay :filter-return #'make-flyspell-overlay-return-mouse-stuff)

Delete Trailing Whitespaces Except Current Line

I hook this function with save-buffer.

The before-save-hook does not work in a specific scenario:

  1. When the current line has trailing space.
  2. After saving the file (the trailing space is not removed, as expected).
  3. Move the cursor to the next line.
  4. Save the file again, the before-save-hook is not triggered because the file has not been altered from the last save.
;; Remove trailing whitespace except current line.
;; https://stackoverflow.com/a/35781486/1747877
(defun my/delete-trailing-whitespace-except-current-line ()
  "Delete trailing whitespace in the whole buffer, except on the current line.
  The current line exception is because we do want to remove any whitespace
  on the current line on saving the file while we are in-between typing something.

  Do not do anything if `do-not-delete-trailing-whitespace' is non-nil."
  (when (not (bound-and-true-p do-not-delete-trailing-whitespace))
    (delete-trailing-whitespace (point-min) (line-beginning-position))
    (delete-trailing-whitespace (line-end-position) (point-max))))

Better save-buffer

I made 2 improvements to save-buffer:

  1. do not save for non-file-visiting buffer (See my blog post)
  2. save asynchronously with thread to avoid blocking the UI
(defun my/save-buffer-advice (orig-fun &rest args)
  (unless (or (buffer-file-name)                       ; regular buffer
              (buffer-file-name (buffer-base-buffer))) ; indirect buffer
    (user-error "Use 'M-x write-file' to save this buffer."))


  (apply orig-fun args)
  ;; Execute save-buffer with thread so it does not block the UI.
  ;; (make-thread
  ;;  (condition-case err
  ;;      (apply orig-fun args)
  ;;    (error
  ;;     (message "Error from my/save-buffer-advice %S" err)
  ;;     nil))
  ;;  "my/save-buffer-advice")

(advice-add 'save-buffer :around #'my/save-buffer-advice)

Auto Save and Auto Revert

Auto-save and auto-revert cause less conflict when editing files synchronized on multiple computers.

;; Auto save buffer if idled for 2 seconds.
(setq auto-save-timeout 2)
(auto-save-visited-mode 1)

;; Watch and reload the file changed on the disk.
(setq auto-revert-remote-files t)
(global-auto-revert-mode 1)

;; Use a timer instead of file notification.
;; File notification does not work well on Emacs 29.1.2.
;; Error: "file-notify--call-handler: Symbol’s function definition is void: nil"
;; 2023-09-22 :: However, it seems causing file modified error. Commented again and try.
;; (setq auto-revert-use-notify nil
;;       auto-revert-interval 5)

Modern Editor Behavior

These configurations modernize Emacs.

;; Delete the selected text first before editing.
(delete-selection-mode +1)

;; Mouse middle-click yanks where the point is, not where the mouse is.
(setq mouse-yank-at-point t)

Smooth Scrolling

The default Emacs scrolling behavior is really weird and different from other modern editors. However, the result is still not ideal. We might need to wait for the pixel-based scrolling coming with Emacs 29.

(if (fboundp 'pixel-scroll-precision-mode)
    (pixel-scroll-precision-mode 1)
  ;; Smooth Scrolling: https://www.emacswiki.org/emacs/SmoothScrolling
  (setq scroll-conservatively 10000
        scroll-step 1))

Moving Lines

Moving lines up and down are very common editing operations to me. This stackoverflow entry has more fancy answers but these two are exactly what I need.

;; move line up
(defun my/move-line-up ()
  (transpose-lines 1)
  (previous-line 2))
(global-set-key [(meta shift up)] 'my/move-line-up)

;; move line down
(defun my/move-line-down ()
  (next-line 1)
  (transpose-lines 1)
  (previous-line 1))

(global-set-key [(meta shift down)] 'my/move-line-down)

Sentence End with Single Space

By default, Emacs treat a period followed by double spaces as the end of sentence. This is old-fashioned and uncommon now.

(setq sentence-end-double-space nil)

Indent with Space

(setq-default indent-tabs-mode nil)

Rename File and Buffer Together

See https://emacs.readthedocs.io/en/latest/file_management.html.

;; rename-visited-file is introduced in Emacs 29.
(unless (fboundp 'rename-visited-file)
  (defun rename-visited-file ()
    "Renames the current buffer and the file it is visiting."
    (let ((name (buffer-name))
          (filename (buffer-file-name)))
      (if (not (and filename (file-exists-p filename)))
          (error "Buffer '%s' is not visiting a file!" name)
        (let ((new-name (read-file-name "New name: " filename)))
          (if (get-buffer new-name)
              (error "A buffer named '%s' already exists!" new-name)
            (rename-file filename new-name 1)
            (rename-buffer new-name)
            (set-visited-file-name new-name)
            (set-buffer-modified-p nil)
            (message "File '%s' successfully renamed to '%s'"
                     name (file-name-nondirectory new-name))))))))

(global-set-key (kbd "C-x R") 'rename-visited-file)

Delete File and Buffer Together

See http://emacsredux.com/blog/2013/04/03/delete-file-and-buffer/. If you like this command, it worth taking a look at crux package as well for similar useful collection.

(defun my/delete-file-and-buffer ()
  "Kills the current buffer and deletes the file it is visiting."
  (if-let ((filename (buffer-file-name)))
      (when (y-or-n-p (concat "Do you really want to delete file " filename " ?"))
        (delete-file filename)
        (message "Deleted file %s." filename)
    (message "Not a file visiting buffer!")))

(global-set-key (kbd "C-x K") 'my/delete-file-and-buffer)

Edit File as Root

(defun my/sudo-find-file (file-name)
  "Like find file, but opens the file as root."
  (interactive "FSudo Find File: ")
  (let ((tramp-file-name (concat "/sudo::" (expand-file-name file-name))))
    (find-file tramp-file-name)))


I found Tramp could be spammy to the minibuffer when saving file.

For example, these logs are printed to the minibuffer when saving a file.

Tramp: Encoding local file ‘/tmp/tramp.JniPQo.org’ using ‘base64-encode-region’…done Tramp: Decoding remote file ‘/ssh:<user>@<host>:/path/to/test.org’ using ‘base64 -d -

Set tramp-verbose to 2 or lower to avoid showing the “connection to remote hosts” level message in minibuffer.

;; for Emacs 28 or above
(setq tramp-verbose 2)
;; for Emacs 27 or below
(setq tramp-message-show-message nil)

Case-sensitive replace-string

M-x replace-string preserves case in each match if case-replace (preserve case) and case-fold-search (ignore case) are non-nil. The latter makes replace-string case-insensitive.

I prefer case-sensitive replace-string and apply the customization from https://stackoverflow.com/a/5346216.

(defun with-case-fold-search (orig-fun &rest args)
  (let ((case-fold-search nil))
    (apply orig-fun args)))

(advice-add 'replace-string :around #'with-case-fold-search)


Modus Theme

Note that there is a command M-x modus-themes-toggle to toggle the dark and light modus theme. Thanks to this video. I found the Modus themes is less buggy than doom theme, with the which-key package.

(use-package modus-themes
  (setq modus-themes-to-toggle '(modus-operandi modus-vivendi-tinted))
  (setq modus-themes-org-blocks 'gray-background)
  (setq modus-themes-headings
        '((agenda-date . (1.2))))

  (setq modus-themes-common-palette-overrides
        '((fg-heading-1 blue)
          (fg-heading-2 cyan)
          (fg-heading-3 magenta)
          (fg-heading-4 blue)))

  (load-theme 'modus-vivendi-tinted :no-confirm)
  ("<f5>" . modus-themes-toggle)
  ("<f6>" . modus-themes-toggle))

Doom Modeline

I don’t use Doom Emacs but I do use its modeline.

;; https://github.com/seagle0128/doom-modeline
(use-package doom-modeline
  (doom-modeline-mode +1))

;; Doom modeline needs nerd-icons.
;; For the first install, run =M-x nerd-icons-install-fonts=.
(use-package nerd-icons)

Window Management

Winner Mode

Winner Mode is a global minor mode. When activated, it allows you to “undo” (and “redo”) changes in the window configuration with the key commands C-c left and C-c right.

(use-package winner
  (winner-mode +1))

Window Navigation

Most of the time, I have only 1 or 2 windows in a frame. Rarely 3, and probably never 4 or above. other-window just works.

I bind it to M-o in additional to the default C-x o for even faster navigation.

(global-set-key (kbd "M-o") 'other-window)

I had tried windmove and ace-window but disabled both because other-window just work.

(use-package windmove
  ("C-M-<up>" . 'windmove-up)
  ("C-M-<down>" . 'windmove-down)
  ("C-M-<left>" . 'windmove-left)
  ("C-M-<right>" . 'windmove-right))

(use-package ace-window
  ("M-o" . 'ace-window)
  (aw-keys '(?a ?s ?d ?f ?g ?h ?j ?k ?l))
  (aw-scope 'frame))

Window Dedication

(defun my/toggle-current-window-dedication ()
  (let* ((window (selected-window))
         (dedicated (window-dedicated-p window)))
    (set-window-dedicated-p window (not dedicated))
    (message "Window %sdedicated to %s"
             (if dedicated "no longer " "")
(global-set-key (kbd "<f10>") 'my/toggle-current-window-dedication)

Desktop Save Mode

;; starting Emacs from a directory where you have a saved desktop configuration
;; will restore that configuration, provided that you customize desktop-path to
;; prepend . (the current directory) to the other directories there.
(setq desktop-path '("." "~/.emacs.d" "~"))

;; do not load desktop if it is being used.
(setq desktop-load-locked-desktop nil)

;; Set how much buffer to restore immediately. Remaining buffers are restore
;; lazily when Emacs is idle.
;; (setq desktop-restore-eager 0)

;; Disables because desktop-save-mode
;; - keeps too many buffers in memory
;; - slows down start up graduately
(desktop-save-mode 1)

Tab Bar Mode

I use the tab bar mode to keep important buffers visible. For example, I create a new tab for a frequently used buffer so that I can switch to it real quick.

Note that it is common to use tab bar mode with desktop mode to restore the window configuration. However, I am not using that.

(setq tab-bar-close-button-show nil)
(setq tab-bar-new-button-show nil)

;; hide the tab bar when only one tab. Looks better especially when editting a file with emacsclient.
;; (setq tab-bar-show 1)
;; Show the absolute number of the tab
(setq tab-bar-tab-hints t)
;; Switch to tab by C-?
(setq tab-bar-select-tab-modifiers '(control))

(tab-bar-mode +1)

(global-set-key (kbd "C-<tab>") 'tab-next)

Focus to new Window after Split

I found it is more nature to focus to the new window after splitting.

(defun my/split-window-advice (&rest args) (other-window 1))
(advice-add 'split-window-below :after #'my/split-window-advice)
(advice-add 'split-window-right :after #'my/split-window-advice)

Prefer not to Split a Window Vertically

;; When nil, `split-window-sensibly' is not allowed to split window vertically.
;; e.g., when going to the heading from org-agenda.
(setq split-height-threshold nil)

Hydra Menu

Hydra Consult Menu

Create a hydra menu for the consult commands I use frequently.

(use-package hydra
  :commands defhydra
  (defhydra hydra-consult-menu (:hint nil
                                      :foreign-keys warn
                                      :exit t
                                      :pre (setq which-key-inhibit t)
                                      :post (setq which-key-inhibit nil))
    "===== Consult Menu (F12) =====\n"
    ("f" (my/consult-org-agenda) "Agenda")
    ("r" (consult-recent-file) "Recentf")
    ("q" nil "quit menu" :color blue))
  (global-set-key (kbd "<f8>") 'hydra-consult-menu/body))

Hydra File Menu

A hydra menu to open common files.

Also see https://github.com/abo-abo/hydra/wiki/Hydras-by-Topic.

(use-package hydra
  :commands defhydra
  (defhydra hydra-file-menu (:hint nil
                                   :foreign-keys warn
                                   :exit t
                                   :pre (setq which-key-inhibit t)
                                   :post (setq which-key-inhibit nil))
    ("er" (load-file user-init-file))
    ("ed" (let ((vc-follow-symlinks t)) (find-file (locate-user-emacs-file "dotemacs.org"))) "dotemacs.org")
    ("ep" (let ((vc-follow-symlinks t)) (find-file (locate-user-emacs-file "private.org"))) "private.org")
    ("eg" (let ((vc-follow-symlinks t)) (find-file (locate-user-emacs-file "google.org"))) "google.org")

    ("i" (find-file (my/org-inbox-file)) "inbox.org")
    ("t" (find-file (my/org-tasks-file)) "tasks.org")
    ("d" (find-file (my/org-diary-file)) "diary.org")
    ("n" (find-file (my/org-notes-file)) "notes.org")

    ("w" (find-file "~/org/work.org") "work.org")
    ("D" (find-file "~/org/work/diary.org") "work/diary.org")
    ;; ("T" (find-file "~/org/work/tasks.org") "work/tasks.org")

    ("q" nil "quit menu" :color blue))

  (global-set-key (kbd "C-c e") 'hydra-file-menu/body))

Hydra Snippet Menu

Very often, I want to insert today’s date. There are many ways of doing this.

(defun my/current-date ()
  (concat "[" (shell-command-to-string "echo -n $(date '+%Y-%m-%d %a')") "]"))

;; NOTE: Consider using "org-time-stamp-inactive" if there is a way to
;; avoid the date selection prompt.
(defun my/insert-current-date ()
  (insert (my/current-date)))

(use-package hydra
  :commands defhydra
  (defhydra my/hydra-snippets (:hint nil
                                     :foreign-keys warn
                                     :exit t)
    ("d" (my/insert-current-date) "Current Date (yyyy-mm-dd Aaa)")
    ("q" nil "Quit Menu"))

  (global-set-key (kbd "C-c s") 'my/hydra-snippets/body))


Completion with vertico

(use-package vertico
  (setq vertico-count 25)
  (:map vertico-map
        ([escape] . minibuffer-keyboard-quit)
        ("<prior>" . vertico-scroll-down)
        ("<next>" . vertico-scroll-up)))

;; Persist history over Emacs restarts. Vertico sorts by history position.
(use-package savehist

;; A few more useful configurations...
(use-package emacs
  ;; Add prompt indicator to `completing-read-multiple'.
  ;; We display [CRM<separator>], e.g., [CRM,] if the separator is a comma.
  (defun crm-indicator (args)
    (cons (format "[CRM%s] %s"
                   "\\`\\[.*?]\\*\\|\\[.*?]\\*\\'" ""
                  (car args))
          (cdr args)))
  (advice-add #'completing-read-multiple :filter-args #'crm-indicator)

  ;; Do not allow the cursor in the minibuffer prompt
  (setq minibuffer-prompt-properties
        '(read-only t cursor-intangible t face minibuffer-prompt))
  (add-hook 'minibuffer-setup-hook #'cursor-intangible-mode)

  ;; Emacs 28: Hide commands in M-x which do not work in the current mode.
  ;; Vertico commands are hidden in normal buffers.
  (setq read-extended-command-predicate

  ;; Enable recursive minibuffers
  (setq enable-recursive-minibuffers t))

;; Optionally use the `orderless' completion style.
(use-package orderless
  ;; Configure a custom style dispatcher (see the Consult wiki)
  ;; (setq orderless-style-dispatchers '(+orderless-dispatch)
  ;;       orderless-component-separator #'orderless-escapable-split-on-space)
  (setq completion-styles '(orderless basic)
        completion-category-defaults nil
        completion-category-overrides '((file (styles partial-completion)))))


(use-package consult
  ("C-f" . consult-line)
  ("C-s" . consult-line)
  ("C-b" . consult-bookmark)
  ("C-j" . consult-imenu)
  ("C-o" . consult-outline)
  ("C-r" . consult-recent-file)

  ("C-x b" . consult-buffer)                ;; orig. switch-to-buffer
  ("C-x p b" . consult-project-buffer)      ;; orig. project-switch-to-buffer
  ("M-y" . consult-yank-pop)                ;; orig. yank-pop
  ("M-g g" . consult-goto-line)             ;; orig. goto-line
  (with-eval-after-load "org"
    (define-key org-mode-map (kbd "C-j") #'consult-org-heading)))

Embark & Marginalia

(use-package marginalia
  (setq marginalia-align 'center)

(use-package embark
  (("C->" . embark-act)         ;; pick some comfortable binding
   ("C-h B" . embark-bindings)) ;; alternative for "describe-bindings"

  ;; Optionally replace the key help with a completing-read interface
  (setq prefix-help-command #'embark-prefix-help-command)

  ;; Hide the mode line of the Embark live/completions buffers
  (add-to-list 'display-buffer-alist
               '("\\`\\*Embark Collect \\(Live\\|Completions\\)\\*"
                 (window-parameters (mode-line-format . none)))))

;; Consult users will also want the embark-consult package.
(use-package embark-consult
  (embark-collect-mode . consult-preview-at-point-mode))


which-key displays the key bindings following your currently entered incomplete command (a prefix).

(use-package which-key
  ; (which-key-idle-delay 10000 "Set idle delay to infinite so it never trigger automatically")
  ; (which-key-show-early-on-C-h t "Allow C-h to trigger which-key before it is done automatically.")
  ; (which-key-idle-secondary-delay 0.05)
  (which-key-mode +1 "Non-nil if which-Key mode is enabled"))


Org Files

;; Adding a "/" so that =find-file= finds the files under =~/org/=.
;; The org-directory is computed based on user-emacs-directory.
;; - ".emacs.d" -> "~/org/"
;; - ".emacs.d-personal" -> "~/org-personal/"
(setq org-directory
      (concat "~/org" (nth 1 (split-string user-emacs-directory "emacs.d"))))
(defun my/expand-org-file-name (filename)
  (expand-file-name filename org-directory))

(defun my/org-inbox-file () (my/expand-org-file-name "inbox.org"))
(defun my/org-tasks-file () (my/expand-org-file-name "tasks.org"))
(defun my/org-notes-file () (my/expand-org-file-name "notes.org"))
(defun my/org-diary-file () (my/expand-org-file-name "diary.org"))
(defun my/org-blog-file () (my/expand-org-file-name "blog.org"))
(defun my/org-drill-file () (my/expand-org-file-name "drill.org"))
(defun my/org-calendar-directory () (my/expand-org-file-name ".calendar/"))
(defun my/org-attachment-directory () (my/expand-org-file-name ".attachment/"))
(defun my/org-emacs-config-file () (expand-file-name "dotemacs.org" user-emacs-directory))

Org Basic

(use-package org
  (:map org-mode-map ("C-x n n" . org-toggle-narrow-to-subtree))
  ;; Reserve "C-c <arrow>" for windmove
  (org-mode . (lambda ()
                (local-unset-key (kbd "C-c <left>"))
                (local-unset-key (kbd "C-c <right>"))
                (local-unset-key (kbd "C-c <up>"))
                (local-unset-key (kbd "C-c <down>")))))


(global-set-key (kbd "C-c c") 'org-capture)

;; The default file for capturing.
(setq org-default-notes-file (my/org-inbox-file))

;; Org Capture Templates
;; See https://orgmode.org/manual/Template-elements.html#index-org_002ddefault_002dnotes_002dfile-1
(setq org-capture-templates nil)
 `("i" "Inbox" entry (file ,(my/org-inbox-file))
   "* %?\n%i\n%a"))

 `("p" "Project" entry (file+headline ,(my/org-tasks-file) "Projects")
   (file "~/org/.template/project.org")))

 `("v" "Vocab" entry (file+headline ,(my/org-drill-file) "Translation")
   "* %? :drill:\n\n** Translation\n\n** Definition\n"))

(use-package org-cliplink)


I was using org-download but switched to the built-in org-attach in 2022. I use .dir-locals.el to customize org-attach-id-dir if necessary.

(require 'org-attach)
(setq org-attach-id-dir (my/org-attachment-directory))
(setq org-attach-use-inheritance t)

;; Use timestamp as ID and attachment folder. See https://helpdeskheadesk.net/2022-03-13/
;; (setq org-id-method 'ts)
;; (setq org-attach-id-to-path-function-list
;;       '(org-attach-id-ts-folder-format
;;         org-attach-id-uuid-folder-format))
;; Shorten the Org timestamp ID
;; (setq org-id-ts-format "%Y%m%dT%H%M%S")

Task Management

See this blog post for my Org-Mode workflow for task management.

(setq org-todo-keywords
      '((sequence "TODO(t)" "NEXT(n)" "PROG(p)" "|" "DONE(d)" "CANCELED(c)")))

(setq org-agenda-custom-commands
      '(("n" "Agenda / PROG / TODO"
         ((agenda "" nil)
          (todo "PROG" nil)
          (todo "NEXT" nil))

;; Sets default-directory to org-directory so that =M-x magit= from the agenda view does not ask me for a dir.
(global-set-key (kbd "C-c a")
                (lambda ()
                  (let ((default-directory org-directory)) (org-agenda))))

;; My agenda files.
(setq org-agenda-files (list (my/org-inbox-file) (my/org-tasks-file) (my/org-notes-file) (my/org-calendar-directory)))

;; Trying to use the current window as agenda frame.
(setq org-agenda-window-setup 'current-window)

;; Use sticky agenda since I need different agenda views (personal and work) at the same time.
(setq org-agenda-sticky t)

;; Just today
(setq org-agenda-span 'day)

;; Hide all scheduled todo.
(setq org-agenda-todo-ignore-scheduled 'all)

;; Ignores "far" deadline TODO items from TODO list.
(setq org-agenda-todo-ignore-deadlines 'far)

;; Hide all scheduled todo, from tags search view, like tags-todo.
(setq org-agenda-tags-todo-honor-ignore-options t)

;; Hide all done todo in agenda
(setq org-agenda-skip-scheduled-if-done t)

;; Hide task until the scheduled date.
(setq org-agenda-skip-deadline-prewarning-if-scheduled 'pre-scheduled)

;; Use an indirect buffer after <Tab> (org-agenda-goto) or <Enter> (org-agenda-switch-to).
;; Also see https://emacs.stackexchange.com/a/17822
;; (advice-add 'org-agenda-goto :after
;;             (lambda (&rest args)
;;               (org-tree-to-indirect-buffer)))
;; (advice-add 'org-agenda-switch-to :after
;;             (lambda (&rest args)
;;               (org-tree-to-indirect-buffer)))

;; Narrow to subtree after <Tab> (org-agenda-goto) or <Enter> (org-agenda-switch-to).
;; (advice-add 'org-agenda-goto :after
;;             (lambda (&rest args)
;;               (org-narrow-to-subtree)))
;; (advice-add 'org-agenda-switch-to :after
;;             (lambda (&rest args)
;;               (org-narrow-to-subtree)))

(advice-add 'org-agenda-goto :after
            (lambda (&rest args)
(advice-add 'org-agenda-switch-to :after
            (lambda (&rest args)

(setq org-enforce-todo-dependencies t)

(setq org-log-into-drawer t)
;; (setcdr (assoc 'note org-log-note-headings) "%d")
;; Interstitial Journaling: add note to CLOCK entry after clocking out
;; https://emacs.stackexchange.com/questions/37526/add-note-to-clock-entry-after-clocking-out
(setq org-log-note-clock-out t)

;; 4 priorities to model Eisenhower's matrix.
;; - [#A] means +important +urgent
;; - [#B] means +important -urgent
;; - [#C] means -important +urgent
;; - [#D] means -important -urgent
(setq org-priority-default 68
      org-priority-lowest 68)

;; Include the file name into the path in refile target.
(setq org-refile-use-outline-path 'file)
(setq org-refile-targets
      `((nil :maxlevel . 3)
        (,(my/org-tasks-file) :maxlevel . 2)
        (,(my/org-notes-file) :maxlevel . 3)))
(setq org-outline-path-complete-in-steps nil)

In general,

I wrote some functions to customize the search scopes (e.g., which files to search).

(defun my/consult-org-agenda ()

(setq my/consult-org-files '())
(add-to-list 'my/consult-org-files (my/org-inbox-file) t)
(add-to-list 'my/consult-org-files (my/org-tasks-file) t)
(add-to-list 'my/consult-org-files (my/org-notes-file) t)
(when (file-exists-p (my/org-blog-file))
  (add-to-list 'my/consult-org-files (my/org-blog-file) t))
(when (file-exists-p (my/org-emacs-config-file))
  (add-to-list 'my/consult-org-files (my/org-emacs-config-file) t))

(defun my/consult-org-all ()

(defun my/consult-org-notes ()
   (list (my/org-notes-file))))

(global-set-key (kbd "C-S-j") #'my/consult-org-all)
(global-set-key (kbd "C-S-n") #'my/consult-org-notes)
(global-set-key (kbd "<f1>") #'my/consult-org-all)
(global-set-key (kbd "<f2>") #'my/consult-org-notes)

;; Full text search the whole org directory
(defun my/consult-ripgrep-org-directory ()
  (require 'consult)
  ;; Add "--no-ignore-vcs" to the rg command so todo.org could be searched.
  (let ((consult-ripgrep-args (concat consult-ripgrep-args " --no-ignore-vcs")))
    (consult-ripgrep org-directory "")))

(global-set-key (kbd "C-S-f") #'my/consult-ripgrep-org-directory)

Org Heading Breadcrumb

Inspired by this answer from emacs.stackexchange.com.

(defun my/org-breadcrumbs ()
  "Get the chain of headings from the top level down
    to the current heading."
  (let ((breadcrumbs (org-format-outline-path
                      (org-get-outline-path t)
                      (1- (frame-width))
                      nil " > ")))
    (format "%s" breadcrumbs)))

(defun my/set-header-line-format()
  "Set the header line dynamically."
  (setq header-line-format '(:eval (my/org-breadcrumbs))))

(add-hook 'org-mode-hook #'my/set-header-line-format)

Jump to a Random Org Heading

When organizing all notes in a giant org file, it is useful to review them with this function.

(defun my/org-random-heading ()
  "Jump to a random org heading in the current org file."
  (goto-char (point-min))
  (let ((headings '()))
    (while (re-search-forward "^\\*+ " nil t)
      (push (point) headings))
    (when headings
      (goto-char (nth (random (length headings)) headings))

(with-eval-after-load "org"
  (define-key org-mode-map (kbd "C-c n R") #'my/org-random-heading))

Pulling Google Calendar

I followed https://orgmode.org/worg/org-tutorials/org-google-sync.html to sync Google Calendar to org but not the other way, including a cron job every hour. Also, here is a elisp command to fetch manually.

(defun my/sync-calendar()
  (message "Synchronizing...")
  (shell-command "~/org/.calendar/fetch.sh")
  (message "Synchronized."))

Literate Programming with Org-Babel


 '((emacs-lisp . t) (shell . t) (python . t) (gnuplot . t) (ditaa . t)))

(setq org-edit-src-content-indentation 0)

;; python3
(setq org-babel-python-command "python3")

Auto Tangle

Add #+auto_tangle: t to tangle a file on save.

(use-package org-auto-tangle
  :defer t
  :hook (org-mode . org-auto-tangle-mode))

Inline Latex Fragment

This snippet customize LaTeX Fragments.

;; To enable preview on startup globally
(setq org-startup-with-latex-preview t)

;; Slightly increase the size of the Latex fragment previews.
(setq org-format-latex-options (plist-put org-format-latex-options :scale 1.2))

;; Put the generated image to an absolute directory.
;; A side effect is that all latex images from this shared directory
;; might be copied during exporting.
;; e.g., ox-hugo (https://github.com/kaushalmodi/ox-hugo/issues/723)
;; (setq org-preview-latex-image-directory
;;       (expand-file-name "preview/ltximg/" user-emacs-directory))

Note that this requires installing Latex. For MacOS, install MacTex with brew install --cask mactex.

Pretty Entities

It renders entities as UTF-8 by default. e.g. π, Γ, ∑.

;; 2023-10-13: I prefer using M-x org-toggle-pretty-entities instead.
;; (setq org-pretty-entities t)

Plot Graph with gnuplot

(use-package gnuplot)

See https://github.com/dryman/org-math for the setup and usage.

Preview with org-preview-html

Open an Org file and execute M-x org-preview-html-mode. A preview window opens next to the Org file. See the repo for customization.

(use-package org-preview-html)

Respect Content When Inserting Heading

(setq org-insert-heading-respect-content t)

Also see https://www.n16f.net/blog/org-mode-headline-tips/.


(setq org-clock-mode-line-total 'current)
(setq org-show-notification-timeout 3600)

;; Comment out since I forgot why I added it.
;; (org-clock-auto-clockout-insinuate)

;; Create an indirect buffer for the current clocking task, and focus into it.
(defun my/org-clock-goto ()
  (other-window 1)
(global-set-key (kbd "C-c C-x j") 'my/org-clock-goto)


;; Display the inline image at startup.
(setq org-startup-with-inline-images t)

;; Display the image roughly match the org-tags-column.
;; To customize the width, use "#+ATTR_ORG: :width <new_width>".
(setq org-image-actual-width 600)

See https://orgmode.org/manual/Images.html for more details.


I know there are packages to make Org Mode looks better, like org-bullets and org-modern. I am not using them. The org-indent-mode makes the layout nice and clear enough to me.

;; Enable the =org-indent-mode= by default.
(setq org-startup-indented t)

;; Reduce org-indent-indentation-per-level from 2 to 1.
;; This keeps =org-tags-column= the same for all headings.
;; Avoid inconsistency when eidting outside Emacs, like Beorg.
;; Note that Orgzly has option the customize this variable.
;; (setq org-indent-indentation-per-level 2)

Disable Org Cache

When org element cache is broken for me (causing org-export to run forever),

;; (setq org-element-use-cache nil)

Personal Knowledge Management

Note Taking with denote

(defun my/denote-random-note-from-directory (directory)
  "Open a random denote from a specific denote directory."
  (let* ((denote-directory directory)
         (files (denote-directory-files)))
    (find-file (nth (random (length files)) files))))

(defun my/denote-random-note ()
  "Open a random denote."
  (my/denote-random-note-from-directory denote-directory))

(use-package denote
  ("C-c n n" . 'denote)
  ("C-c n f" . 'denote-open-or-create)
  ("C-c n i" . 'denote-link)
  ("C-c n k" . 'denote-keywords-add)    ;; update file name automatically
  ("C-c n K" . 'denote-keywords-remove) ;; update file name automatically
  ("C-c n u" . 'denote-rename-file-using-front-matter)
  ("C-c n l" . 'denote-link-find-backlink)
  ("C-c n r" . 'my/denote-random-note)
  (setq denote-directory (expand-file-name org-directory))
  (setq denote-known-keywords '("emacs"))
  (setq denote-prompts '(subdirectory title))
  (setq denote-excluded-directories-regexp ".attachment")

  ;; Makes the denote links different from usual link.
  (set-face-attribute 'denote-faces-link
                      nil :foreground "magenta" :inherit 'link)

  ;; Remove the date and the identifier. They are duplicated with the file name.
  ;; I want to remove filetags too but denote-keyword-* need that.
  (setq denote-org-front-matter "#+title: %1$s\n#+filetags: %3$s\n")

  (add-hook 'dired-mode-hook #'denote-dired-mode))

;; allow empty keyword
(defun denote-rename-file-using-front-matter (file &optional auto-confirm)
  (interactive (list (buffer-file-name) current-prefix-arg))
  (when (buffer-modified-p)
    (if (or auto-confirm
            (y-or-n-p "Would you like to save the buffer?"))
      (user-error "Save buffer before proceeding")))
  (unless (denote-file-is-writable-and-supported-p file)
    (user-error "The file is not writable or does not have a supported file extension"))
  (if-let* ((file-type (denote-filetype-heuristics file))
            (title (denote-retrieve-title-value file file-type))
            (extension (file-name-extension file t))
            (id (denote-retrieve-or-create-file-identifier file))
            (dir (file-name-directory file))
            (new-name (denote-format-file-name
                       dir id (denote-retrieve-keywords-value file file-type) (denote-sluggify title) extension)))
      (when (or auto-confirm
                (denote-rename-file-prompt file new-name))
        (denote-rename-file-and-buffer file new-name)
    (user-error "No front matter for title and/or keywords")))

;; (use-package consult-denote
;;   :straight (consult-denote :type git :host codeberg :repo "whhone/consult-denote")
;;   :after denote
;;   :bind
;;   ("C-c n i" . 'consult-denote-link-insert-link)
;;   ("C-c n f" . 'consult-denote-open-or-create)
;;   ("C-c n F" . 'consult-denote-ripgrep))

Blogging with ox-hugo

My blog is generated by Hugo and ox-hugo.

(use-package ox-hugo
  ;; :vc (ox-hugo :url "git@github.com:whhone/ox-hugo.git" :branch "async")
  :after ox
  (setq org-hugo-auto-export-async t))

Exporting Notes

;; Do not export with TOC, e.g., with org-md-export-as-markdown, org-ascii-export-as-ascii
(setq org-export-with-toc nil)

;; (setq org-export-with-section-numbers nil)

Spaced Repetition with org-drill

I use org-drill to enhance my learning, like vocabulary, reading notes, concepts, etc.

;; https://orgmode.org/worg/org-contrib/org-drill.html
(use-package org-drill
  ;; save buffers after drill sessions without prompt.
  (setq org-drill-save-buffers-after-drill-sessions-p nil)
  ;; reduce from the default 30 to make it to become a habit.
  (setq org-drill-maximum-items-per-session 10)
  ("C-c d" . org-drill))

I used Anki before embracing Emacs and Org Mode. Anki gave me access on mobile but I have to sync my data to its server. I migrated to org-drill for a more coherent Emacs workflow. To be fair, it gives me access over ssh :-p.


Google Translate

(use-package google-translate
  (setq google-translate-output-destination 'popup)
  (setq google-translate-default-source-language "en")
  (setq google-translate-default-target-language "zh-TW")
  ("C-c v" . google-translate-at-point))


Spell Checking with flyspell-correct-wrapper

(use-package flyspell-correct
  :after flyspell
  :bind (:map flyspell-mode-map ("C-;" . flyspell-correct-wrapper)))


;; https://www.powerthesaurus.org/
(use-package powerthesaurus
  ("M-`" . powerthesaurus-lookup-word-dwim))

Write Good

The first challenge from Dreyer’s English is to write without weasel words.

(use-package writegood-mode
  (setq writegood-weasel-words
        '("very" "rather" "really" "quite" "in fact" "just" "so" "pretty" "of course" "surely" "that said" "actually")))

Auth Source

I use auth-source to manage secrets, mainly for api keys.

(require 'auth-source)
(add-to-list 'auth-sources "~/.emacs.d/.authinfo")


LLM with llm

(use-package llm
  ;; :vc (llm :url "git@github.com:whhone/llm.git" :branch "streaming")
  ;; :vc (:fetcher github :repo ahyatt/llm)
  (setq llm-warn-on-nonfree nil)
  (require 'llm-openai)
  (setq my/llm-provider-openai
        (make-llm-openai :key (auth-source-pick-first-password :host "api.openai.com")))
  (require 'llm-gemini)
  (setq my/llm-provider-gemini
        (make-llm-gemini :key (auth-source-pick-first-password :host "gemini")))

   '(("Gemini" . my/llm-provider-gemini)
     ("Open AI" . my/llm-provider-openai)))

  (defun my/consult-llm-switch-provider ()
    "Switch the LLM provider."
    (require 'consult)
    (let ((selected (consult--read
                     (mapcar #'car my/llm-providers)
                     :prompt "Switch my LLM provider: "
                     :require-match t)))
      (message "Switched LLM provider to '%s'" selected)
      (setq my/llm-provider (cdr (assoc selected my/llm-providers)))))

  ;; (setq my/llm-provider (cdr (assoc "Gemini" my/llm-providers)))
  (setq my/llm-provider my/llm-provider-openai)
  (setq my/llm-provider my/llm-provider-gemini))

Custom llm functions

(defun my/get-region-string ()
  (unless (region-active-p)
    (user-error "No region active"))
  (buffer-substring (region-beginning) (region-end)))

(defun my/llm-buffer (provider prompt)
  (let ((prompt-info-heading (llm-chat-prompt-to-text prompt)))
    (display-buffer (get-buffer-create "*llm*"))
    (with-current-buffer (get-buffer-create "*llm*")
      (visual-line-mode +1)
      (insert prompt-info-heading)
      (insert "==== THINKING ====\n\n"))
     `(lambda (response)
        (message "partial")
        (with-current-buffer (get-buffer-create "*llm*")
          (insert ,prompt-info-heading)
          (insert "==== PARTIAL ====\n\n")
          (insert response)))
     `(lambda (response)
        (message "full")
        (with-current-buffer (get-buffer-create "*llm*")
          (insert ,prompt-info-heading)
          (insert "==== FULL ====\n\n")
          (insert response)
     (lambda (err msg)
       (message "error")
       (with-current-buffer (get-buffer-create "*llm*")
         (insert ,prompt-info-heading)
         (insert "==== ERROR ==== %S %S" err msg))))))

(defun my/llm-region-with-header (header)
  (interactive "sHeader: ")
  (when (region-active-p)
       ;; Note: adding 'system break Gemini.
       ;; (make-llm-chat-prompt-interaction
       ;;  :role 'system
       ;;  :content "Be brief.")
        :role 'user
        :content (concat header "\n\n" (my/get-region-string))))))))

(defun my/llm-org-heading-with-header (header)
  (interactive "sHeader: ")
    (concat header "\n\n" (my/org-breadcrumbs)))))

;; Explaining

(defun my/llm-explain-org-heading ()
   "Explain the given topic briefly and provides 3 fun facts to help me remembering and learning it:"))

;; Writing

(defun my/llm-write-org-heading ()
   "Write an article for the topic briefly in Markdown:"))

;; (add-to-list 'display-buffer-alist
;;              '("\\*llm\\*"
;;                (display-buffer-reuse-window display-buffer-in-side-window)
;;                (side . right)
;;                (dedicated . t)))


(setq my/llm-headers '())
;; When selected, `my/consult-llm' will ask for the header.
(add-to-list 'my/llm-headers '("*Custom*" . nil))

(add-to-list 'my/llm-headers '("Proofread" . "Proofread the text. Highlight the differences:"))
(add-to-list 'my/llm-headers '("Rewrite Funny" . "Rewrite the text in a funny manner:"))
(add-to-list 'my/llm-headers '("Rewrite Formal" . "Rewrite the text formally:"))
(add-to-list 'my/llm-headers '("Rewrite Concise" . "Rewrite the text concisely:"))
(add-to-list 'my/llm-headers '("Translate to English" . "Translate to English:"))
(add-to-list 'my/llm-headers '("Translate to Chinese" . "Translate to Traditional Chinese:"))
(add-to-list 'my/llm-headers '("Explain with Fun Facts" . "Explain the given topic briefly and provides 3 fun facts to help me remembering and learning it:"))
(add-to-list 'my/llm-headers '("Summerize" . "Summerize the text briefly and list the key highlights:"))
(add-to-list 'my/llm-headers '("Code Explain" . "Please explain the following code:"))
(add-to-list 'my/llm-headers '("Code Refactor" . "Please help me refactor the following code.
   Please reply with the refactoring explanation in English, refactored code, and diff between two versions.
   Please ignore the comments and strings in the code during the refactoring.
   If the code remains unchanged after refactoring, please say 'No need to refactor'."))

(defun my/consult-llm ()
  "Consult llm.

If there is an active region, then act on that. Otherwise, ask the user for the prompt."
  (let ((llm--name (llm-name my/llm-provider)))
    (if (not (region-active-p))
           (format "Enter prompt for %s: " llm--name))))
      (require 'consult)
      (let* ((selected (consult--read
                        (mapcar #'car my/llm-headers)
                        :prompt (format "Select header for %s: " llm--name)
                        :require-match t))
             (header (or (cdr (assoc selected my/llm-headers))
                         (read-string "Custom header: "))))
        (my/llm-region-with-header header)))))

(global-set-key (kbd "M-l") 'my/consult-llm)

Version Control

Diff Highlight with diff-hl

(use-package diff-hl
  ;; :vc (diff-hl :url "git@github.com:whhone/diff-hl.git" :branch "faster")
  ;; Added in https://github.com/dgutov/diff-hl/pull/207
  (setq diff-hl-update-async t)
  (diff-hl-flydiff-mode +1)
  (magit-pre-refresh . diff-hl-magit-pre-refresh)
  (magit-post-refresh . diff-hl-magit-post-refresh))


There are multiple key-binding to trigger magit:

C-x g
C-c g
C-x f
C-x p m
The keybinding from project.el.

Other useful functions:

shows the git log, e.g., magit-log-current, magit-log-buffer-file.

magit-rebase-interactive :

(use-package magit
  (setq magit-define-global-key-bindings 'recommended)
  ;; this binds `magit-project-status' to `project-prefix-map' when
  ;; project.el is loaded.
  (require 'magit-extras))


IDE Layout with Side Windows

;; show shell/compilation buffer in side window
(add-to-list 'display-buffer-alist
               (display-buffer-reuse-window display-buffer-in-side-window)
               (side . bottom)
               (dedicated . t)
               (reusable-frames . visible)
               (window-height . 0.5)))

(setq compilation-scroll-output t)
(add-hook 'compilation-mode-hook 'goto-address-mode)

Terminal with vterm

(use-package vterm
  (define-key vterm-mode-map (kbd "<f1>") nil)
  (define-key vterm-mode-map (kbd "<f2>") nil)
  (define-key vterm-mode-map (kbd "<f3>") nil)
  (define-key vterm-mode-map (kbd "<f4>") nil)
  (define-key vterm-mode-map (kbd "<f5>") nil)
  (define-key vterm-mode-map (kbd "<f6>") nil)
  (define-key vterm-mode-map (kbd "<f7>") nil)
  (define-key vterm-mode-map (kbd "<f8>") nil)
  (define-key vterm-mode-map (kbd "<f9>") nil)
  (define-key vterm-mode-map (kbd "<f10>") nil)
  (define-key vterm-mode-map (kbd "<f11>") nil)
  (define-key vterm-mode-map (kbd "<f12>") nil)
  (define-key vterm-mode-map (kbd "C-b") nil)
  (define-key vterm-mode-map (kbd "C-p") nil)

  (setq vterm-shell (if (eq system-type 'darwin) "zsh" "bash"))
  (setq vterm-tramp-shells '(("docker" "/bin/sh")
                             ("ssh" "/bin/bash")
                             ("sshx" "/bin/bash")))
  (vterm-mode . goto-address-mode))

(use-package vterm-toggle
  ;; show vterm buffer in side window
  (add-to-list 'display-buffer-alist
                 (display-buffer-reuse-window display-buffer-in-side-window)
                 (side . bottom)
                 (dedicated . t)
                 (reusable-frames . visible)))
  ("s-<return>" . vterm-toggle)
  ("C-`" . vterm-toggle)
  ("C-c t" . vterm-toggle))

Make Script Files Executable Automatically

Make script files (with shebang like #!/bin/bash, #!/bin/sh) executable automatically. See this blog post from Emacs Redux.

(add-hook 'after-save-hook

Kotlin Mode

(use-package kotlin-mode)


(use-package yaml-mode)

Web Mode

https://web-mode.org/ is an autonomous major-mode for editing web templates.

(use-package web-mode
  (add-to-list 'auto-mode-alist '("\\.html\\'" . web-mode))

  ;; TODO: Use .dir.local because not all .html are go template
  (setq web-mode-engines-alist
    '(("go" . "\\.html\\'"))))

Markdown Mode

(use-package markdown-mode
  (:map markdown-mode-map ("M-<left>" . markdown-promote))
  (:map markdown-mode-map ("M-<right>" . markdown-demote))
  (:map markdown-mode-map ("M-S-<left>" . markdown-promote-subtree))
  (:map markdown-mode-map ("M-S-<right>" . markdown-demote-subtree)))

Caddyfile Mode

(use-package caddyfile-mode
  :mode (("Caddyfile\\'" . caddyfile-mode)))

Company Mode

(use-package company)


(use-package eglot
  (define-key eglot-mode-map
    [remap xref-find-definitions] #'eglot-find-typeDefinition)
  (define-key eglot-mode-map
    [remap xref-find-references] #'eglot-find-declaration)
  (define-key eglot-mode-map (kbd "M-l r") 'eglot-rename)
  (define-key eglot-mode-map (kbd "M-l f") 'eglot-format)

  (add-hook 'c++-mode-hook 'eglot-ensure))

Make Script Files Executable Automatically

Make script files (with shebang like #!/bin/bash, #!/bin/sh) executable automatically. See this blog post from Emacs Redux.

(add-hook 'after-save-hook

Competitive Programming

Auto Insert the C++ Template

(setq auto-insert-directory (expand-file-name "auto-insert/" user-emacs-directory))

(define-auto-insert "\.cpp" "template.cpp")

;; Uncomment to enable auto-insert-mode globally. Otherwise, use "M-x
;; auto-insert" on demand.
;; (auto-insert-mode)

Compile and Run

See https://codeforces.com/blog/entry/101292.

(defun my/compile-and-run()
  (if (eq major-mode 'c++-mode)
    (let* ((src (file-name-nondirectory (buffer-file-name)))
           (exe (file-name-sans-extension src)))
      (compile (concat "g++ -std=c++17 -O2 -Wall -Wno-sign-compare " src " -o /tmp/" exe " && time /tmp/" exe " < /tmp/input.txt" )))

(global-set-key (kbd "<f12>") 'my/compile-and-run)

Project Management


Note: Run project-forget-zombie-projects to remove deleted project directories.

project-prefix-map is bind to C-x p by default. (it seems no way to change it)

;; Use the entire "project-prefix-map" in "project-switch-project".
(setq project-switch-use-entire-map t)

Find File (a) in All Known Project

I particularly love the handy projectile function projectile-find-file-in-known-project and adding that function to project.el below.

(defun my/project-all-project-files ()
  "Get a list of all files in all known projects."
   (lambda (project)
     (when (file-exists-p project)
       (mapcar (lambda (file)
                 (expand-file-name file project))
               (project-files (project-current nil project)))))

(defun my/project-find-file-in-known-projects ()
  "Find a file from all known projects."
  (let* ((completion-ignore-case read-file-name-completion-ignore-case)
         ;; Note that "project--read-file-cpd-relative" is broken for
         ;; this function since Emacs 29. Instead of using
         ;; "project-read-file-name-function", always use
         ;; "project--read-file-absolute".
         (file (project--read-file-absolute
                "Find file in known projects" (my/project-all-project-files) nil nil
                (thing-at-point 'filename))))
    (if (string= file "")
        (user-error "You didn't specify the file")
      (find-file file))))

(define-key project-prefix-map (kbd "a") #'my/project-find-file-in-known-projects)

Full Text Search (g) in Current Project Files

(defun my/consult-ripgrep-current-project ()
  "Full text search with ripgrep in current project"
  (consult-ripgrep (if (project-current) (project-root (project-current))
                     default-directory) ""))
(define-key project-prefix-map (kbd "g") #'my/consult-ripgrep-current-project)

Chinese Support

Rime Input Method

See https://github.com/DogLooksGood/emacs-rime for the setup instruction.

Use C-\ (toggle-input-method) to toggle the input method. Run M-x rime-open-configuration to open the default.custom.yaml under rime-user-data-dir.

(use-package rime
  (when (eq system-type 'darwin)
    ;; Set the root for librime ("rime-api.h").
    ;; See https://github.com/DogLooksGood/emacs-rime/blob/master/INSTALLATION.org
    ;; 1. need to download a zip of rime for osx
    ;; 2. unzip it to ~/.emacs.d/librime/dist
    (setq rime-librime-root (expand-file-name "librime/dist" user-emacs-directory))

    ;; Set the root for emacs module ("emacs-module.h")
    ;; (setq rime-emacs-module-header-root "/opt/homebrew/opt/emacs-head@29/include/")
    (setq rime-emacs-module-header-root "/Applications/Emacs.app/Contents/Resources/include"))

  (setq default-input-method "rime")
  (rime-show-candidate 'posframe)
  (rime-posframe-style 'vertical))

CJK Word Wrap

Emacs 28 adds better word wrap / line break support for CJK. See Emacs 28 新特性介绍.

(setq word-wrap-by-category t)

Better CJK Font

cnfonts is a tool for configuring the fonts used in Emacs.

(use-package cnfonts
  (setq cnfonts-profiles (if (eq system-type 'darwin) '("osx") '("hack")))
  (setq cnfonts-default-fontsize 11)
  (cnfonts-mode 1))

GnuPG Passphrase Via Minibuffer

GnuPG could be used when signing git commit with GPG in Magit over the SSH.

See https://elpa.gnu.org/packages/pinentry.html for the setup steps. It requires adding allow-emacs-pinentry to the ~/.gnupg/gpg-agent.conf.

(use-package pinentry
  ;; Redirects all pinentry queries to the caller, so Emacs can query passphrase
  ;; through the minibuffer, instead of external pinentry program, like Gnome
  ;; Keyring. e..g, this makes plstore (org-gcal) asks password in minibuffer.
  (setq epg-pinentry-mode 'loopback)

Mac OS (Command: “M”, Option: “A”)

This preserves the Emacs’s bindings closer to Linux by setting the mac-*-modifier.

;; These are some key bindings ported from MacOS to everywhere, since
;; I found they are handy.

;; MacOS uses Command+f for "find".
(global-set-key (kbd "M-f") 'consult-line)
(global-set-key (kbd "M-F") 'my/consult-ripgrep-org-directory)

;; MacOS uses Command+s for "save".
(global-set-key (kbd "M-s") #'save-buffer)
(with-eval-after-load "org-agenda"
  (define-key org-agenda-mode-map (kbd "M-s") #'org-save-all-org-buffers))

;; MacOS uses Command+c to copy but I prefer keeping the Emacs style.
;; Disable it in case I mistrigger "capitalize-word".
(global-unset-key (kbd "M-c"))

(when (eq system-type 'darwin)
  ;; MacOS put the menu-bar in the top bar which already using the space.
  (menu-bar-mode 1)

  (setq mac-option-modifier 'alt)
  (setq mac-command-modifier 'meta)

  (global-set-key (kbd "<home>") 'move-beginning-of-line)
  (global-set-key (kbd "<end>") 'move-end-of-line)

  ;; MacOS uses Command+Control+f to toggle fullscreen. Also make it
  ;; work with Emacs.
  (global-set-key (kbd "C-M-f") 'toggle-frame-fullscreen)

  ;; MacOS uses Option+up/down to scroll.
  (global-set-key (kbd "A-<up>") 'scroll-down-command)
  (global-set-key (kbd "A-<down>") 'scroll-up-command)

  ;; (global-set-key (kbd "M-p") 'execute-extended-command)
  ;; (global-set-key (kbd "M-x") 'kill-region) ; already bind for s-x
  ;; sets fn-delete to be right-delete
  (global-set-key [kp-delete] 'delete-char)

  (defun my/apply-theme (appearance)
    "Load theme, taking current system APPEARANCE into consideration."
    ;; (mapc #'disable-theme custom-enabled-themes)
    (pcase appearance
      ('light (modus-themes-select 'modus-operandi))
      ('dark (modus-themes-select 'modus-vivendi-tinted))))

  (add-hook 'ns-system-appearance-change-functions #'my/apply-theme))

Personal Information

(setq user-mail-address "whhone@gmail.com"
      user-full-name "Wai Hon Law")

Setting Environment Variables

By setting the PATH variable, commands are available for Emacs (org babel, eshell, etc).

(defun my/add-to-path-env (path)
  "Add `path' to the environment variable PATH."
  (let* ((env-path (getenv "PATH"))
         (paths (split-string env-path ":")))
    (when (and (file-exists-p path)
               (not (member path paths)))
      (setenv "PATH" (concat env-path ":" path)))))

;; Android SDK
(my/add-to-path-env (expand-file-name
                     (getenv "HOME")))

Load Private Config

;; private emacs config
(let ((vc-follow-symlinks t))
  (org-babel-load-file (concat user-emacs-directory "private.org")))