125 KiB
Emacs configuration
- Introduction
- Basics
- Custom functionality
- Aesthetics
- Core packages
- Small packages
- Applications
- Text modes
- Programming packages
- Org mode
- Languages
#+latex_header:\usepackage[margin=1.0in]{geometry}
Introduction
Welcome to my Emacs configuration. You may be confused by the fact it's a readable document with prose rather than just code; this file serves as both documentation and code. The essential idea is that I can explain my ideas in prose then provide the code as a block.
Here's an example of some Emacs Lisp code:
;;; config.el --- Compiled configuration from config.org -*- lexical-binding: t; -*-
;; Copyright (C) 2024 Aryadev Chavali
;; Author: Aryadev Chavali <aryadev@aryadevchavali.com>
;; This program is distributed in the hope that it will be useful, but WITHOUT
;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
;; FOR A PARTICULAR PURPOSE. See the MIT License for details.
;; You may distribute and modify this code under the terms of the MIT License,
;; which you should have received a copy of along with this program. If not,
;; please go to <https://opensource.org/license/MIT>.
;;; Commentary:
;; Welcome to my Emacs configuration. This file is considered volatile i.e. any
;; edits made to this file will be overwritten if and when the configuration is
;; compiled.
;; To propagate edits from this file back to the literate document, call
;; (org-babel-detangle).
;;; Code:
This allows the document to act as both source code and documentation at once. Pretty cool, right? This style of coding is called literate programming. Donald Knuth really liked the idea. I mainly utilise this to explain my decisions for configuring or using certain packages: Emacs is an opinionated piece of software and I may as well express my opinions somewhere.
Sections tagged WAIT are not compiled and are, hence, unused.
Usually I provide some reasoning as to why. If using Emacs, the code
in any one section may be loaded interactively (in case I need it
immediately). A lot of code here is essentially write and forget;
nothing needs to change unless I find a more efficient way to do
things.
Some sections border on blog posts justifying why I think they're good
applications or giving some greater reasoning about my specific
configuration of a package. That can be distracting, so reading the
produced file may be more helpful for you. Use org-babel-tangle in
Emacs to do so, or ask me very nicely.
Basics
Let's setup a few absolute essentials:
- My name and mail address
- File encoding (no "\r" characters at the end of lines, please)
- Where to store backup files (
backup-directory-alist) - Auto refresh buffers when a change occurs (
auto-revert-mode) - Yes or no questions can be less painful (
y-or-n-p) - Make the "kill ring" work seamlessly with the clipboard
- deleting files or directories "trashes" them instead
(use-package emacs
:demand t
:init
(setq user-full-name "Aryadev Chavali"
user-mail-address "aryadev@aryadevchavali.com"
buffer-file-coding-system 'utf-8-unix
save-buffer-coding-system 'utf-8-unix
backup-directory-alist `(("." . ,(no-littering-expand-var-file-name "saves/")))
global-auto-revert-non-file-buffers t
auto-revert-verbose nil
auto-revert-use-notify nil
select-enable-clipboard t
delete-by-moving-to-trash t)
:config
(fset 'yes-or-no-p 'y-or-n-p)
(global-auto-revert-mode))
Custom functionality
This is custom Lisp I've written to help me out throughout the configuration. Note that because it's setup so early I can use it throughout the file.
Procedure
An anonymous function (lambda) which takes no arguments is a
procedure. This macro generates procedures, with the parameters of
the macro being the body of the procedure. It returns it in quoted
form (as data rather than code), as that is the most common use of
this macro.
(defmacro proc (&rest BODY)
"For a given list of forms BODY, return a quoted 0 argument
lambda."
`(function (lambda nil ,@BODY)))
Automatically run a command on saving
Define a macro which creates hooks into after-save-hook. On certain
conditions being met, to-run is evaluated. Classic example use
case: compiling on save.
(use-package simple
:defer t
:config
(defmacro create-auto-save (conditions &rest to-run)
"Create a hook for after saves, where on CONDITIONS being met
TO-RUN is evaluated."
`(add-hook 'after-save-hook
(proc
(interactive)
(when ,conditions ,@to-run)))))
Clean buffer list
Clean all buffers except for those in clean-buffers-keep.
(defconst clean-buffers-keep
(list "config.org" "*scratch*"
"*dashboard*" "*Messages*"
"*Warnings*" "*eshell*")
"List of buffer names to preserve.")
(defun clean-buffers ()
"Kill all buffers except any with names in CLEAN-BUFFERS-KEEP."
(interactive)
(let ((should-not-kill
#'(lambda (buf)
(member (buffer-name buf)
clean-buffers-keep))))
(mapc #'kill-buffer
(cl-remove-if should-not-kill (buffer-list)))))
Custom window management
Generally speaking, applications that have a windowing concept do not have a lot of options for how those windows are placed. Emacs has a window management system unlike any other piece of software I have ever used, with some complexity but incredible capability.
The big idea is this table (alists are basically just tables),
display-buffer-alist, which associates regular expressions with
"actions". The regular expressions are for the name of buffers, and
the actions are how the buffer should be displayed. And there are a
lot of ways to display buffers.
Here's an example record:
'("config.org"
(display-buffer-in-side-window)
(side . bottom))
This matches any buffer named config.org, displaying the buffer in a
side window to the bottom.
What I configure here is a use-package keyword, :display, which
will allow me to write associations to display-buffer-alist really
easily.
2024-04-23: Found this option switch-to-buffer-obey-display-actions
which makes manual buffer switches obey the same constraints via
display-buffer-alist as creating the buffer automatically.
(use-package window
:demand t
:init
(setq switch-to-buffer-obey-display-actions nil)
(with-eval-after-load "use-package-core"
(add-to-list 'use-package-keywords ':display)
(defun use-package-normalize/:display (_name-symbol _keyword args)
"Normalise args for use in handler. Don't do anything to the args
here."
args)
(defun use-package-handler/:display (name _keyword args rest state)
(use-package-concat
(use-package-process-keywords name rest state)
(mapcar
#'(lambda (arg)
`(add-to-list 'display-buffer-alist
',arg))
args)))))
Here's some :display records for buffers that don't really have
configuration anywhere else in the file. Good examples as well on how
to use the keyword.
(use-package window
:defer t
:display
("\\*Process List\\*"
(display-buffer-at-bottom)
(window-height . 0.25))
("\\*Async Shell Command\\*"
(display-buffer-at-bottom)
(window-height . 0.25)))
add-to-list multiple times
I want to be able to add multiple items to a list. Here's a macro to do that for me.
(defmacro add-multiple-to-list (listvar &rest elements)
(cons
'progn
(cl-loop for element in elements
collect `(cl-pushnew ,element ,listvar))))
Setting number of native jobs
Emacs has a native compilation capability to make things even faster. In early-init.el I set the number of native-workers to 4, which isn't necessarily optimal when loading/compiling the rest of this file depending on the machine I use. On my machines, which have 8 process throughput (4 core + hyperthreading), 6-7 workers makes much more sense. On a machine I've never used before, 3 seems to be a reasonable default.
(use-package comp
:init
(setq native-comp-async-jobs-number
(pcase (system-name)
((or "ravenmaiden" "oldboy") 6)
(_ 3))))
Aesthetics
General look and feel of Emacs (mostly disabling stuff I don't like).
Themes
I have both a dark and light theme for differing situations. Here I configure a timer which ensures I have a light theme during the day and dark theme at night. I wrote my own themes by copying stuff I like from other themes then modifying them. The dark theme is in this file and the light theme is in this file.
(use-package custom
:defer t
:commands (+oreo/load-theme)
:hook (after-init-hook . +oreo/load-theme)
:init
(setq custom-theme-directory (concat user-emacs-directory "elisp/"))
(defvar +oreo/theme-list `(personal-light personal-solarized))
(defvar +oreo/theme 1)
:config
(defun +oreo/disable-other-themes ()
"Disable all other themes in +OREO/THEME-LIST excluding
+OREO/THEME."
(cl-loop
for theme in +oreo/theme-list
for i from 0
if (not (= i +oreo/theme))
do (disable-theme theme)))
(defun +oreo/load-theme ()
"Load +OREO/THEME, disabling all other themes to reduce conflict."
(mapc #'disable-theme custom-enabled-themes)
(+oreo/disable-other-themes)
(load-theme (nth +oreo/theme +oreo/theme-list) t))
(defun +oreo/switch-theme ()
"Flip between different themes set in +OREO/THEME-ALIST."
(interactive)
(setq +oreo/theme (mod (+ 1 +oreo/theme) (length +oreo/theme-list)))
(+oreo/load-theme))
(+oreo/load-theme))
Font size
Adjust font sizes for my devices.
(use-package faces
:defer t
:config
(set-face-attribute 'default nil :height
(pcase (system-name)
("newboy" 145)
("ravenmaiden" 135)
(_ 130))))
Startup screen
The default startup screen is quite bad in all honesty. While for a first time user it can be very helpful in running the tutorial and finding more about Emacs, for someone who's already configured it there isn't much point.
The scratch buffer is created at boot. When the splash screen isn't
enabled, it is the first buffer a user sees. By default, it is in
lisp-interaction-mode, which allows one to prototype Emacs Lisp
code.
I mostly use the scratch buffer to hold snippets of code and to write
text (usually then copy-pasted into other applications). So
text-mode is a good fit for that.
2024-06-04: I use to load org-mode in the scratch buffer and it added 2 seconds of load time, so let's just use fundamental mode and call it a day.
(use-package emacs
:defer t
:init
(setq inhibit-startup-screen t
inhibit-startup-echo-area-message user-login-name
initial-major-mode 'text-mode
initial-scratch-message ""
ring-bell-function 'ignore)
:config
(add-hook
'emacs-startup-hook
(proc
(with-current-buffer "*scratch*"
(goto-char (point-max))
(insert
(format
"Emacs v%s - %s\n\n"
emacs-version (emacs-init-time)))))))
Blinking cursor
Configure the blinking cursor.
(use-package frame
:defer t
:init
(setq blink-cursor-delay 0.2)
:config
(blink-cursor-mode))
Mode line
The mode line is the little bar at the bottom of the buffer, just above the minibuffer. It can store essentially any text, but generally details about the current buffer (such as name, major mode, etc) is placed there.
The default mode-line is… disgusting. It displays information in an unintelligible format and seems to smash together a bunch of information without much care for ordering. Most heartbreaking is that anything can seemingly append new information to it without any purview, which is REALLY annoying. It can be very overstimulating to look at, without even being that immediately informative.
I've got a custom Emacs lisp package (here) which sets up the default mode line as a set of 3 segments: left, centre and right. It pads out the mode line with space strings to achieve this.
(use-package better-mode-line
:load-path "elisp/"
:demand t
:init
(defun +mode-line/evil-state ()
"Returns either the empty string if no evil-state is defined or
the first character of the evil state capitalised"
(with-eval-after-load "evil"
(if (bound-and-true-p evil-state)
(upcase
(substring
(format "%s"
evil-state)
0 1))
"")))
(setq better-mode-line/left-segment
'(" " ;; Left padding
(:eval
(when (mode-line-window-selected-p)
'("%l:%c" ;; Line and column count
" "
"%p" ;; Percentage into buffer
("[" ;; Evil state
(:eval
(+mode-line/evil-state))
"]")))))
better-mode-line/centre-segment
'("%+" ;; Buffer state (changed or not)
"%b" ;; Buffer name
"(" ;; Major mode
(:eval (format "%s" major-mode))
")")
better-mode-line/right-segment
'((:eval
(when (mode-line-window-selected-p)
(if (project-current) ;; Name of current project (if any)
(concat
(project-name (project-current))
" "
vc-mode ;; Git branch
))))
mode-line-misc-info ;; Any other information
(:eval ;; Compilation mode errors
(if (eq major-mode 'compilation-mode)
compilation-mode-line-errors))
" " ;; Right padding
))
:config
(better-mode-line/setup-mode-line))
Fringes
Turning off borders in my window manager was a good idea, so turn off the borders for Emacs, so called fringes. However, some things like Compilation Mode do require fringes to provide arrows. So I use a minimal fringe style (exactly 1 pixel on either side of the window) to ensure I get those.
(use-package fringe
:demand t
:config
(set-fringe-style (cons 1 1)))
Mouse
Who uses a mouse? This disables the use of GUI dialogues for stuff.
(setq-default use-file-dialog nil
use-dialog-box nil)
Scrolling
When scrolling, editors generally try to keep the cursor on screen. Emacs has some variables which ensure the cursor is a certain number of lines above the bottom of the screen and below the top of the screen when scrolling. Here I set the margin to 8 (so it'll start correcting at 8) and scroll-conservatively to the same value so it'll keep the cursor centred.
(use-package emacs
:init
(setq scroll-conservatively 8
scroll-margin 8))
Core packages
Core packages required when configuring the other stuff.
General - Bindings package
Vanilla Emacs has the bind-key function (and the bind-key* macro)
for this, but Evil has it's own evil-define-key. I'd
like a unified interface for using both, which is why I use general.
General provides a set of very useful macros for defining keys in a
variety of different situations. One may redefine any key in any
keymap, bind over different Evil states, add which-key
documentation, create so-called "definers" which act as wrapper macros
over some pre-defined configuration, etc, all at the same time.
Here I setup the rough outline of how bindings should be made in the global scope, namely:
- Use "SPC" as a "leader", the root of all general bindings
- Use "\" as a local-leader, the root of all major mode specific bindings
- A few "definers" for the different sub bindings for the leader key
nmmapmacro, for defining keys under both normal and motion states.
(use-package general
:straight t
:demand t
:config
;; General which key definitions for leaders
(general-def
:states '(normal motion)
"SPC" 'nil
"\\" '(nil :which-key "Local leader")
"SPC a" '(nil :which-key "Applications")
"SPC b" '(nil :which-key "Buffers")
"SPC c" '(nil :which-key "Code")
"SPC d" '(nil :which-key "Directories")
"SPC f" '(nil :which-key "Files")
"SPC i" '(nil :which-key "Insert")
"SPC m" '(nil :which-key "Modes")
"SPC r" '(nil :which-key "Tabs")
"SPC s" '(nil :which-key "Search")
"SPC t" '(nil :which-key "Shell")
"SPC q" '(nil :which-key "Quit/Literate"))
(general-create-definer leader
:states '(normal motion)
:keymaps 'override
:prefix "SPC")
(general-create-definer local-leader
:states '(normal motion)
:prefix "\\")
(general-create-definer code-leader
:states '(normal motion)
:keymaps 'override
:prefix "SPC c")
(general-create-definer file-leader
:states '(normal motion)
:keymaps 'override
:prefix "SPC f")
(general-create-definer shell-leader
:states '(normal motion)
:keymaps 'override
:prefix "SPC t")
(general-create-definer tab-leader
:states '(normal motion)
:keymaps 'override
:prefix "SPC r")
(general-create-definer mode-leader
:states '(normal motion)
:keymaps 'override
:prefix "SPC m")
(general-create-definer app-leader
:states '(normal motion)
:keymaps 'override
:prefix "SPC a")
(general-create-definer search-leader
:states '(normal motion)
:keymaps 'override
:prefix "SPC s")
(general-create-definer buffer-leader
:states '(normal motion)
:keymaps 'override
:prefix "SPC b")
(general-create-definer quit-leader
:states '(normal motion)
:keymaps 'override
:prefix "SPC q")
(general-create-definer insert-leader
:states '(normal motion)
:keymaps 'override
:prefix "SPC i")
(general-create-definer dir-leader
:states '(normal motion)
:keymaps 'override
:prefix "SPC d")
(general-create-definer general-nmmap
:states '(normal motion))
(defalias 'nmmap #'general-nmmap)
(general-evil-setup t))
Some binds for Emacs
Here are some bindings for Emacs using general and the definers created previously. Here I bind stuff I don't care to make a separate heading for, so it serves as both a dumping ground and as a great set of examples on how to use general.
(use-package emacs
:general
("C-x d" #'delete-frame)
(nmmap
"M-;" #'eval-expression
"g=" #'align-regexp
"C--" #'text-scale-decrease
"C-=" #'text-scale-increase
"C-+" #'text-scale-adjust)
(leader
"SPC" '(execute-extended-command :which-key "M-x")
"R" `(revert-buffer :which-key "Revert buffer")
"p" `(,project-prefix-map :which-key "Project")
"'" '(browse-url-emacs :which-key "Download URL to Emacs")
":" `(,(proc (interactive) (switch-to-buffer "*scratch*"))
:which-key "Switch to *scratch*")
"!" '(async-shell-command :which-key "Async shell command")
"h" '(help-command :which-key "Help"))
(mode-leader
"T" #'+oreo/switch-theme)
(code-leader
"F" `(,(proc (interactive) (find-file "~/Code/"))
:which-key "Open ~/Code/"))
(file-leader
"f" #'find-file
"F" #'find-file-other-window
"t" #'find-file-other-tab
"v" #'add-file-local-variable
"s" #'save-buffer)
(dir-leader
"v" #'add-dir-local-variable)
(buffer-leader
"b" #'switch-to-buffer
"d" #'kill-current-buffer
"c" #'kill-buffer-and-window
"K" #'kill-buffer
"j" #'next-buffer
"k" #'previous-buffer
"D" '(clean-buffers :which-key "Kill most buffers"))
(quit-leader
"q" #'save-buffers-kill-terminal
"c" #'+literate/compile-config
"C" #'+literate/clean-config
"l" #'+literate/load-config))
Evil - Vim emulation
My editor journey started off with Vim rather than Emacs, so my brain has imprinted on its style. Emacs is super extensible so there exists a package for porting Vim's modal editing style to Emacs, called evil (Emacs Vi Layer).
However there are a lot of packages in Vim that provide greater functionality, for example tpope's "vim-surround". Emacs has these capabilities out of the box, but there are further packages which integrate them into Evil.
Evil core
Setup the evil package, with some opinionated keybindings:
- Switch
evil-upcaseandevil-downcasebecause I useevil-upcasemore - Switch
evil-goto-markandevil-goto-mark-lineas I'd rather have the global one closer to the home row -
Use 'T' character as an action for "transposing objects"
- Swapping any two textual "objects" seems like a natural thing in Vim considering the "verb-object" model most motions follow, but by default it doesn't have the capabilities. But Emacs can.
(use-package evil
:straight t
:demand t
:general
(leader
"w" '(evil-window-map :which-key "Window")
"wT" #'window-swap-states
"wd" #'evil-window-delete
"w;" #'make-frame)
(nmmap
"K" #'man
"TAB" #'evil-jump-item
"r" #'evil-replace-state
"zC" #'hs-hide-level
"zO" #'hs-show-all
"'" #'evil-goto-mark
"`" #'evil-goto-mark-line)
(general-def
:keymaps 'override
:states '(normal motion visual)
"gu" #'evil-upcase
"gU" #'evil-downcase
"M-y" #'yank-pop
"T" nil)
(general-def
:keymaps 'override
:states '(normal motion visual)
:infix "T"
"w" #'transpose-words
"c" #'transpose-chars
"s" #'transpose-sentences
"p" #'transpose-paragraphs
"e" #'transpose-sexps
"l" #'transpose-lines)
:init
(setq evil-want-keybinding nil
evil-split-window-below t
evil-vsplit-window-right t
evil-move-beyond-eol t
evil-want-abbrev-expand-on-insert-exit t
evil-undo-system #'undo-tree
evil-want-minibuffer t)
:config
(evil-mode))
Evil surround
Evil surround is a port for vim-surround.
(use-package evil-surround
:after evil
:straight t
:config
(global-evil-surround-mode))
Evil commentary
Allows generalised commenting of objects easily.
(use-package evil-commentary
:after evil
:straight t
:config
(evil-commentary-mode))
Evil multi cursor
Setup for multi cursors in Evil mode. Don't let evil-mc setup it's own keymap because it uses 'gr' as its prefix, which I don't like.
(use-package evil-mc
:after evil
:straight t
:init
(defvar evil-mc-key-map (make-sparse-keymap))
:general
(nmap
:infix "gz"
"m" 'evil-mc-make-all-cursors
"u" 'evil-mc-undo-last-added-cursor
"q" 'evil-mc-undo-all-cursors
"s" 'evil-mc-pause-cursors
"r" 'evil-mc-resume-cursors
"f" 'evil-mc-make-and-goto-first-cursor
"l" 'evil-mc-make-and-goto-last-cursor
"h" 'evil-mc-make-cursor-here
"j" 'evil-mc-make-cursor-move-next-line
"k" 'evil-mc-make-cursor-move-prev-line
"N" 'evil-mc-skip-and-goto-next-cursor
"P" 'evil-mc-skip-and-goto-prev-cursor
"n" 'evil-mc-skip-and-goto-next-match
"p" 'evil-mc-skip-and-goto-prev-match
"I" 'evil-mc-make-cursor-in-visual-selection-beg
"A" 'evil-mc-make-cursor-in-visual-selection-end
"d" #'evil-mc-make-and-goto-next-match)
:config
(global-evil-mc-mode))
Evil collection
Provides a community based set of keybindings for most modes in Emacs. I don't necessarily like all my modes having these bindings though, as I may disagree with some. So I use it in a mode to mode basis.
(use-package evil-collection
:straight t
:after evil)
Evil number
Increment/decrement a number at point like Vim does, but use bindings that don't conflict with Emacs default.
(use-package evil-numbers
:straight t
:defer t
:general
(nmmap
"+" #'evil-numbers/inc-at-pt
"-" #'evil-numbers/dec-at-pt))
Text Completion
Emacs is a text based interface. Completion is its bread and butter in providing good user experience. By default Emacs provides 'completions-list' which produces a buffer of options which can be searched and selected. We can take this further though!
Ivy and Helm provide more modern interfaces, though Helm is quite heavy. Ivy, on the other hand, provides an interface similar to Ido with less clutter and better customisation options.
WAIT Ivy
Setup for ivy, in preparation for counsel. Turn on ivy-mode just after init.
Setup vim-like bindings for the minibuffer ("M-(j|k)" for down|up the selection list).
(use-package ivy
:straight t
:demand t
:display
("\\*ivy-occur.*"
(display-buffer-at-bottom)
(window-height . 0.25))
:general
(:keymaps 'ivy-minibuffer-map
"C-j" #'ivy-yank-symbol
"M-j" #'ivy-next-line-or-history
"M-k" #'ivy-previous-line-or-history
"C-SPC" #'ivy-occur)
(:keymaps 'ivy-switch-buffer-map
"M-j" #'ivy-next-line-or-history
"M-k" #'ivy-previous-line-or-history)
(nmap
:keymaps '(ivy-occur-mode-map ivy-occur-grep-mode-map)
"RET" #'ivy-occur-press-and-switch
"J" #'ivy-occur-press
"gr" #'ivy-occur-revert-buffer
"q" #'quit-window
"D" #'ivy-occur-delete-candidate
"W" #'ivy-wgrep-change-to-wgrep-mode
"{" #'compilation-previous-file
"}" #'compilation-next-file)
:init
(with-eval-after-load "evil"
(evil-set-initial-state 'ivy-occur-mode 'normal)
(evil-set-initial-state 'ivy-occur-grep-mode 'normal))
(setq ivy-height 8
ivy-height-alist nil
ivy-wrap t
ivy-fixed-height-minibuffer t
ivy-use-virtual-buffers nil
ivy-virtual-abbreviate 'full
ivy-on-del-error-function #'ignore
ivy-use-selectable-prompt t)
:config
(ivy-mode 1))
WAIT Counsel
Setup for counsel. Load as late as possible, after ivy force requires it.
(use-package counsel
:straight t
:after ivy
:general
(search-leader
"s" #'counsel-grep-or-swiper
"R" #'counsel-rg)
(file-leader
"r" #'counsel-recentf)
(insert-leader
"c" #'counsel-unicode-char)
([remap describe-bindings] #'counsel-descbinds
[remap load-theme] #'counsel-load-theme)
:config
(setq ivy-initial-inputs-alist '((org-insert-link . "^"))
counsel-describe-function-function #'helpful-callable
counsel-describe-variable-function #'helpful-variable
counsel-grep-swiper-limit 1500000
ivy-re-builders-alist '((swiper . ivy--regex-plus)
(counsel-grep-or-swiper . ivy--regex-plus)
(counsel-rg . ivy--regex-plus)
(t . ivy--regex-ignore-order)))
(counsel-mode 1))
Completions-list
In case I ever use the completions list, some basic commands to look around.
(use-package simple
:after evil
:general
(nmmap
:keymaps 'completion-list-mode-map
"l" #'next-completion
"h" #'previous-completion
"q" #'quit-window
"RET" #'choose-completion
"<backtab>" #'switch-to-minibuffer)
:config
(evil-set-initial-state 'completion-list-mode 'normal))
Minibuffer
(use-package minibuffer
:demand t
:general
(general-def
:states '(normal insert)
:keymaps 'minibuffer-local-map
"<backtab>" #'switch-to-completions
"C-j" #'next-line-or-history-element
"C-k" #'previous-line-or-history-element))
Save minibuffer history
Save any minibuffer usage in a history file, which allows reuse in later instances.
(use-package savehist
:defer t
:config
(savehist-mode t))
IComplete
(use-package icomplete
:demand t
:general
(general-def
:state '(normal insert)
:keymaps '(icomplete-fido-mode-map icomplete-minibuffer-map)
"<backtab>" #'switch-to-completions
"M-j" #'icomplete-forward-completions
"M-k" #'icomplete-backward-completions
"RET" #'icomplete-force-complete-and-exit
"TAB" #'minibuffer-complete-word
"SPC" #'self-insert-command)
:init
(setq icomplete-compute-delay 0.01
icomplete-delay-completions-threshold 2500)
:config
(icomplete-vertical-mode))
Consult
(use-package consult
:straight t
:general
(search-leader
"i" #'consult-imenu
"s" #'consult-line))
Amx
Amx is a fork of Smex that works to enhance the execute-extended-command interface. It also provides support for ido or ivy (though I'm likely to use ido here) and allows you to switch between them.
It provides a lot of niceties such as presenting the key bind when looking for a command.
(use-package amx
:straight t
:defer 2
:init
(setq amx-backend 'auto)
:config
(amx-mode))
Orderless
Orderless sorting method for completion, probably one of the best things ever.
(use-package orderless
:straight t
:after icomplete
:config
(setq completion-styles '(substring orderless basic)
completion-category-defaults nil
completion-category-overrides '((file (styles initials substring partial-completion))))
(with-eval-after-load "ivy"
(setf (alist-get t ivy-re-builders-alist) 'orderless-ivy-re-builder)))
Company
Company is the auto complete system I use. I don't like having heavy setups for company as it only makes it slower to use. In this case, just setup some evil binds for company.
(use-package company
:defer t
:straight t
:hook
(prog-mode-hook . company-mode)
(eshell-mode-hook . company-mode)
:general
(imap
"C-SPC" #'company-complete
"C-@" #'company-complete
"M-j" #'company-select-next
"M-k" #'company-select-previous))
Pretty symbols
Prettify symbols mode allows users to declare "symbols" that replace text within certain modes. It's eye candy in most cases, but can aid comprehension for symbol heavy languages.
This configures a use-package keyword which makes declaring pretty
symbols for language modes incredibly easy. Checkout my [[*Emacs
lisp][Emacs lisp]] configuration for an example.
(use-package prog-mode
:demand t
:init
(setq prettify-symbols-unprettify-at-point t)
:config
(with-eval-after-load "use-package-core"
(add-to-list 'use-package-keywords ':pretty)
(defun use-package-normalize/:pretty (_name-symbol _keyword args)
args)
(defun use-package-handler/:pretty (name _keyword args rest state)
(use-package-concat
(use-package-process-keywords name rest state)
(mapcar
#'(lambda (arg)
(let ((mode (car arg))
(rest (cdr arg)))
`(add-hook
',mode
#'(lambda nil
(setq prettify-symbols-alist ',rest)
(prettify-symbols-mode)))))
args)))))
Here's a collection of keywords and possible associated symbols for any prog language of choice. Mostly for reference and copying.
("null" . "Ø")
("list" . "ℓ")
("string" . "𝕊")
("char" . "ℂ")
("int" . "ℤ")
("float" . "ℝ")
("!" . "¬")
("for" . "Σ")
("return" . "≡")
("reduce" . "↓")
("map" . "→")
("some" . "∃")
("every" . "∃")
("lambda" . "λ")
("function" . "ƒ")
("<=" . "≤")
(">=" . "≥")
Tabs
Tabs in vscode are just like buffers in Emacs but way slower and harder to use. Tabs in Emacs are essentially window layouts, similar to instances in Tmux. With this setup I can use tabs quite effectively.
(use-package tab-bar
:defer t
:init
(setq tab-bar-close-button-show nil
tab-bar-format '(tab-bar-format-history tab-bar-format-tabs tab-bar-separator))
:config
(setq tab-bar-show 1)
(tab-bar-mode)
:general
(tab-leader
"R" #'tab-rename
"c" #'tab-close
"d" #'tab-close
"f" #'tab-detach
"h" #'tab-move-to
"j" #'tab-next
"k" #'tab-previous
"l" #'tab-move
"n" #'tab-new
"r" #'tab-switch
"w" #'tab-window-detach)
(mode-leader
"t" #'toggle-tab-bar-mode-from-frame))
Auto typing
Snippets are a pretty nice way of automatically inserting code. Emacs provides a ton of packages by default to do this, but there are great packages to install as well.
Abbrevs and skeletons make up a popular solution within Emacs default. Abbrevs are for simple expressions wherein the only input is the key, and the output is some Elisp function. They provide a lot of inbuilt functionality and are quite useful. Skeletons, on the other hand, are for higher level insertions
The popular external solution is Yasnippet. Yasnippet is a great package for snippets, which I use heavily in programming and org-mode. I setup here the global mode for yasnippet and a collection of snippets for ease of use.
Abbrevs
Just define a few abbrevs for various date-time operations. Also define a macro that will assume a function for the expansion, helping with abstracting a few things away.
(use-package abbrev
:defer t
:hook
(prog-mode-hook . abbrev-mode)
(text-mode-hook . abbrev-mode)
:init
(defmacro +abbrev/define-abbrevs (abbrev-table &rest abbrevs)
`(progn
,@(mapcar #'(lambda (abbrev)
`(define-abbrev
,abbrev-table
,(car abbrev)
""
(proc (insert ,(cadr abbrev)))))
abbrevs)))
(setq save-abbrevs nil)
:config
(+abbrev/define-abbrevs
global-abbrev-table
("sdate"
(format-time-string "%Y-%m-%d" (current-time)))
("stime"
(format-time-string "%H:%M:%S" (current-time)))
("sday"
(format-time-string "%A" (current-time)))
("smon"
(format-time-string "%B" (current-time)))))
Auto insert
Allows inserting text immediately upon creating a new buffer with a
given name. Supports skeletons for inserting text. To make it easier
for later systems to define their own auto inserts, I define a
use-package keyword auto-insert which allows one to define an
entry for auto-insert-alist.
(use-package autoinsert
:demand t
:hook (emacs-startup-hook . auto-insert-mode)
:config
(with-eval-after-load "use-package-core"
(add-to-list 'use-package-keywords ':auto-insert)
(defun use-package-normalize/:auto-insert (_name-symbol _keyword args)
args)
(defun use-package-handler/:auto-insert (name _keyword args rest state)
(use-package-concat
(use-package-process-keywords name rest state)
(mapcar
#'(lambda (arg)
`(add-to-list
'auto-insert-alist
',arg))
args)))))
Yasnippet
Look at the snippets folder for all snippets I've got.
(use-package yasnippet
:straight t
:defer t
:hook
(prog-mode-hook . yas-minor-mode)
(text-mode-hook . yas-minor-mode)
:general
(insert-leader
"i" #'yas-insert-snippet)
:config
(yas-load-directory (no-littering-expand-etc-file-name
"yasnippet/snippets")))
Hydra
Hydra is a great package by abo-abo (yes the same guy who made ivy
and swiper) and I hope to use it later on in the config. There are
two use-package declarations here: one for hydra itself, and the
other for use-package-hydra which provides the keyword :hydra in
use-package declarations.
(use-package hydra
:straight t)
(use-package use-package-hydra
:straight t)
(use-package hydra
:hydra
(hydra-window-resize
nil "Resize the current window effectively"
("l" #'evil-window-increase-width)
("h" #'evil-window-decrease-width)
("j" #'evil-window-decrease-height)
("k" #'evil-window-increase-height)
("=" #'balance-windows))
:general
(leader
"wr" #'hydra-window-resize/body))
Small packages
Magit
Magit is the git porcelain for Emacs, which perfectly encapsulates the git CLI. It's so good that some people use Emacs just to use it. It's difficult to describe well without using it, in my opinion, and it integrates so well with Emacs that there is very little need to use the git CLI ever.
In this case I just need to setup the bindings for it. As magit will definitely load after evil (as it must be run by a binding, and evil will load after init), I can use evil-collection freely. Also, define an auto insert for commit messages so that I don't need to write everything myself.
(use-package transient
:straight (:host github :repo "magit/transient" :tag "v0.7.5"))
(use-package magit
:straight (:host github :repo "magit/magit" :tag "v4.1.0")
:defer t
:display
("magit:.*"
(display-buffer-same-window)
(inhibit-duplicate-buffer . t))
("magit-diff:.*"
(display-buffer-below-selected))
("magit-log:.*"
(display-buffer-same-window))
:general
(leader
"g" '(magit-dispatch :which-key "Magit"))
(code-leader
"b" #'magit-blame)
:auto-insert
(("COMMIT_EDITMSG" . "Commit skeleton")
""
"(" (read-string "Enter feature/module: ") ")"
(read-string "Enter simple description: ") "\n\n")
:init
(setq vc-follow-symlinks t
magit-blame-echo-style 'lines
magit-copy-revision-abbreviated t)
:config
(with-eval-after-load "evil"
(evil-set-initial-state 'magit-status-mode 'motion))
(with-eval-after-load "evil-collection"
(evil-collection-magit-setup)))
Info
Info is GNU's attempt at better man pages. Most Emacs packages have info pages so I'd like nice navigation options.
(use-package info
:defer t
:general
(nmmap
:keymaps 'Info-mode-map
"h" #'evil-backward-char
"k" #'evil-previous-line
"l" #'evil-forward-char
"H" #'Info-history-back
"L" #'Info-history-forward
"RET" #'Info-follow-nearest-node))
Display line numbers
I don't really like line numbers, I find them similar to fringes (useless space), but at least it provides some information. Sometimes it can help with doing repeated commands so a toggle option is necessary.
(use-package display-line-numbers
:defer t
:commands display-line-numbers-mode
:general
(mode-leader
"l" #'display-line-numbers-mode)
:init
(setq-default display-line-numbers-type 'relative))
WAIT esup
I used to be able to just use
profile-dotemacs.el, when my
Emacs config was smaller, but now it tells me very little information
about where my setup is inefficient due to the literate config. Just
found this esup thing and it works perfectly, exactly how I would
prefer getting this kind of information. It runs an external Emacs
instance and collects information from it, so it doesn't require
restarting Emacs to profile, and I can compile my configuration in my
current instance to test it immediately.
2023-10-16: Unless I'm doing some optimisations or tests, I don't really need this in my config at all times. Enable when needed.
(use-package esup
:straight t
:defer t)
WAIT Hl-line
Highlights the current line.
(use-package hl-line
:straight t
:defer t
:hook (text-mode-hook . hl-line-mode)
:hook (prog-mode-hook . hl-line-mode))
Recentf
Recentf provides a method of keeping track of recently opened files.
(use-package recentf
:defer t
:hook (emacs-startup-hook . recentf-mode))
Avy
Setup avy with leader. As I use avy-goto-char-timer a lot, use the
C-s bind which replaces isearch. Switch isearch to M-s in case I
need to use it.
(use-package avy
:straight t
:defer t
:general
(nmmap
:keymaps 'override
"C-s" #'avy-goto-char-timer
"M-s" #'isearch-forward
"gp" #'avy-copy-region
"gP" #'avy-move-region
"gl" #'avy-goto-line
"gw" #'avy-goto-word-1))
Ace window
Though evil provides a great many features in terms of window management, ace window can provide some nicer chords for higher management of windows (closing, switching, etc).
(use-package ace-window
:straight t
:defer t
:custom
(aw-keys '(?a ?s ?d ?f ?g ?h ?j ?k ?l))
:general
(nmmap
[remap evil-window-next] #'ace-window))
Ace link
Avy-style link following!
(use-package ace-link
:straight t
:defer t
:general
(nmmap
:keymaps 'override
"gL" #'ace-link))
Helpful
Helpful provides a modernised interface for some common help
commands. I replace describe-function, describe-variable and
describe-key by their helpful counterparts.
(use-package helpful
:straight t
:defer t
:commands (helpful-callable helpful-variable)
:general
([remap describe-function] #'helpful-callable
[remap describe-variable] #'helpful-variable
[remap describe-key] #'helpful-key)
:display
("\\*helpful.*"
(display-buffer-at-bottom)
(inhibit-duplicate-buffer . t)
(window-height . 0.25))
:config
(evil-define-key 'normal helpful-mode-map "q" #'quit-window))
Which-key
Which key uses the minibuffer when performing a keybind to provide possible options for the next key.
(use-package which-key
:straight t
:after general
:config
(which-key-mode))
(Rip)grep
Grep is a great piece of software, a necessary tool in any Linux
user's inventory. By default Emacs has a family of functions
utilising grep, presenting results in a compilation
buffer. grep searches files, rgrep searches files in a directory
using the find program and zgrep searches archives. This is a
great solution for a general computer environment; essentially all
Linux installs will have grep and find installed.
Ripgrep is a Rust program that attempts to perform better than grep,
and it does. This is because of many optimisations, such as reading
.gitignore to exclude certain files from being searched. The
ripgrep package provides utilities to search projects and files.
ivy comes with counsel-rg which uses Ivy's completion
framework rather than the compilation style buffers, which can
sometimes prove useful.
Of course, this requires installing the rg binary which is available in most distribution nowadays.
Grep
I have no use for standard 'grep'; counsel-swiper does the same
thing faster and within Emacs lisp. rgrep is useful though.
(use-package grep
:defer t
:display
("^\\*grep.*"
(display-buffer-reuse-window display-buffer-at-bottom)
(window-height . 0.35)
(reusable-frames . t))
:general
(search-leader
"d" #'rgrep)
(nmmap
:keymaps 'grep-mode-map
"0" #'evil-beginning-of-line
"q" #'quit-window
"i" #'wgrep-change-to-wgrep-mode
"c" #'recompile)
(nmmap
:keymaps 'wgrep-mode-map
"q" #'evil-record-macro
"ZZ" #'wgrep-finish-edit
"ZQ" #'wgrep-abort-changes)
:config
;; Without this wgrep doesn't work properly
(evil-set-initial-state 'grep-mode 'normal))
rg
(use-package rg
:straight t
:defer t
:display
("^\\*\\*ripgrep\\*\\*"
(display-buffer-reuse-window display-buffer-at-bottom)
(window-height . 0.35)
(reusable-frames . t))
:general
(search-leader
"r" #'rg)
(nmmap
:keymaps 'rg-mode-map
"c" #'rg-recompile
"C" #'rg-rerun-toggle-case
"]]" #'rg-next-file
"[[" #'rg-prev-file
"q" #'quit-window
"i" #'wgrep-change-to-wgrep-mode)
:init
(setq rg-group-result t
rg-hide-command t
rg-show-columns nil
rg-show-header t
rg-custom-type-aliases nil
rg-default-alias-fallback "all"
rg-buffer-name "*ripgrep*")
:config
(evil-set-initial-state 'rg-mode 'normal))
Olivetti
Olivetti provides a focus mode for Emacs, which makes it look a bit nicer. It uses margins by default and centres using fill-column. I actually really like olivetti mode particularly with my [[*Mode line][centred mode-line]], so I also define a global minor mode which enables it in all but the minibuffer.
(use-package olivetti
:straight t
:defer t
:general
(mode-leader
"o" #'olivetti-global-mode)
:init
(setq-default olivetti-body-width nil)
(setq-default olivetti-minimum-body-width 100)
(setq olivetti-style nil)
:config
(define-globalized-minor-mode olivetti-global-mode olivetti-mode
(lambda nil (unless (minibufferp)
(olivetti-mode 1)))))
All the Icons
Nice set of icons with a great user interface to manage them.
(use-package all-the-icons
:straight t
:defer t
:commands (all-the-icons-insert)
:general
(insert-leader
"e" #'all-the-icons-insert))
Hide mode line
Custom minor mode to toggle the mode line. Check it out at elisp/hide-mode-line.el.
(use-package hide-mode-line
:load-path "elisp/"
:defer t
:general
(mode-leader
"m" #'global-hide-mode-line-mode))
Save place
Saves current place in a buffer permanently, so on revisiting the file (even in a different Emacs instance) you go back to the place you were at last.
(use-package saveplace
:defer t
:config
(save-place-mode))
Licensing
Loads license.el for inserting licenses. Licenses are important for distribution and attribution to be defined clearly.
(use-package license
:demand t
:load-path "elisp/"
:general
(insert-leader
"l" #'+license/insert-copyright-notice
"L" #'+license/insert-complete-license))
Memory-report
New feature of Emacs-29, gives a rough report of memory usage with some details. Useful to know on a long Emacs instance what could be eating up memory.
(use-package memory-report
:defer t
:general
(leader
"qm" #'memory-report))
Drag Stuff
Drag stuff around, like my favourite russian programmer (Tsoding). Useful mechanism which works better than any vim motion.
(use-package drag-stuff
:straight t
:defer t
:general
(nmmap
"C-M-h" #'drag-stuff-left
"C-M-j" #'drag-stuff-down
"C-M-k" #'drag-stuff-up
"C-M-l" #'drag-stuff-right))
Searching git directories efficiently
Using search.el I can search a set of directories particularly efficiently.
(use-package search
:defer t
:load-path "elisp/"
:general
(file-leader
"p" #'+search/find-file
"S" #'+search/search-all))
Separedit
Edit anything anywhere all at once!
(use-package separedit
:defer t
:straight t
:general
(leader "e" #'separedit)
:init
(setq separedit-default-mode 'org-mode
separedit-remove-trailing-spaces-in-comment t))
lorem ipsum
Sometimes you need placeholder text for some UI or document. Pretty easy to guess what text I'd use.
(use-package lorem-ipsum
:straight t
:general
(insert-leader
"p" #'lorem-ipsum-insert-paragraphs))
diff mode
Oh diffs; the way of the ancient ones. Nowadays we use our newfangled "pull requests" and "cool web interfaces" to manage changes in our code repositories, but old school projects use patches to make code changes. They're a pain to distribute and can be very annoying to use when applying them to code. Even then I somewhat like patches, if only for their simplicity.
dwm uses patches for adding
new features and Emacs has great functionality to work with patches
effectively. Here I configure diff-mode, which provides most of
this cool stuff, to be a bit more ergonomic with evil.
(use-package diff-mode
:general
(nmmap
:keymaps 'diff-mode-map
"}" #'diff-hunk-next
"{" #'diff-hunk-prev
"RET" #'diff-goto-source))
Applications
Emacs is basically an operating system whose primary datatype is text. Applications are interfaces/environments which serve a variety of purposes, but provide a lot of capability.
EWW
Emacs Web Wowser is the inbuilt text based web browser for Emacs. It can render images and basic CSS styles but doesn't have a JavaScript engine, which makes sense as it's primarily a text interface.
(use-package eww
:defer t
:general
(app-leader
"w" #'eww)
(nmmap
:keymaps 'eww-mode-map
"w" #'evil-forward-word-begin
"Y" #'eww-copy-page-url)
:config
(with-eval-after-load "evil-collection"
(evil-collection-eww-setup)))
Calendar
Calendar is a simple inbuilt application that helps with date functionalities. I add functionality to copy dates from the calendar to the kill ring and bind it to "Y".
(use-package calendar
:defer t
:commands (+calendar/copy-date +calendar/toggle-calendar)
:display
("\\*Calendar\\*"
(display-buffer-at-bottom)
(inhibit-duplicate-buffer . t)
(window-height . 0.17))
:general
(nmmap
:keymaps 'calendar-mode-map
"Y" #'+calendar/copy-date)
(app-leader
"d" #'calendar)
:config
(defun +calendar/copy-date ()
"Copy date under cursor into kill ring."
(interactive)
(if (use-region-p)
(call-interactively #'kill-ring-save)
(let ((date (calendar-cursor-to-date)))
(when date
(setq date (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date)))
(kill-new (format-time-string "%Y-%m-%d" date)))))))
Mail is a funny thing; most people use it just for business or advertising and it's come out of use in terms of personal communication in the west for the most part (largely due to "social" media applications). However, this isn't true for the open source and free software movement who heavily use mail for communication.
Integrating mail into Emacs helps as I can send source code and integrate it into my workflow just a bit better. There are a few ways of doing this, both in built and via package.
Notmuch
Notmuch is an application for categorising some local mail system.
It's really fast, has tons of customisable functionality and has good
integration with Emacs. I use mbsync separately to pull my mail
from the remote server.
(use-package notmuch
:straight t
:defer t
:commands (notmuch +mail/flag-thread)
:general
(app-leader "m" #'notmuch)
(nmap
:keymaps 'notmuch-search-mode-map
"f" #'+mail/flag-thread)
:init
(defconst +mail/local-dir (no-littering-expand-var-file-name "mail/"))
(setq notmuch-show-logo nil
notmuch-search-oldest-first nil
notmuch-hello-sections '(notmuch-hello-insert-saved-searches
notmuch-hello-insert-alltags
notmuch-hello-insert-recent-searches)
notmuch-archive-tags '("-inbox" "-unread" "+archive")
message-auto-save-directory +mail/local-dir
message-directory +mail/local-dir)
:config
(defun +mail/flag-thread (&optional unflag beg end)
(interactive (cons current-prefix-arg (notmuch-interactive-region)))
(notmuch-search-tag
(notmuch-tag-change-list '("-inbox" "+flagged") unflag) beg end)
(when (eq beg end)
(notmuch-search-next-thread)))
(with-eval-after-load "evil-collection"
(evil-collection-notmuch-setup)))
Smtpmail
Setup the smtpmail package, which is used when sending mail. Mostly custom configuration for integration with other parts of Emacs' mail system.
(use-package smtpmail
:defer t
:commands mail-send
:init
(setq-default
smtpmail-smtp-server "mail.aryadevchavali.com"
smtpmail-smtp-user "aryadev"
smtpmail-smtp-service 587
smtpmail-stream-type 'starttls
send-mail-function #'smtpmail-send-it
message-send-mail-function #'smtpmail-send-it))
Mail signature using fortune
Generate a mail signature using the fortune executable. Pretty
cool!
(use-package fortune
:init
(setq fortune-dir "/usr/share/fortune"
fortune-file "/usr/share/fortune/cookie")
:config
(defvar +mail/signature "---------------\nAryadev Chavali\n---------------\n%s")
(defun +mail/make-signature ()
(interactive)
(format +mail/signature
(with-temp-buffer
(let ((fortune-buffer-name (current-buffer)))
(fortune-in-buffer t)
(if (bolp) (delete-char -1))
(buffer-string)))))
(add-hook 'message-setup-hook
(lambda nil (setq message-signature (+mail/make-signature)))))
Dired
Dired: Directory editor for Emacs. An incredibly nifty piece of software which deeply integrates with Emacs as a whole. Probably the best file manager overall and for large scale file system tasks I can't think of a better tool than this.
Here I setup dired with a few niceties
- Hide details by default (no extra stuff from
ls) - Omit dot files by default (using
dired-omit-mode) - If I have two dired windows open, moving or copying files in one
dired instance will automatically target the other dired window
(
dired-dwim) - If opening an application on a PDF file, suggest
zathura - Examine all the subdirectories within the same buffer
(
+dired/insert-all-subdirectories)
(use-package dired
:defer t
:commands (dired find-dired)
:hook
(dired-mode-hook . auto-revert-mode)
(dired-mode-hook . dired-hide-details-mode)
(dired-mode-hook . dired-omit-mode)
:init
(setq-default dired-listing-switches "-AFBlu --group-directories-first"
dired-omit-files "^\\." ; dotfiles
dired-omit-verbose nil
dired-dwim-target t
dired-kill-when-opening-new-dired-buffer t)
(with-eval-after-load "evil-collection"
(evil-collection-dired-setup))
:general
(nmmap
:keymaps 'dired-mode-map
"SPC" nil
"SPC ," nil
"(" #'dired-hide-details-mode
")" #'dired-omit-mode
"T" #'dired-create-empty-file
"H" #'dired-up-directory
"L" #'dired-find-file)
(dir-leader
"f" #'find-dired
"d" #'dired
"D" #'dired-other-window
"i" #'image-dired
"p" `(,(proc (interactive)
(dired "~/Text/PDFs/"))
:which-key "Open PDFs"))
(local-leader
:keymaps 'dired-mode-map
"i" #'dired-maybe-insert-subdir
"I" #'+dired/insert-all-subdirectories
"o" #'dired-omit-mode
"k" #'dired-prev-subdir
"j" #'dired-next-subdir
"K" #'dired-kill-subdir
"m" #'dired-mark-files-regexp
"u" #'dired-undo)
:config
(add-multiple-to-list dired-guess-shell-alist-user
'("\\.pdf\\'" . "zathura")
'("\\.epub\\'" . "zathura")
'("\\.jpg\\'" . "feh")
'("\\.png\\'" . "feh")
'("\\.webm\\'" . "mpv")
'("\\.mp[34]\\'" . "mpv")
'("\\.mkv\\'" . "mpv"))
(defun +dired/insert-all-subdirectories ()
"Insert all subdirectories currently viewable."
(interactive)
(dired-mark-directories nil)
(mapc #'dired-insert-subdir (dired-get-marked-files))
(dired-unmark-all-marks)))
image-dired
Image dired is a little cherry on top for Dired: the ability to look through swathes of images in a centralised fashion while still being able to do all the usual dired stuff as well is really cool.
(use-package dired
:defer t
:init
(setq image-dired-external-viewer "nsxiv")
:general
(nmmap
:keymaps 'image-dired-thumbnail-mode-map
"h" #'image-dired-backward-image
"l" #'image-dired-forward-image
"j" #'image-dired-next-line
"k" #'image-dired-previous-line
"H" #'image-dired-display-previous
"L" #'image-dired-display-next
"RET" #'image-dired-display-this
"m" #'image-dired-mark-thumb-original-file
"q" #'quit-window))
fd-dired
Uses fd for finding file results in a directory: find-dired ->
fd-dired.
(use-package fd-dired
:straight t
:after dired
:general
(dir-leader
"g" #'fd-dired))
wdired
Similar to wgrep wdired provides
the ability to use Emacs motions and editing on file names. This
makes stuff like mass renaming and other file management tasks way
easier than even using the mark based system.
(use-package wdired
:after dired
:hook (wdired-mode-hook . undo-tree-mode)
:general
(nmmap
:keymaps 'dired-mode-map
"W" #'wdired-change-to-wdired-mode)
(nmmap
:keymaps 'wdired-mode-map
"ZZ" #'wdired-finish-edit
"ZQ" #'wdired-abort-changes)
:config
(eval-after-load "evil"
;; 2024-09-07: Why does evil-set-initial-state returning a list of modes for
;; normal state make eval-after-load evaluate as if it were an actual
;; expression?
(progn (evil-set-initial-state 'wdired-mode 'normal)
nil)))
dired-rsync
Rsync is a great way the best way of transferring files around *nix
machines, and I use dired for all my file management concerns. So I
should be able to rsync stuff around if I want.
(use-package dired-rsync
:straight t
:after dired
:general
(nmmap
:keymaps 'dired-mode-map
"M-r" #'dired-rsync))
Eshell
Why Eshell?
Eshell is an integrated shell environment for Emacs, written in Emacs Lisp. I argue henceforth that it is the best shell/command interpreter to use in Emacs.
Eshell is unlike the other alternatives in Emacs as it's a shell first, not a terminal emulator, with the ability to spoof some aspects of a terminal emulator (through the shell parser).
The killer benefits of eshell (which would appeal particularly to an Emacs user) are a direct result of eshell being written in Emacs Lisp:
- incredible integration with Emacs utilities (such as
dired,find-file, any read functions, etc) - very extensible, easy to write new commands which leverage Emacs commands as well as external utilities
-
agnostic of platform: "eshell/cd" will call the underlying change directory function for you, so commands will (usually) mean the same thing regardless of platform
- this means as long as Emacs can run on an operating system, one may run eshell
However, my favourite feature of eshell is the set of evaluators that run on command input. Some of the benefits listed above come as a result of this powerful feature. These evaluators are described below.
Lisp evaluator: works on braced expressions, evaluating them as Lisp
expressions (e.g. (message "Hello, World!\n")). Any returned
objects are printed. This makes eshell a LISP REPL!
External evaluator: works within curly braces, evaluating them via
some external shell process (like sh) (e.g. {echo "Hello,
world!\n"}). This makes eshell a (kinda dumb) terminal emulator!
The alias evaluator is the top level evaluator. It is the main evaluator for each expression given to eshell. When given an expression it tries to evaluate it by testing against these conditions:
- it's an alias defined by the user or in the
eshell/namespace of functions (simplest evaluator) - it's some form of lisp expression (lisp evaluator)
- it's an external command (bash evaluator)
Essentially, you get the best of both Emacs and external shell programs ALL WITHIN Emacs for free.
Eshell keymaps, display and variables
Bind some evil-like movements for easy shell usage, a display record so when you call eshell it kinda looks like VSCode's terminal popup.
NOTE: This mode doesn't allow you to set maps the normal way; you need to set keybindings on eshell-mode-hook, otherwise it'll just overwrite them.
(use-package eshell
:defer t
:display
("\\*.*eshell\\*"
(display-buffer-same-window)
(reusable-frames . t))
:init
(setq eshell-cmpl-ignore-case t
eshell-cd-on-directory t
eshell-cd-shows-directory nil
eshell-highlight-prompt nil)
(add-hook
'eshell-mode-hook
(proc
(interactive)
(nmap
:keymaps 'eshell-mode-map
"0" #'eshell-bol)
(general-def
:states '(normal insert)
:keymaps 'eshell-mode-map
"C-j" #'eshell-next-matching-input-from-input
"C-k" #'eshell-previous-matching-input-from-input)
(local-leader
:keymaps 'eshell-mode-map
"c" (proc (interactive) (eshell/clear)
(recenter))
"k" #'eshell-kill-process))))
Eshell prompt
Here I use my external library eshell-prompt, which provides a more dynamic prompt for Eshell. Current features include:
- Git (with difference from remote and number of modified files)
- Current date and time
- A coloured prompt which changes colour based on the exit status of the previous command
NOTE: I don't defer this package because it doesn't use any eshell internals, just standard old Emacs packages.
(use-package eshell-prompt
:load-path "elisp/"
:config
(defun +eshell/banner-message ()
(concat (shell-command-to-string "cowfortune") "\n"))
(setq eshell-prompt-regexp (format "^%s" +eshell-prompt/user-prompt)
eshell-prompt-function #'+eshell-prompt/make-prompt
eshell-banner-message '(+eshell/banner-message)))
Eshell additions
Using my external library eshell-additions, I get a few new eshell internal commands and a surface command to open eshell at the current working directory.
NOTE: I don't defer this package because it autoloads any eshell
internals that it uses so I'm only loading what I need to. Any
eshell/* functions need to be known by eshell before launching, so
if I loaded this :after eshell then the first instance has no
knowledge of the new additions.
(use-package eshell-additions
:defer t
:load-path "elisp/"
:general
(shell-leader
"t" #'+eshell/open)
(leader
"T" #'+eshell/at-cwd))
Eshell syntax highlighting
This package external package adds syntax highlighting to eshell (disabling it for remote work). Doesn't require a lot of config thankfully.
(use-package eshell-syntax-highlighting
:straight t
:after eshell
:hook (eshell-mode-hook . eshell-syntax-highlighting-mode))
WAIT Elfeed
Elfeed is the perfect RSS feed reader, integrated into Emacs perfectly. I've got a set of feeds that I use for a large variety of stuff, mostly media and entertainment. I've also bound "<leader> ar" to elfeed for loading the system.
(use-package elfeed
:straight t
:general
(app-leader "r" #'elfeed)
(nmmap
:keymaps 'elfeed-search-mode-map
"gr" #'elfeed-update
"s" #'elfeed-search-live-filter
"<return>" #'elfeed-search-show-entry)
:init
(setq elfeed-db-directory (no-littering-expand-var-file-name "elfeed/"))
(setq +rss/feed-urls
'(("Arch Linux"
"https://www.archlinux.org/feeds/news/"
News Technology)
("The Onion"
"https://www.theonion.com/rss"
Social)
("Protesilaos Stavrou"
"https://www.youtube.com/@protesilaos"
YouTube Technology)
("Tsoding Daily"
"https://www.youtube.com/feeds/videos.xml?channel_id=UCrqM0Ym_NbK1fqeQG2VIohg"
YouTube Technology)
("Tsoding"
"https://www.youtube.com/feeds/videos.xml?channel_id=UCrqM0Ym_NbK1fqeQG2VIohg"
YouTube Technology)
("Nexpo"
"https://www.youtube.com/feeds/videos.xml?channel_id=UCpFFItkfZz1qz5PpHpqzYBw"
YouTube Stories)
("3B1B"
"https://www.youtube.com/feeds/videos.xml?channel_id=UCYO_jab_esuFRV4b17AJtAw"
YouTube)
("Fredrik Knusden"
"https://www.youtube.com/feeds/videos.xml?channel_id=UCbWcXB0PoqOsAvAdfzWMf0w"
YouTube Stories)
("Barely Sociable"
"https://www.youtube.com/feeds/videos.xml?channel_id=UC9PIn6-XuRKZ5HmYeu46AIw"
YouTube Stories)
("Atrocity Guide"
"https://www.youtube.com/feeds/videos.xml?channel_id=UCn8OYopT9e8tng-CGEWzfmw"
YouTube Stories)
("Hacker News"
"https://news.ycombinator.com/rss"
Social News Technology)
("Hacker Factor"
"https://www.hackerfactor.com/blog/index.php?/feeds/index.rss2"
Social)))
:config
(with-eval-after-load "evil-collection"
(evil-collection-elfeed-setup))
(setq elfeed-feeds (cl-map 'list #'(lambda (item)
(append (list (nth 1 item)) (cdr (cdr item))))
+rss/feed-urls))
(advice-add 'elfeed-search-show-entry :after #'+elfeed/dispatch-entry)
(defun +elfeed/dispatch-entry (entry)
"Process each type of entry differently.
e.g., you may want to open HN entries in eww."
(let ((url (elfeed-entry-link entry)))
(pcase url
((pred (string-match-p "https\\:\\/\\/www.youtube.com\\/watch"))
(mpv-play-url url))
(_ (eww url))))))
IBuffer
IBuffer is the dired of buffers: providing the ability to mark buffers, mass rename/delete and just observe stuff.
(use-package ibuffer
:defer t
:general
(buffer-leader
"i" #'ibuffer)
:config
(with-eval-after-load "evil-collection"
(evil-collection-ibuffer-setup)))
Proced
Emacs has two systems for process management:
- proced: a general 'top' like interface which allows general management of linux processes
- list-processes: a specific Emacs based system that lists processes spawned by Emacs (similar to a top for Emacs specifically)
Core proced config, just a few bindings and evil collection setup.
(use-package proced
:defer t
:general
(app-leader
"p" #'proced)
(nmap
:keymaps 'proced-mode-map
"za" #'proced-toggle-auto-update)
:display
("\\*Proced\\*"
(display-buffer-at-bottom)
(window-height . 0.25))
:init
(setq proced-auto-update-interval 0.5)
:config
(with-eval-after-load "evil-collection"
(evil-collection-proced-setup)))
Calculator
Surprise, surprise Emacs comes with a calculator.
calc-mode is a calculator system within Emacs that provides a
diverse array of mathematical operations. It uses reverse polish
notation, but there is a standard infix algebraic notation mode so
don't be too shocked. It can do a surprising amount of stuff, such
as:
- finding derivatives/integrals of generic equations
- matrix operations
- finding solutions for equations, such as for finite degree multi variable polynomials
It also has this thing called embedded mode. This allows one to
perform computation within a non calc-mode buffer. Surround any
equation with dollar signs (such as 2^20, for example) and call
(calc-embedded) with your cursor on it to compute it. It'll replace
the equation with the result it computed.
Say I want to find the 4th power of 2 cos I'm writing some bit manipulation code and I need to set the 4th bit of some variable to 1. Instead of computing it outside of my editor then copying the result back in, I can just do it within Emacs. Pretty nifty, right?
(use-package calc
:defer t
:display
("*Calculator*"
(display-buffer-at-bottom)
(window-height . 0.18))
:general
(app-leader
"c" #'calc-dispatch)
:init
(setq calc-algebraic-mode t)
:config
(with-eval-after-load "evil-collection"
(evil-collection-calc-setup)))
Zone
Of course Emacs has a cool screensaver software.
(use-package zone
:defer t
:commands (zone)
:general
(leader
"z" #'zone)
:init
(setq zone-programs
[zone-pgm-drip
zone-pgm-drip-fretfully
zone-pgm-martini-swan-dive
zone-pgm-stress
zone-pgm-random-life]))
(Wo)man
Man pages are the user manuals for most software on Linux. Really useful when writing code for Un*x systems, though they can be very verbose.
2023-08-17: `Man-notify-method' is the reason the `:display' record doesn't work here. I think it's to do with how Man pages are rendered or something, but very annoying as it's a break from standards!
(use-package man
:defer t
:init
(setq Man-notify-method 'pushy)
:display
("^\\*Man.*"
(display-buffer-reuse-mode-window display-buffer-same-window))
:general
(file-leader
"m" #'man) ;; kinda like "find man page"
(nmmap
:keymaps 'Man-mode-map
"RET" #'man-follow))
WAIT gif-screencast
Little application that uses gifsicle to make essentially videos of
Emacs. Useful for demonstrating features.
(use-package gif-screencast
:straight t
:general
(app-leader
"x" #'gif-screencast-start-or-stop)
:init
(setq gif-screencast-output-directory (expand-file-name "~/Media/emacs/")))
Image-mode
Image mode, for viewing images. Supports tons of formats, easy to use and integrates slickly into image-dired. Of course,
(use-package image-mode
:defer t
:general
(nmmap
:keymaps 'image-mode-map
"+" #'image-increase-size
"-" #'image-decrease-size
"a" #'image-toggle-animation
"p+" #'image-increase-speed
"p-" #'image-increase-speed
"h" #'image-backward-hscroll
"j" #'image-next-line
"k" #'image-previous-line
"l" #'image-forward-hscroll))
mpv
My custom mpv module for opening videos in Emacs.
(use-package mpv
:defer t
:load-path "elisp/"
:general
(app-leader
"v" #'mpv-open-video))
Text modes
Standard packages and configurations for text-mode and its derived modes.
Flyspell
Flyspell allows me to spell check text documents. I use it primarily in org mode, as that is my preferred prose writing software, but I also need it in commit messages and so on, thus it should really hook into text-mode.
(use-package flyspell
:defer t
:hook (text-mode-hook . flyspell-mode)
:general
(nmmap
:keymaps 'text-mode-map
(kbd "M-C") #'flyspell-correct-word-before-point
(kbd "M-c") #'flyspell-auto-correct-word)
(mode-leader
"s" #'flyspell-mode))
Undo tree
Undo tree sits on top of Emacs' undo capabilities. It provides a nice visual for the history of a buffer and is a great way to produce branches of edits. This history may be saved to and loaded from the disk, which makes Emacs a quasi version control system in and of itself. The only feature left is describing changes…
(use-package undo-tree
:demand t
:straight t
:general
(leader
"u" #'undo-tree-visualize)
:init
(setq undo-tree-auto-save-history t
undo-tree-history-directory-alist backup-directory-alist)
:config
(global-undo-tree-mode))
Whitespace
Deleting whitespace, highlighting when going beyond the 80th character limit, all good stuff. I don't want to highlight whitespace for general mode categories (Lisp shouldn't really have an 80 character limit), so set it for specific modes need the help.
(use-package whitespace
:defer t
:general
(nmmap
"M--" #'whitespace-cleanup)
(mode-leader
"w" #'whitespace-mode)
:hook
(before-save-hook . whitespace-cleanup)
((c-mode-hook c++-mode-hook haskell-mode-hook python-mode-hook
org-mode-hook text-mode-hook js-mode-hook)
. whitespace-mode)
:init
(setq whitespace-line-column nil
whitespace-style '(face empty spaces tabs newline trailing lines-char
tab-mark)))
Filling and displaying fills
The fill-column is the number of characters that should be in a single line of text before doing a hard wrap. The default case is 80 characters for that l33t Unix hard terminal character limit. I like different fill-columns for different modes: text modes should really use 70 fill columns while code should stick to 80.
(use-package emacs
:init
(setq-default fill-column 80)
(add-hook 'text-mode-hook (proc (setq-local fill-column 70)))
:hook
(text-mode-hook . auto-fill-mode)
((c-mode-hook c++-mode-hook haskell-mode-hook python-mode-hook
org-mode-hook text-mode-hook js-mode-hook)
. display-fill-column-indicator-mode))
Show-paren-mode
Show parenthesis for Emacs
(use-package paren
:hook (prog-mode-hook . show-paren-mode))
Smartparens
Smartparens is a smarter electric-parens, it's much more aware of context and easier to use.
(use-package smartparens
:straight t
:defer t
:hook
(prog-mode-hook . smartparens-mode)
(text-mode-hook . smartparens-mode)
:config
(setq sp-highlight-pair-overlay nil
sp-highlight-wrap-overlay t
sp-highlight-wrap-tag-overlay t)
(let ((unless-list '(sp-point-before-word-p
sp-point-after-word-p
sp-point-before-same-p)))
(sp-pair "'" nil :unless unless-list)
(sp-pair "\"" nil :unless unless-list))
(sp-local-pair sp-lisp-modes "(" ")" :unless '(:rem sp-point-before-same-p))
(require 'smartparens-config))
Powerthesaurus
Modern package for thesaurus in Emacs with a transient + hydra.
(use-package powerthesaurus
:defer t
:straight t
:general
(search-leader
"w" #'powerthesaurus-transient))
Programming packages
Packages that help with programming in general, providing IDE like capabilities.
Eldoc
Eldoc presents documentation to the user upon placing ones cursor upon any symbol. This is very useful when programming as it:
- presents the arguments of functions while writing calls for them
- presents typing and documentation of variables
Eldoc box makes the help buffer a hovering box instead of printing it in the minibuffer. A lot cleaner.
2024-05-31: Eldoc box is a bit useless now that I'm not using frames. I prefer the use of the minibuffer for printing documentation now.
(use-package eldoc
:defer t
:hook (prog-mode-hook . eldoc-mode)
:init
(global-eldoc-mode 1)
:general
(leader
"h>" #'eldoc-doc-buffer))
Flycheck
Flycheck is the checking system for Emacs. I don't necessarily like having all my code checked all the time, so I haven't added a hook to prog-mode as it would be better for me to decide when I want checking and when I don't.
I've added it to C/C++ mode because I use them regularly and flycheck has very little overhead to work there.
(use-package flycheck
:straight t
:defer t
:commands (flycheck-mode flycheck-list-errors)
:hook
(c-mode-hook . flycheck-mode)
(c++-mode-hook . flycheck-mode)
:general
(mode-leader
"f" #'flycheck-mode)
(code-leader
"x" #'flycheck-list-errors
"j" #'flycheck-next-error
"k" #'flycheck-previous-error)
:display
("\\*Flycheck.*"
(display-buffer-at-bottom)
(window-height . 0.25))
:init
(setq-default flycheck-check-syntax-automatically '(save idle-change new-line mode-enabled))
:config
(with-eval-after-load "evil-collection"
(evil-collection-flycheck-setup)))
Eglot
Eglot is package to communicate with LSP servers for better programming capabilities. Interactions with a server provide results to the client, done through JSON.
NOTE: Emacs 28.1 comes with better JSON parsing, which makes Eglot much faster.
2023-03-26: I've found Eglot to be useful sometimes, but many of the
projects I work on don't require a heavy server setup to efficiently
edit and check for errors; Emacs provides a lot of functionality. So
by default I've disabled it, using M-x eglot to startup the LSP
server when I need it.
2024-06-27: In projects where I do use eglot and I know I will need it regardless of file choice, I prefer setting it at the dir-local level via an eval form. So I add to the safe values for the eval variable to be set.
(use-package eglot
:defer t
:general
(code-leader
:keymaps 'eglot-mode-map
"f" #'eglot-format
"a" #'eglot-code-actions
"r" #'eglot-rename
"R" #'eglot-reconnect)
:init
(setq eglot-stay-out-of '(flymake)
eglot-ignored-server-capabilities '(:documentHighlightProvider
:documentOnTypeFormattingProvider
:inlayHintProvider))
(add-to-list 'safe-local-variable-values '(eval eglot-ensure))
:config
(add-to-list 'eglot-server-programs '((c++-mode c-mode) "clangd")))
Flycheck-Eglot
By default Eglot uses the integrated flymake package for error reporting. I don't mind flymake, and I think an integrated solution which doesn't rely on external packages is always a great idea. However, I just personally prefer flycheck and it's become part of my mental model when programming. So here's a package which will integrate flycheck into Eglot's error reporting.
(Funny but also kind of depressing is this issue in Eglot where someone requested this integration, which caused a bit of a flame war. People are stupid. no opinion on flymake)
(use-package flycheck-eglot
:straight t
:after (flycheck eglot)
:hook (eglot-managed-mode-hook . flycheck-eglot-mode))
Indentation
By default, turn off tabs and set the tab width to two.
(setq-default indent-tabs-mode nil
tab-width 2)
However, if necessary later, define a function that may activate tabs locally.
(defun +oreo/use-tabs ()
(interactive)
(setq-local indent-tabs-mode t))
Highlight todo items
TODO items are highlighted in org-mode, but not necessarily in every mode. This minor mode highlights all TODO like items via a list of strings to match. It also configures faces to use when highlighting. I hook it to prog-mode.
(use-package hl-todo
:straight t
:after prog-mode
:hook (prog-mode-hook . hl-todo-mode)
:init
(setq hl-todo-keyword-faces
'(("TODO" . "#E50000")
("WIP" . "#ffa500")
("NOTE" . "#00CC00")
("FIXME" . "#d02090"))))
Hide-show mode
Turn on hs-minor-mode for all prog-mode. This provides folds for
free.
(use-package hideshow
:defer t
:hook (prog-mode-hook . hs-minor-mode))
Aggressive indenting
Essentially my dream editing experience: when I type stuff in, try and indent it for me on the fly. Just checkout the page, any description I give won't do it justice.
(use-package aggressive-indent
:straight t
:demand t
:config
(add-multiple-to-list aggressive-indent-excluded-modes
'c-mode 'c++-mode 'cc-mode
'asm-mode 'js-mode 'typescript-mode
'tsx-mode 'typescript-ts-mode 'tsx-ts-mode)
(global-aggressive-indent-mode))
Compilation
Compilation mode is an incredibly useful subsystem of Emacs which allows one to run arbitrary commands. If those commands produce errors (particularly errors that have a filename, column and line) compilation-mode can colourise these errors and help you navigate to them.
Here I add some bindings and a filter which colourises the output of compilation mode for ANSI escape sequences; the eyecandy is certainly nice but it's very useful when dealing with tools that use those codes so you can actually read the text.
(use-package compile
:defer t
:display
("\\*compilation\\*"
(display-buffer-reuse-window display-buffer-at-bottom)
(reusable-frames . t)
(window-height . 0.25))
:general
(leader
"j" #'next-error
"k" #'previous-error)
(code-leader
"c" #'compile
"C" #'recompile)
(:keymaps 'compilation-mode-map
"g" nil) ;; by default this is recompile
(nmmap
:keymaps 'compilation-mode-map
"c" #'recompile)
:init
(setq compilation-scroll-output 'first-error
compilation-context-lines nil
next-error-highlight 'fringe-arrow)
:config
(add-hook 'compilation-filter-hook #'ansi-color-compilation-filter))
xref
Find definitions, references and general objects using tags without
external packages. Provided out of the box with Emacs, but requires a
way of generating a TAGS file for your project (look at
Project.el for my way of doing so). A critical
component in a minimal setup for programming without heavier systems
like Eglot.
(use-package xref
:defer t
:display
("\\*xref\\*"
(display-buffer-at-bottom)
(inhibit-duplicate-buffer . t)
(window-height . 0.25))
:general
(code-leader
"t" '(nil :which-key "Tags"))
(code-leader
:infix "t"
"t" #'xref-find-apropos
"d" #'xref-find-definitions
"r" #'xref-find-references)
(nmmap
:keymaps 'xref--xref-buffer-mode-map
"RET" #'xref-goto-xref
"J" #'xref-next-line
"K" #'xref-prev-line
"g" #'xref-revert-buffer
"q" #'quit-window))
Project.el
An inbuilt solution for creating and managing projects that doesn't require a dependency. Where possible we should try to use Emacs defaults (admittedly this is a philosophy I've only recently adopted) so when setting up on a new computer it takes a bit less time.
Here I write a TAGS command, mimicking projectile's one, so I can quickly generate them in C/C++ projects.
(use-package project
:defer t
:general
(:keymaps 'project-prefix-map
"R" #'+project/generate-tags)
:config
(defun +project/generate-tags ()
(interactive)
(let ((project (project-current)))
(if (not project)
(message "+project/generate-tags: Not in project.")
(let ((tags-file (concat (project-root project) "TAGS"))
(folder (format "%s" (project-root project))))
(set-process-sentinel
(start-process-shell-command
"PROJECT-GENERATE-TAGS"
"*gen-tags*"
(format "ctags -Re -f %s %s"
tags-file
(concat folder "*")))
(lambda (p event)
(when (string= event "finished\n")
(visit-tags-table (concat (project-root (project-current)) "TAGS"))
(message "Finished generating tags!")))))))))
devdocs
When man pages aren't enough, you need some documentation lookup system (basically whenever your using anything but C/C++/Bash). Devdocs is a great little website that provides a ton of documentation sets. There's an Emacs package for it which works well and downloads documentation sets to my machine, which is nice.
(use-package devdocs
:straight t
:defer t
:general
(file-leader
"d" #'devdocs-lookup))
rainbow-delimiters
Makes colours delimiters (parentheses) based on their depth in an expression. Rainbow flag in your Lisp source code.
(use-package rainbow-delimiters
:defer t
:straight t
:general
(mode-leader "r" #'rainbow-delimiters-mode)
:hook
((lisp-mode-hook emacs-lisp-mode-hook racket-mode-hook) . rainbow-delimiters-mode))
Org mode
Org is, at its most basic, a markup language. org-mode is a major
mode for Emacs to interpret org buffers. org-mode provides a lot of
capabilities, some are:
- A complete table based spreadsheet system, with formulas (including calc-mode integration)
-
Code blocks with proper syntax highlighting and editing experience
- Evaluation
- Export of code blocks to a variety of formats
- Export of code blocks to a code file (so called "tangling", which is what occurs in this document)
-
Feature complete scheduling system with calendar integration
- A clock-in system to time tasks
- TODO system
- Export to a variety of formats or make your own export engine using the org AST.
- Inline $\LaTeX$, with the ability to render the fragments on demand within the buffer
-
Links to a variety of formats:
- Websites (via http or https)
- FTP
- SSH
- Files (even to a specific line)
- Info pages
I'd argue this is a bit more than a markup language. Like Magit, some use Emacs just for this system.
Org Essentials
Org has a ton of settings to tweak, which change your experience quite a bit. Here are mine, but this took a lot of just reading other people's configurations and testing. I don't do a good job of explaining how this works in all honesty, but it works well for me so I'm not very bothered.
- By default
~/Textis my directory for text files. I actually have a repository that manages this directory for agenda files and other documents - Indentation in file should not be allowed, i.e. text indentation, as that forces other editors to read it a certain way as well. It's obtrusive hence it's off.
- Org startup indented is on by default as most documents do benefit
from the indentation, but I do turn it off for some files via
#+startup:noindent - When opening an org document there can be a lot of headings, so I set folding to just content
- Org documents can also have a lot of latex previews, which make opening some after a while a massive hassle. If I want to see the preview, I'll do it myself, so turn it off.
- Org manages windowing itself, to some extent, so I set those options to be as unobtrusive as possible
- Load languages I use in
srcblocks in org-mode (Emacs-lisp for this configuration, C and Python)
(use-package org
:defer t
:init
(setq org-directory "~/Text/"
org-adapt-indentation nil
org-indent-mode nil
org-startup-indented nil
org-startup-folded 'content
org-startup-with-latex-preview nil
org-imenu-depth 10
org-src-window-setup 'current-window
org-indirect-buffer-display 'current-window
org-link-frame-setup '((vm . vm-visit-folder-other-frame)
(vm-imap . vm-visit-imap-folder-other-frame)
(file . find-file))
org-babel-load-languages '((emacs-lisp . t)
(lisp . t)
(shell . t))))
Org Latex
Org mode has deep integration with latex, can export to PDF and even display latex fragments in the document directly. I setup the pdf-process, code listing options via minted and the format options for latex fragments.
(use-package org
:defer t
:init
(setq org-format-latex-options
'(:foreground default :background "Transparent" :scale 4
:html-foreground "Black" :html-background "Transparent"
:html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
org-latex-src-block-backend 'minted
org-latex-minted-langs '((emacs-lisp "common-lisp")
(ledger "text")
(cc "c++")
(cperl "perl")
(shell-script "bash")
(caml "ocaml"))
org-latex-packages-alist '(("" "minted"))
org-latex-pdf-process
(list (concat "latexmk -f -bibtex -pdf "
"-shell-escape -%latex -interaction=nonstopmode "
"-output-directory=%o %f"))
org-latex-minted-options
'(("style" "colorful")
("linenos")
("frame" "single")
("mathescape")
("fontfamily" "courier")
("samepage" "false")
("breaklines" "true")
("breakanywhere" "true"))))
Org Core Variables
Tons of variables for org-mode, including a ton of latex ones. Can't really explain because it sets up quite a lot of local stuff. Also I copy pasted the majority of this, tweaking it till it felt good. Doom Emacs was very helpful here.
(use-package org
:defer t
:init
(setq org-edit-src-content-indentation 0
org-eldoc-breadcrumb-separator " → "
org-enforce-todo-dependencies t
org-export-backends '(ascii html latex odt icalendar)
org-fontify-quote-and-verse-blocks t
org-fontify-whole-heading-line t
org-footnote-auto-label t
org-goto-interface 'outline
org-hide-emphasis-markers nil
org-hide-leading-stars t
org-image-actual-width nil
org-imenu-depth 10
org-link-descriptive nil
org-priority-faces '((?A . error) (?B . warning) (?C . success))
org-refile-targets '((nil . (:maxlevel . 2)))
org-tags-column 0
org-todo-keywords '((sequence "TODO" "WIP" "DONE")
(sequence "PROJ" "WAIT" "COMPLETE"))
org-use-sub-superscripts '{}))
Org Core Functionality
Hooks, prettify-symbols and records for auto insertion.
(use-package org
:defer t
:hook
(org-mode-hook . prettify-symbols-mode)
:display
("\\*Org Src.*"
(display-buffer-same-window))
:auto-insert
(("\\.org\\'" . "Org skeleton")
"Enter title: "
"#+title: " str | (buffer-file-name) "\n"
"#+author: " (read-string "Enter author: ") | user-full-name "\n"
"#+description: " (read-string "Enter description: ") | "Description" "\n"
"#+date: " (format-time-string "%Y-%m-%d" (current-time)) "\n"
"* " _))
Org Core Bindings
A load of bindings for org-mode which binds together a lot of functionality. It's best to read it yourself; to describe it is to write the code.
(use-package org
:defer t
:config
(with-eval-after-load "consult"
(general-def
:keymaps 'org-mode-map
[remap imenu] #'consult-outline))
:general
(file-leader
"l" #'org-store-link
"i" #'org-insert-last-stored-link)
(code-leader
:keymaps 'emacs-lisp-mode-map
"D" #'org-babel-detangle)
(local-leader
:keymaps 'org-mode-map
"l" '(nil :which-key "Links")
"'" '(nil :which-key "Tables")
"c" '(nil :which-key "Clocks")
"r" #'org-refile
"d" #'org-date-from-calendar
"t" #'org-todo
"," #'org-priority
"T" #'org-babel-tangle
"i" #'org-insert-structure-template
"p" #'org-latex-preview
"s" #'org-property-action
"e" #'org-export-dispatch
"o" #'org-edit-special)
(local-leader
:keymaps 'org-mode-map
:infix "l"
"i" #'org-insert-link
"l" #'org-open-at-point
"f" #'org-footnote-action)
(local-leader
:keymaps 'org-mode-map
:infix "'"
"a" #'org-table-align
"c" #'org-table-create
"f" #'org-table-edit-formulas
"t" #'org-table-toggle-coordinate-overlays
"s" #'org-table-sum
"e" #'org-table-calc-current-TBLFM
"E" #'org-table-eval-formula))
Org Agenda
Org agenda provides a nice viewing for schedules. With org mode it's a very tidy way to manage your time.
(use-package org-agenda
:defer t
:init
(defconst +org/agenda-root "~/Text"
"Root directory for all agenda files")
(setq org-agenda-files (list (expand-file-name +org/agenda-root))
org-agenda-window-setup 'current-window
org-agenda-skip-deadline-prewarning-if-scheduled t
org-agenda-skip-scheduled-if-done t
org-agenda-skip-deadline-if-done t
org-agenda-start-with-entry-text-mode nil)
:config
(evil-set-initial-state 'org-agenda-mode 'normal)
:general
(file-leader
"a" `(,(proc (interactive)
(find-file (completing-read "Enter directory: " org-agenda-files nil t)))
:which-key "Open agenda directory"))
(app-leader
"a" #'org-agenda)
(nmmap
:keymaps 'org-agenda-mode-map
"zd" #'org-agenda-day-view
"zw" #'org-agenda-week-view
"zm" #'org-agenda-month-view
"gd" #'org-agenda-goto-date
"RET" #'org-agenda-switch-to
"J" #'org-agenda-later
"K" #'org-agenda-earlier
"t" #'org-agenda-todo
"." #'org-agenda-goto-today
"," #'org-agenda-goto-date
"q" #'org-agenda-quit
"r" #'org-agenda-redo))
Org capture
Org capture provides a system for quickly "capturing" some information into an org file. A classic example is creating a new TODO in a todo file, where the bare minimum to record one is:
- where was it recorded?
- when was it recorded?
- what is it?
Org capture provides a way to do that seamlessly without opening the todo file directly.
(use-package org-capture
:defer t
:init
(setq
org-default-notes-file (concat org-directory "todo.org")
org-capture-templates
'(("t" "Todo" entry
(file "")
"* TODO %?
%T
%a")))
:general
(leader
"C" #'org-capture)
(nmmap
:keymaps 'org-capture-mode-map
"ZZ" #'org-capture-finalize
"ZR" #'org-capture-refile
"ZQ" #'org-capture-kill))
Org clock-in
Org provides a nice timekeeping system that allows for managing how much time is taken per task. It even has an extensive reporting system to see how much time you spend on specific tasks or overall.
(use-package org-clock
:after org
:init
(defvar +org/clock-out-toggle-report nil
"Non-nil means update the first clock report in the file every
time a clock out occurs.")
:config
(advice-add #'org-clock-out
:after
(proc (interactive)
(if +org/clock-out-toggle-report
(org-clock-report t))))
:general
(local-leader
:keymaps 'org-mode-map
:infix "c"
"d" #'org-clock-display
"c" #'org-clock-in
"o" #'org-clock-out
"r" #'org-clock-report
"t" (proc (interactive)
(setq-local +org/clock-out-toggle-report
(not +org/clock-out-toggle-report)))))
WAIT Org ref
For bibliographic stuff in $\LaTeX$ export.
(use-package org-ref
:straight t
:defer t
:init
(setq bibtex-files '("~/Text/bibliography.bib")
bibtex-completion-bibliography '("~/Text/bibliography.bib")
bibtex-completion-additional-search-fields '(keywords)))
Org ref ivy integration
Org ref requires ivy-bibtex to work properly with ivy, so we need to set that up as well
(use-package ivy-bibtex
:straight t
:after org-ref
:config
(require 'org-ref-ivy))
Org message
Org message allows for the use of org mode when composing mails, generating HTML multipart emails. This integrates the WYSIWYG experience with mail in Emacs while also providing powerful text features with basically no learning curve (as long as you've already learnt the basics of org).
(use-package org-msg
:straight t
:hook
(message-mode-hook . org-msg-mode)
(notmuch-message-mode-hook . org-msg-mode)
:config
(setq org-msg-options "html-postamble:nil H:5 num:nil ^:{} toc:nil author:nil email:nil \\n:t tex:dvipng"
org-msg-greeting-name-limit 3)
(add-to-list 'org-msg-enforce-css
'(img latex-fragment-inline
((transform . ,(format "translateY(-1px) scale(%.3f)"
(/ 1.0 (if (boundp 'preview-scale)
preview-scale 1.4))))
(margin . "0 -0.35em")))))
Org for evil
Evil org for some nice bindings.
(use-package evil-org
:straight t
:defer t
:hook (org-mode-hook . evil-org-mode)
:general
(nmmap
:keymaps 'org-mode-map
"TAB" #'org-cycle))
WAIT Org reveal
Org reveal allows one to export org files as HTML presentations via reveal.js. Pretty nifty and it's easy to use.
(use-package ox-reveal
:straight t
:defer t
:init
(setq org-reveal-root "https://cdn.jsdelivr.net/npm/reveal.js"
org-reveal-theme "sky"))
Org superstar
Org superstar adds unicode symbols for headers, much better than the default asterisks.
(use-package org-superstar
:straight t
:defer t
:hook (org-mode-hook . org-superstar-mode))
Org bookmark
I maintain a bookmarks file at ~/Text/bookmarks.org. I would like
the ability to construct new bookmarks and open bookmarks. They may
be either articles I want to read, useful information documents or
just straight up youtube videos. So I wrote a
library myself which does the
appropriate dispatching and work for me. Pretty sweet!
Also I define a template for org-capture here for bookmarks and add it
to the list org-capture-templates.
(use-package org-bookmark
:defer t
:load-path "elisp/"
:general
(file-leader
"b" #'org-bookmark/open-bookmark)
:init
(with-eval-after-load "org-capture"
(add-to-list
'org-capture-templates
'("b" "Bookmark" entry
(file "bookmarks.org")
"* %? :bookmark:
%T
%^{url|%x}p
"
))))
Languages
For a variety of (programming) languages Emacs comes with default modes but this configures them as well as pulls any modes Emacs doesn't come with.
Makefile
Defines an auto-insert for Makefiles. Assumes C but it's very easy to change it for C++.
(use-package make-mode
:defer t
:auto-insert
(("[mM]akefile\\'" . "Makefile skeleton")
""
"CC=gcc
OUT=main.out
LIBS=
ARGS=
RELEASE=0
GFLAGS=-Wall -Wextra -Werror -Wswitch-enum -std=c11
DFLAGS=-ggdb -fsanitize=address -fsanitize=undefined
RFLAGS=-O3
DEPFLAGS=-MT $@ -MMD -MP -MF
ifeq ($(RELEASE), 1)
CFLAGS=$(GFLAGS) $(RFLAGS)
else
CFLAGS=$(GFLAGS) $(DFLAGS)
endif
SRC=src
DIST=build
CODE=$(addprefix $(SRC)/, ) # add source files here
OBJECTS=$(CODE:$(SRC)/%.c=$(DIST)/%.o)
DEPDIR:=$(DIST)/dependencies
DEPS:=$(CODE:$(SRC)/%.c=$(DEPDIR):%.d) $(DEPDIR)/main.d
.PHONY: all
all: $(OUT)
$(OUT): $(DIST)/$(OUT)
$(DIST)/$(OUT): $(OBJECTS) $(DIST)/main.o | $(DIST)
$(CC) $(CFLAGS) $^ -o $@ $(LIBS)
$(DIST)/%.o: $(SRC)/%.c | $(DIST) $(DEPDIR)
$(CC) $(CFLAGS) $(DEPFLAGS) $(DEPDIR)/$*.d -c $< -o $@ $(LIBS)
.PHONY: run
run: $(DIST)/$(OUT)
./$^ $(ARGS)
.PHONY:
clean:
rm -rfv $(DIST)/*
$(DIST):
mkdir -p $(DIST)
$(DEPDIR):
mkdir -p $(DEPDIR)
-include $(DEPS)
"
_))
WAIT SQL
The default SQL package provides support for connecting to common database types (sqlite, mysql, etc) for auto completion and query execution. I don't use SQL currently but whenever I need it it's there.
(use-package sql
:defer t
:init
(setq sql-display-sqli-buffer-function nil))
WAIT Ada
Check out ada-mode, my custom ada-mode
that replaces the default one. This mode just colourises stuff, and
uses eglot and a language server to do the hard work.
(use-package ada-mode
:load-path "elisp/"
:defer t
:config
(with-eval-after-load "eglot"
(add-hook 'ada-mode-hook #'eglot)))
NHexl
Hexl-mode is the inbuilt package within Emacs to edit hex and binary format buffers. There are a few problems with hexl-mode though, including an annoying prompt on revert-buffer.
Thus, nhexl-mode! It comes with a few other improvements. Check out the page yourself.
(use-package nhexl-mode
:straight t
:defer t
:mode ("\\.bin" "\\.out"))
C/C++
Setup for C and C++ modes, using Emacs' default package: cc-mode.
cc-mode
Tons of stuff, namely:
auto-fill-modefor 80 char limit- Some keybindings to make evil statement movement easy
- Lots of pretty symbols
- Indenting options and a nice (for me) code style for C
- Auto inserts to get a C file going
(use-package cc-mode
:defer t
:hook
(c-mode-hook . auto-fill-mode)
(c++-mode-hook . auto-fill-mode)
:general
(:keymaps '(c-mode-map c++-mode-map)
:states '(normal motion visual)
"(" #'c-beginning-of-statement
")" #'c-end-of-statement
"{" #'c-beginning-of-defun
"}" #'c-end-of-defun)
:init
(setq-default c-basic-offset 2)
(setq-default c-auto-newline nil)
(setq-default c-default-style '((other . "user")))
(defun +cc/copyright-notice ()
(let* ((lines (split-string (+license/copyright-notice) "\n"))
(copyright-line (car lines))
(rest (cdr lines)))
(concat
"* "
copyright-line
"\n"
(mapconcat
#'(lambda (x)
(if (string= x "")
""
(concat " * " x)))
rest
"\n"))))
:auto-insert
(("\\.c\\'" . "C skeleton")
""
"/" (+cc/copyright-notice) "\n\n"
" * Created: " (format-time-string "%Y-%m-%d") "\n"
" * Author: " user-full-name "\n"
" * Description: " _ "\n"
" */\n"
"\n")
(("\\.cpp\\'" "C++ skeleton")
""
"/" (+cc/copyright-notice) "\n\n"
" * Created: " (format-time-string "%Y-%m-%d") "\n"
" * Author: " user-full-name "\n"
" * Description: " _ "\n"
" */\n"
"\n")
(("\\.\\([Hh]\\|hh\\|hpp\\|hxx\\|h\\+\\+\\)\\'" . "C / C++ header")
(replace-regexp-in-string "[^A-Z0-9]" "_"
(string-replace "+" "P"
(upcase
(file-name-nondirectory buffer-file-name))))
"/" (+cc/copyright-notice) "\n\n"
" * Created: " (format-time-string "%Y-%m-%d") "\n"
" * Author: " user-full-name "\n"
" * Description: " _ "\n"
" */\n\n"
"#ifndef " str n "#define " str "\n\n" "\n\n#endif")
:config
(c-add-style
"user"
'((c-basic-offset . 2)
(c-comment-only-line-offset . 0)
(c-hanging-braces-alist (brace-list-open)
(brace-entry-open)
(substatement-open after)
(block-close . c-snug-do-while)
(arglist-cont-nonempty))
(c-cleanup-list brace-else-brace)
(c-offsets-alist
(statement-block-intro . +)
(substatement-open . 0)
(access-label . -)
(inline-open . 0)
(label . 0)
(statement-cont . +)))))
Clang format
clang-format is a program that formats C/C++ files. It's highly configurable and quite fast. I have a root configuration in my Dotfiles (check it out here.
Clang format comes inbuilt with clang/LLVM, so it's quite likely to be on your machine.
(use-package clang-format
:load-path "/usr/share/clang/"
:defer t
:after cc-mode
:commands (+code/clang-format-region-or-buffer
clang-format-mode)
:general
(code-leader
:keymaps '(c-mode-map c++-mode-map)
"f" #'clang-format-buffer)
:config
(define-minor-mode clang-format-mode
"On save formats the current buffer via clang-format."
:lighter nil
(let ((save-func (proc (interactive)
(clang-format-buffer))))
(if clang-format-mode
(add-hook 'before-save-hook save-func nil t)
(remove-hook 'before-save-hook save-func t))))
(defun +code/clang-format-region-or-buffer ()
(interactive)
(if (mark)
(clang-format-region (region-beginning) (region-end))
(clang-format-buffer))))
cc org babel
To ensure org-babel executes language blocks of C/C++, I need to load
it as an option in org-babel-load-languages.
(use-package org
:after cc-mode
:init
(org-babel-do-load-languages
'org-babel-load-languages
'((C . t))))
cc compile fsan
Sanitisers are a blessing for C/C++. An additional runtime on top of
the executable which catches stuff like undefined behaviour or memory
leaks make it super easy to see where and how code is failing.
However, by default, Emacs' compilation-mode doesn't understand the
logs fsanitize makes so you usually have to manually deal with it
yourself.
Compilation mode uses regular expressions to figure out whether
something is an error and how to navigate to the file where that error
is located. So adding support for -fsanitize is as simple as making
a regular expression which captures file names and digits
(use-package compile
:after cc-mode
:config
(add-to-list 'compilation-error-regexp-alist-alist
`(fsan ,(rx (seq
line-start " #" digit " 0x" (one-or-more hex) " in "
(1+ word) " "
(group (seq (* any) (or ".c" ".cpp"))) ":"
(group (+ digit))))
1 3 4))
(add-to-list 'compilation-error-regexp-alist
'fsan))
Markdown
Why use Markdown when you have org-mode? Because LSP servers sometimes format their documentation as markdown, which Eglot can use to provide nicer views on docs!
(use-package markdown-mode
:defer t
:straight t)
WAIT D
D is a systems level programming language with C-style syntax. I
think it has some interesting ideas such as a toggleable garbage
collector. Here I just install the D-mode package, enable org-babel
execution of d-mode blocks and alias D-mode with d-mode.
(use-package d-mode
:defer t
:straight t
:config
(fset 'D-mode 'd-mode)
(with-eval-after-load "org-mode"
(setf (alist-get 'd org-babel-load-languages) t)))
WAIT Rust
Rust is the systems programming language that also does web stuff and CLI programs and basically tries to be a jack of all trades. It's got some interesting stuff but most importantly it's very new, so everyone must learn it, right?
(use-package rust-mode
:straight t
:defer t
:general
(code-leader
:keymaps 'rust-mode-map
"f" #'rust-format-buffer)
(local-leader
:keymaps 'rust-mode-map
"c" #'rust-run-clippy)
:init
(setq rust-format-on-save t)
(with-eval-after-load "eglot"
(add-to-list 'eglot-server-programs '(rust-mode "rust-analyzer"))))
WAIT Racket
A scheme with lots of stuff inside it. Using it for a language design book so it's useful to have some Emacs binds for it.
(use-package racket-mode
:straight t
:defer t
:hook (racket-mode-hook . racket-xp-mode)
:display
("\\*Racket REPL*"
(display-buffer-at-bottom)
(window-height . 0.3))
:init
(setq racket-documentation-search-location 'local)
:general
(nmap
:keymaps 'racket-describe-mode-map
"q" #'quit-window)
(nmap
:keymaps 'racket-mode-map
"gr" #'racket-eval-last-sexp)
(local-leader
:keymaps '(racket-mode-map racket-repl-mode-map)
"d" #'racket-repl-describe)
(local-leader
:keymaps 'racket-mode-map
"r" #'racket-run
"i" #'racket-repl
"e" #'racket-send-definition
"sr" #'racket-send-region
"sd" #'racket-send-definition))
WAIT CSharp
Haven't used C# in a while, but Emacs is alright for it with omnisharp.
(use-package csharp-mode
:defer t)
WAIT Java
I kinda dislike Java, but if necessary I will code in it. Just setup a style and some pretty symbols. You can use LSP to get cooler features to be fair.
(use-package ob-java
:defer t
:config
(with-eval-after-load "cc-mode"
(c-add-style
"java"
'((c-basic-offset . 4)
(c-comment-only-line-offset 0 . 0)
(c-offsets-alist
(inline-open . 0)
(topmost-intro-cont . +)
(statement-block-intro . +)
(knr-argdecl-intro . 5)
(substatement-open . 0)
(substatement-label . +)
(label . +)
(statement-case-open . +)
(statement-cont . +)
(arglist-intro . c-lineup-arglist-intro-after-paren)
(arglist-close . c-lineup-arglist)
(brace-list-intro first c-lineup-2nd-brace-entry-in-arglist c-lineup-class-decl-init-+ +)
(access-label . 0)
(inher-cont . c-lineup-java-inher)
(func-decl-cont . c-lineup-java-throws))))
(add-to-list 'c-default-style '(java-mode . "java")))
(with-eval-after-load "abbrev"
(define-abbrev-table 'java-mode-abbrev-table nil)
(add-hook 'java-mode-hook
(proc (setq-local local-abbrev-table java-mode-abbrev-table)))))
WAIT Haskell
Haskell is a static lazy functional programming language (what a mouthful). It's quite a beautiful language and really learning it will change the way you think about programming. However, my preferred functional language is still unfortunately Lisp so no extra brownie points there.
Here I configure the REPL for Haskell via the
haskell-interactive-mode. I also load my custom package
haskell-multiedit which allows a
user to create temporary haskell-mode buffers that, upon completion,
will run in the REPL. Even easier than making your own buffer.
(use-package haskell-mode
:straight t
:defer t
:hook
(haskell-mode-hook . haskell-indentation-mode)
(haskell-mode-hook . interactive-haskell-mode)
:init
(setq haskell-interactive-prompt "[λ] "
haskell-interactive-prompt-cont "{λ} "
haskell-interactive-popup-errors nil
haskell-stylish-on-save t
haskell-process-type 'auto)
:general
(shell-leader
"h" #'haskell-interactive-bring)
(local-leader
:keymaps 'haskell-mode-map
"c" #'haskell-compile
"t" #'haskell-process-do-type)
(nmmap
:keymaps 'haskell-mode-map
"C-c C-c" #'haskell-process-load-file)
(local-leader
:keymaps 'haskell-interactive-mode-map
"c" #'haskell-interactive-mode-clear)
(imap
:keymaps 'haskell-interactive-mode-map
"M-k" #'haskell-interactive-mode-history-previous
"M-j" #'haskell-interactive-mode-history-next)
:display
("\\*haskell.**\\*"
(display-buffer-at-bottom)
(window-height . 0.3))
:config
(load (concat user-emacs-directory "elisp/haskell-multiedit.el")))
Python
Works well for python. If you have pyls it should be on your path, so
just run eglot if you need. But an LSP server is not necessary for a
lot of my time in python. Here I also setup org-babel for python
source code blocks.
(use-package python
:defer t
:pretty
(python-mode-hook
("None" . "Ø")
("list" . "ℓ")
("List" . "ℓ")
("str" . "𝕊")
("True" . "⊨")
("False" . "⊭")
("!" . "¬")
("&&" . "∧")
("||" . "∨")
("for" . "∀")
("print" . "φ")
("lambda" . "λ")
("return" . "⟼")
("yield" . "⟻"))
:init
(setq python-indent-offset 4)
:config
(with-eval-after-load "org-mode"
(setf (alist-get 'python org-babel-load-languages) t)))
Python shell
Setup for python shell, including a toggle option
(use-package python
:defer t
:commands +python/toggle-repl
:general
(shell-leader
"p" #'run-python)
:hook
(inferior-python-mode-hook . company-mode)
:display
("\\*Python\\*"
(display-buffer-at-bottom)
(window-height . 0.25)))
YAML
YAML is a data language which is useful for config files.
(use-package yaml-mode
:straight t)
HTML/CSS/JS
Firstly, web mode for consistent colouring of syntax.
(use-package web-mode
:straight t
:defer t
:mode ("\\.html" . web-mode)
:mode ("\\.css" . web-mode)
:custom
((web-mode-code-indent-offset 2)
(web-mode-markup-indent-offset 2)
(web-mode-css-indent-offset 2)))
Emmet
Emmet for super speed code writing.
(use-package emmet-mode
:straight t
:hook (web-mode-hook . emmet-mode)
:general
(imap
:keymaps 'emmet-mode-keymap
"TAB" #'emmet-expand-line
"M-j" #'emmet-next-edit-point
"M-k" #'emmet-prev-edit-point))
HTML Auto insert
An auto-insert for HTML buffers, which just adds some nice stuff.
(use-package web-mode
:defer t
:auto-insert
(("\\.html\\'" . "HTML Skeleton")
""
"<!doctype html>
<html lang=''>
<head>
<meta charset='utf-8'>
<meta http-equiv='x-ua-compatible' content='ie=edge'>
<title>"(read-string "Enter title: ") | """</title>
<meta name='description' content='" (read-string "Enter description: ") | "" "'>
<meta name='author' content='"user-full-name"'/>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='apple-touch-icon' href='/apple-touch-icon.png'>
<link rel='shortcut icon' href='/favicon.ico'/>
<!-- Place favicon.ico in the root directory -->
</head>
<body>
<!--[if lt IE 8]>
<p class='browserupgrade'>
You are using an <strong>outdated</strong> browser. Please
<a href='http://browsehappy.com/'>upgrade your browser</a> to improve
your experience.
</p>
<![endif]-->
"
_
" </body>
</html>"))
Javascript Mode
A better mode for JavaScript that also has automatic integration with eglot.
(use-package js
:mode ("\\.js" . js-mode)
:hook
(js-mode-hook . auto-fill-mode)
:init
(setq js-indent-level 2))
Typescript
A language that adds a build step to JavaScript projects for "static" typing. It's nice because it adds nice auto completion.
(use-package typescript-mode
:straight t
:defer t
:init
(setq typescript-indent-level 2))
WAIT Scheme
Another Lisp but simpler than the rest. A beauty of engineering and fun to write programs in.
(use-package cmuscheme
:display
("\\*scheme\\*"
(display-buffer-reuse-window display-buffer-at-bottom)
(window-height . 0.25))
:general
(local-leader
:keymaps 'scheme-mode-map
"t" #'run-scheme
"cc" #'scheme-compile-definition
"cf" #'scheme-compile-file
"cr" #'scheme-compile-region
"sf" #'scheme-send-definition
"sr" #'scheme-send-region
"e" #'scheme-send-last-sexp))
WAIT Ocaml
Ocaml Setup
Firstly, install opam and ocaml. Then run the following script:
opam install tuareg ocamlformat odoc utop merlin user-setup
opam user-setup install
mv ~/.emacs.d/opam-user-setup.el ~/.config/emacs/elisp
rm -rf ~/.emacs.d ~/.emacs
This sets up the necessary packages (particularly Emacs Lisp) and some
configuration that ensures Emacs is consistent with the user
installation. Notice the moving of opam-user-setup.el into
~/.config/emacs/elisp, which we'll use to setup the ocaml
experience.
Ocaml Configuration
Here I load the opam-user-setup package setup earlier, with some
neat tips from the default ~/.emacs generated by opam user-setup
install.
(use-package opam-user-setup
:defer t
:load-path "elisp/"
:mode ("\\.ml" . tuareg-mode)
:display
("\\*utop\\*"
(display-buffer-at-bottom)
(window-height . 0.3))
:config
(add-to-list 'compilation-error-regexp-alist-alist
`(ocaml
"[Ff]ile \\(\"\\(.*?\\)\", line \\(-?[0-9]+\\)\\(, characters \\(-?[0-9]+\\)-\\([0-9]+\\)\\)?\\)\\(:\n\\(\\(Warning .*?\\)\\|\\(Error\\)\\):\\)?"
2 3 (5 . 6) (9 . 11) 1 (8 compilation-message-face)))
(add-to-list 'compilation-error-regexp-alist
'ocaml)
:general
(local-leader
:keymaps 'tuareg-mode-map
"u" #'utop)
(local-leader
:keymaps 'tuareg-mode-map
:infix "e"
"r" #'utop-eval-region
"e" #'utop-eval-phrase
"b" #'utop-eval-buffer))
(use-package merlin-eldoc
:straight t
:after opam-user-setup
:hook
(tuareg-mode-hook . merlin-eldoc-setup)
:init
(setq merlin-eldoc-occurrences nil))
Common Lisp
Common Lisp is a dialect of Lisp, the most common one around. Emacs comes with builtin Lisp support, of course, and it's really good in comparison to literally everything else. However, I wish it had a better REPL…
WAIT Sly
Enter SLY. Sly is a fork of SLIME and is mandatory for lisp development on Emacs.
Here I just setup Sly to use sbcl.
(use-package sly
:defer t
:straight t
:init
(setq inferior-lisp-program "sbcl"
sly-lisp-loop-body-forms-indentation 0)
:display
("\\*sly-db"
(display-buffer-at-bottom)
(window-height . 0.5))
("\\*sly-"
(display-buffer-at-bottom)
(window-height . 0.3))
:config
(evil-set-initial-state 'sly-db-mode 'normal)
(with-eval-after-load "org"
(setq-default org-babel-lisp-eval-fn #'sly-eval))
(with-eval-after-load "company"
(add-hook 'sly-mrepl-hook #'company-mode))
:general
(shell-leader
"s" #'sly)
(nmap
:keymaps 'lisp-mode-map
"gr" #'sly-eval-buffer
"gd" #'sly-edit-definition
"gR" #'sly-who-calls)
(local-leader
:keymaps 'lisp-mode-map
"a" '(sly-apropos :which-key "Apropos")
"d" '(sly-describe-symbol :which-key "Describe symbol")
"D" '(sly-documentation-lookup :which-key "Lookup on lispworks")
"l" '(sly-load-file :which-key "Load file")
"c" '(sly-compile-defun :which-key "Compile defun")
"C" '(sly-compile-file :which-key "Compile file")
"S" '(sly-mrepl-sync :which-key "Sync REPL"))
(local-leader
:keymaps 'lisp-mode-map
:infix "e"
"b" #'sly-eval-buffer
"e" #'sly-eval-last-expression
"f" #'sly-eval-defun
"r" #'sly-eval-region)
(nmap
:keymaps 'sly-mrepl-mode-map
"M-j" #'sly-mrepl-next-input-or-button
"M-k" #'sly-mrepl-previous-input-or-button)
(local-leader
:keymaps 'sly-mrepl-mode-map
"s" '(sly-mrepl-shortcut :which-key "Shortcut"))
(nmap
:keymaps 'sly-db-mode-map
"\C-i" 'sly-db-cycle
"g?" 'describe-mode
"S" 'sly-db-show-frame-source
"e" 'sly-db-eval-in-frame
"d" 'sly-db-pprint-eval-in-frame
"D" 'sly-db-disassemble
"i" 'sly-db-inspect-in-frame
"gj" 'sly-db-down
"gk" 'sly-db-up
(kbd "C-j") 'sly-db-down
(kbd "C-k") 'sly-db-up
"]]" 'sly-db-details-down
"[[" 'sly-db-details-up
(kbd "M-j") 'sly-db-details-down
(kbd "M-k") 'sly-db-details-up
"gg" 'sly-db-beginning-of-backtrace
"G" 'sly-db-end-of-backtrace
"t" 'sly-db-toggle-details
"gr" 'sly-db-restart-frame
"I" 'sly-db-invoke-restart-by-name
"R" 'sly-db-return-from-frame
"c" 'sly-db-continue
"s" 'sly-db-step
"n" 'sly-db-next
"o" 'sly-db-out
"b" 'sly-db-break-on-return
"a" 'sly-db-abort
"q" 'sly-db-quit
"A" 'sly-db-break-with-system-debugger
"B" 'sly-db-break-with-default-debugger
"P" 'sly-db-print-condition
"C" 'sly-db-inspect-condition
"g:" 'sly-interactive-eval
"0" 'sly-db-invoke-restart-0
"1" 'sly-db-invoke-restart-1
"2" 'sly-db-invoke-restart-2
"3" 'sly-db-invoke-restart-3
"4" 'sly-db-invoke-restart-4
"5" 'sly-db-invoke-restart-5
"6" 'sly-db-invoke-restart-6
"7" 'sly-db-invoke-restart-7
"8" 'sly-db-invoke-restart-8
"9" 'sly-db-invoke-restart-9)
(nmap
:keymaps 'sly-inspector-mode-map
"q" #'sly-inspector-quit))
WAIT Sly-ASDF
ASDF is the package declaration system that most Common Lisp programmers use. Here's a package which integrates some stuff into SLY for ASDF.
(use-package sly-asdf
:straight t
:after sly)
Emacs lisp
Ligatures and bindings for (Emacs) Lisp. Pretty self declarative.
(use-package elisp-mode
:defer t
:pretty
(lisp-mode-hook
("lambda" . "λ")
("nil" . "Ø")
("<=" . "≤")
(">=" . "≥")
("defun" . "ƒ")
("loop" . "Σ")
("mapcar" . "→")
("reduce" . "↓")
("some" . "∃")
("every" . "∀"))
(emacs-lisp-mode-hook
("lambda" . "λ")
("nil" . "Ø")
("defun" . "ƒ")
("mapcar" . "→"))
:general
(:states '(normal motion visual)
:keymaps '(emacs-lisp-mode-map
lisp-mode-map
lisp-interaction-mode-map)
")" #'sp-next-sexp
"(" #'sp-previous-sexp)
(nmmap
:keymaps '(emacs-lisp-mode-map lisp-interaction-mode-map)
"gr" #'eval-last-sexp)
(vmap
:keymaps '(emacs-lisp-mode-map lisp-interaction-mode-map)
"gr" #'eval-region))
WIP Hydra like Lispy
A Hydra which uses the Lispy package (by
abo-abo) to create a set of motions that allow movement around a lisp
file easily.
2024-04-18: Still working on this, quite rough around the edges.
(use-package lispy
:after (lisp-mode elisp-mode)
:hydra
(hydra-lispy
nil "Move around quickly in Lisp"
("h" #'lispy-left)
("j" ("t" #'lispy-teleport)
#'lispy-down)
("k" #'lispy-up)
("l" #'lispy-right)
("d" #'lispy-different)
("u" #'lispy-flow)
("o" #'lispy-oneline)
("m" #'lispy-multiline)
("N" #'lispy-narrow)
("W" #'lispy-widen)
("c" #'lispy-clone)
("fp" #'lispy-ace-paren)
("fs" #'lispy-ace-symbol :exit t)
("H" #'lispy-slurp)
("L" #'lispy-barf)
("M-h" #'lispy-move-left)
("M-j" #'lispy-move-down)
("M-k" #'lispy-move-up)
("M-l" #'lispy-move-right)
("C-g" nil))
:general
(nmmap
:keymaps '(emacs-lisp-mode-map lisp-mode-map)
"." #'hydra-lispy/body))
Lisp indent function
Add a new lisp indent function which indents newline lists more appropriately.
(use-package lisp-mode
:defer t
:config
(defun +oreo/lisp-indent-function (indent-point state)
(let ((normal-indent (current-column))
(orig-point (point)))
(goto-char (1+ (elt state 1)))
(parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
(cond
;; car of form doesn't seem to be a symbol, or is a keyword
((and (elt state 2)
(or (not (looking-at "\\sw\\|\\s_"))
(looking-at ":")))
(if (not (> (save-excursion (forward-line 1) (point))
calculate-lisp-indent-last-sexp))
(progn (goto-char calculate-lisp-indent-last-sexp)
(beginning-of-line)
(parse-partial-sexp (point)
calculate-lisp-indent-last-sexp 0 t)))
;; Indent under the list or under the first sexp on the same
;; line as calculate-lisp-indent-last-sexp. Note that first
;; thing on that line has to be complete sexp since we are
;; inside the innermost containing sexp.
(backward-prefix-chars)
(current-column))
((and (save-excursion
(goto-char indent-point)
(skip-syntax-forward " ")
(not (looking-at ":")))
(save-excursion
(goto-char orig-point)
(looking-at ":")))
(save-excursion
(goto-char (+ 2 (elt state 1)))
(current-column)))
(t
(let ((function (buffer-substring (point)
(progn (forward-sexp 1) (point))))
method)
(setq method (or (function-get (intern-soft function)
'lisp-indent-function)
(get (intern-soft function) 'lisp-indent-hook)))
(cond ((or (eq method 'defun)
(and (null method)
(> (length function) 3)
(string-match "\\`def" function)))
(lisp-indent-defform state indent-point))
((integerp method)
(lisp-indent-specform method state
indent-point normal-indent))
(method
(funcall method indent-point state))))))))
(setq-default lisp-indent-function #'+oreo/lisp-indent-function))