The following variables are used to tweak some of the configuration pieces for use in the live streams so you might need to adjust them for your local machine if you try to use this configuration directly.
#+begin_src emacs-lisp
;; NOTE: init.el is now generated from Emacs.org. Please edit that file
;; in Emacs and init.el will be generated automatically!
In this document I've added links in many places that lead you to documentation for the various packages we use. If you're looking at this file in Emacs, you can put your cursor on a link and press =C-c C-o= or run =M-x org-open-at-point= to open the link in your web browser.
* Startup Performance
#+begin_src emacs-lisp
;; The default is 800 kilobytes. Measured in bytes.
(setq gc-cons-threshold (* 50 1000 1000))
(defun efs/display-startup-time ()
(message "Emacs loaded in %s with %d garbage collections."
Emacs has a built in package manager but it doesn't make it easy to automatically install packages on a new system the first time you pull down your configuration. [[https://github.com/jwiegley/use-package][use-package]] is a really helpful package used in this configuration to make it a lot easier to automate the installation and configuration of everything else we use.
The auto-package-update package helps us keep our Emacs packages up to date! It will prompt you after a certain number of days either at startup or at a specific time of day to remind you to update your packages.
You can also use =M-x auto-package-update-now= to update right now!
We use the [[https://github.com/emacscollective/no-littering/blob/master/no-littering.el][no-littering]] package to keep folders where we edit files and the Emacs configuration folder clean! It knows about a wide variety of variables for built in Emacs features as well as those from community packages so it can be much easier than finding and setting these variables yourself.
#+begin_src emacs-lisp
;; NOTE: If you want to move everything out of the ~/.emacs.d folder
;; reliably, set `user-emacs-directory` before loading no-littering!
;(setq user-emacs-directory "~/.cache/emacs")
(use-package no-littering)
;; no-littering doesn't set this by default so we must place
;; auto save files in the same path as it uses for sessions
This section configures basic UI settings that remove unneeded elements to make Emacs look a lot more minimal and modern. If you're just getting started in Emacs, the menu bar might be helpful so you can remove the =(menu-bar-mode -1)= line if you'd like to still see that.
I am using the [[https://github.com/tonsky/FiraCode][Fira Code]] and [[https://fonts.google.com/specimen/Cantarell][Cantarell]] fonts for this configuration which will more than likely need to be installed on your machine. Both can usually be found in the various Linux distro package managers or downloaded from the links above.
This configuration uses [[https://evil.readthedocs.io/en/latest/index.html][evil-mode]] for a Vi-like modal editing experience. [[https://github.com/noctuid/general.el][general.el]] is used for easy keybinding configuration that integrates well with which-key. [[https://github.com/emacs-evil/evil-collection][evil-collection]] is used to automatically configure various Emacs modes with Vi-like keybindings for evil-mode.
[[https://github.com/lewang/command-log-mode][command-log-mode]] is useful for displaying a panel showing each key binding you use in a panel on the right side of the frame. Great for live streams and screencasts!
[[https://github.com/hlissner/emacs-doom-themes][doom-themes]] is a great set of themes with a lot of variety and support for many different Emacs modes. Taking a look at the [[https://github.com/hlissner/emacs-doom-themes/tree/screenshots][screenshots]] might help you decide which one you like best. You can also run =M-x counsel-load-theme= to choose between them easily.
[[https://github.com/seagle0128/doom-modeline][doom-modeline]] is a very attractive and rich (yet still minimal) mode line configuration for Emacs. The default configuration is quite good but you can check out the [[https://github.com/seagle0128/doom-modeline#customize][configuration options]] for more things you can enable or disable.
*NOTE:* The first time you load your configuration on a new machine, you'll need to run `M-x all-the-icons-install-fonts` so that mode line icons display correctly.
[[https://github.com/justbur/emacs-which-key][which-key]] is a useful UI panel that appears when you start pressing any key binding in Emacs to offer you all possible completions for the prefix. For example, if you press =C-c= (hold control and press the letter =c=), a panel will appear at the bottom of the frame displaying all of the bindings under that prefix and which command they run. This is very useful for learning the possible key bindings in the mode of your current buffer.
[[https://oremacs.com/swiper/][Ivy]] is an excellent completion framework for Emacs. It provides a minimal yet powerful selection menu that appears when you open files, switch buffers, and for many other tasks in Emacs. Counsel is a customized set of commands to replace `find-file` with `counsel-find-file`, etc which provide useful commands for each of the default completion commands.
[[https://github.com/Yevgnen/ivy-rich][ivy-rich]] adds extra columns to a few of the Counsel commands to provide more information about each item.
prescient.el provides some helpful behavior for sorting Ivy completion candidates based on how recently or frequently you select them. This can be especially helpful when using =M-x= to run commands that you don't have bound to a key but still need to access occasionally.
This Prescient configuration is optimized for use in System Crafters videos and streams, check out the [[https://youtu.be/T9kygXveEz0][video on prescient.el]] for more details on how to configure it!
#+begin_src emacs-lisp
(use-package ivy-prescient
:after counsel
:custom
(ivy-prescient-enable-filtering nil)
:config
;; Uncomment the following line to have sorting remembered across sessions!
[[https://github.com/Wilfred/helpful][Helpful]] adds a lot of very helpful (get it?) information to Emacs' =describe-= command buffers. For example, if you use =describe-function=, you will not only get the documentation about the function, you will also see the source code of the function and where it gets used in other places in the Emacs configuration. It is very useful for figuring out how things work in Emacs.
This is an example of using [[https://github.com/abo-abo/hydra][Hydra]] to design a transient key binding for quickly adjusting the scale of the text on screen. We define a hydra that is bound to =SPC t s= and, once activated, =j= and =k= increase and decrease the text scale. You can press any other key (or =f= specifically) to exit the transient key map.
"Enable Flyspell appropriately for the major mode of the current buffer. Uses `flyspell-prog-mode' for modes derived from `prog-mode', so only strings and comments get checked. All other buffers get `flyspell-mode' to check all text. If flyspell is already enabled, does nothing."
(interactive)
(if (not (symbol-value flyspell-mode)) ; if not already on
(progn
(if (derived-mode-p 'prog-mode)
(progn
(message "Flyspell on (code)")
(flyspell-prog-mode))
;; else
(progn
(message "Flyspell on (text)")
(flyspell-mode 1)))
;; I tried putting (flyspell-buffer) here but it didn't seem to work
)))
(defun flyspell-toggle ()
"Turn Flyspell on if it is off, or off if it is on. When turning on, it uses `flyspell-on-for-buffer-type' so code-vs-text is handled appropriately."
[[https://orgmode.org/][Org Mode]] is one of the hallmark features of Emacs. It is a rich document editor, project planner, task and time tracker, blogging engine, and literate coding utility all wrapped up in one package.
This snippet adds a hook to =org-mode= buffers so that =efs/org-babel-tangle-config= gets executed each time such a buffer gets saved. This function checks to see if the file being saved is the Emacs.org file you're looking at right now, and if so, automatically exports the configuration here to the associated output files.
#+begin_src emacs-lisp
;; Automatically tangle our Emacs.org config file when we save it
The =efs/org-font-setup= function configures various text faces to tweak the sizes of headings and use variable width fonts in most cases so that it looks more like we're editing a document in =org-mode=. We switch back to fixed width (monospace) fonts for code blocks and tables so that they display correctly.
This section contains the basic configuration for =org-mode= plus the configuration for Org agendas and capture templates. There's a lot to unpack in here so I'd recommend watching the videos for [[https://youtu.be/VcgjTEa0kU4][Part 5]] and [[https://youtu.be/PNE-mgkZ6HM][Part 6]] for a full explanation.
[[https://github.com/sabof/org-bullets][org-bullets]] replaces the heading stars in =org-mode= buffers with nicer looking characters that you can control. Another option for this is [[https://github.com/integral-dw/org-superstar-mode][org-superstar-mode]] which we may cover in a later video.
We use [[https://github.com/joostkremers/visual-fill-column][visual-fill-column]] to center =org-mode= buffers for a more pleasing writing experience as it centers the contents of the buffer horizontally to seem more like you are editing a document. This is really a matter of personal preference so you can remove the block below if you don't like the behavior.
#+begin_src emacs-lisp
(defun efs/org-mode-visual-fill ()
(setq visual-fill-column-width 100
visual-fill-column-center-text t)
(visual-fill-column-mode 1))
(use-package visual-fill-column
:hook (org-mode . efs/org-mode-visual-fill))
#+end_src
** Configure Babel Languages
To execute or export code in =org-mode= code blocks, you'll need to set up =org-babel-load-languages= for each language you'd like to use. [[https://orgmode.org/worg/org-contrib/babel/languages.html][This page]] documents all of the languages that you can use with =org-babel=.
Org Mode's [[https://orgmode.org/manual/Structure-Templates.html][structure templates]] feature enables you to quickly insert code blocks into your Org files in combination with =org-tempo= by typing =<= followed by the template name like =el= or =py= and then press =TAB=. For example, to insert an empty =emacs-lisp= block below, you can type =<el= and press =TAB= to expand into such a block.
You can add more =src= block templates below by copying one of the lines and changing the two strings at the end, the first to be the template name and the second to contain the name of the language [[https://orgmode.org/worg/org-contrib/babel/languages.html][as it is known by Org Babel]].
We use the excellent [[https://emacs-lsp.github.io/lsp-mode/][lsp-mode]] to enable IDE-like functionality for many different programming languages via "language servers" that speak the [[https://microsoft.github.io/language-server-protocol/][Language Server Protocol]]. Before trying to set up =lsp-mode= for a particular language, check out the [[https://emacs-lsp.github.io/lsp-mode/page/languages/][documentation for your language]] so that you can learn which language servers are available and how to install them.
The =lsp-keymap-prefix= setting enables you to define a prefix for where =lsp-mode='s default keybindings will be added. I *highly recommend* using the prefix to find out what you can do with =lsp-mode= in a buffer.
The =which-key= integration adds helpful descriptions of the various keys so you should be able to learn a lot just by pressing =C-c l= in a =lsp-mode= buffer and trying different things that you find there.
(setq lsp-keymap-prefix "C-c l") ;; Or 'C-l', 's-l'
:config
(lsp-enable-which-key-integration t))
#+end_src
**** lsp-ui
[[https://emacs-lsp.github.io/lsp-ui/][lsp-ui]] is a set of UI enhancements built on top of =lsp-mode= which make Emacs feel even more like an IDE. Check out the screenshots on the =lsp-ui= homepage (linked at the beginning of this paragraph) to see examples of what it can do.
#+begin_src emacs-lisp
(use-package lsp-ui
:hook (lsp-mode . lsp-ui-mode)
:custom
(lsp-ui-doc-position 'bottom))
#+end_src
**** lsp-treemacs
[[https://github.com/emacs-lsp/lsp-treemacs][lsp-treemacs]] provides nice tree views for different aspects of your code like symbols in a file, references of a symbol, or diagnostic messages (errors and warnings) that are found in your code.
Try these commands with =M-x=:
- =lsp-treemacs-symbols= - Show a tree view of the symbols in the current file
- =lsp-treemacs-references= - Show a tree view for the references of the symbol under the cursor
- =lsp-treemacs-error-list= - Show a tree view for the diagnostic messages in the project
This package is built on the [[https://github.com/Alexander-Miller/treemacs][treemacs]] package which might be of some interest to you if you like to have a file browser at the left side of your screen in your editor.
[[https://github.com/emacs-lsp/lsp-ivy][lsp-ivy]] integrates Ivy with =lsp-mode= to make it easy to search for things by name in your code. When you run these commands, a prompt will appear in the minibuffer allowing you to type part of the name of a symbol in your code. Results will be populated in the minibuffer so that you can find what you're looking for and jump to that location in the code upon selecting the result.
Try these commands with =M-x=:
- =lsp-ivy-workspace-symbol= - Search for a symbol name in the current project workspace
- =lsp-ivy-global-workspace-symbol= - Search for a symbol name in all active project workspaces
[[https://emacs-lsp.github.io/dap-mode/][dap-mode]] is an excellent package for bringing rich debugging capabilities to Emacs via the [[https://microsoft.github.io/debug-adapter-protocol/][Debug Adapter Protocol]]. You should check out the [[https://emacs-lsp.github.io/dap-mode/page/configuration/][configuration docs]] to learn how to configure the debugger for your language. Also make sure to check out the documentation for the debug adapter to see what configuration parameters are available to use for your debug templates!
#+begin_src emacs-lisp
(use-package dap-mode
;; Uncomment the config below if you want all UI panes to be hidden by default!
;; :custom
;; (lsp-enable-dap-auto-configure nil)
;; :config
;; (dap-ui-mode 1)
:commands dap-debug
:config
;; Set up Node debugging
(require 'dap-node)
(dap-node-setup) ;; Automatically installs Node debug adapter if needed
This is a basic configuration for the TypeScript language so that =.ts= files activate =typescript-mode= when opened. We're also adding a hook to =typescript-mode-hook= to call =lsp-deferred= so that we activate =lsp-mode= to get LSP features every time we edit TypeScript code.
#+begin_src emacs-lisp
(use-package typescript-mode
:mode "\\.ts\\'"
:hook (typescript-mode . lsp-deferred)
:config
(setq typescript-indent-level 2))
#+end_src
*Important note!* For =lsp-mode= to work with TypeScript (and JavaScript) you will need to install a language server on your machine. If you have Node.js installed, the easiest way to do that is by running the following command:
We use =lsp-mode= and =dap-mode= to provide a more complete development environment for Python in Emacs. Check out [[https://emacs-lsp.github.io/lsp-mode/page/lsp-pyls/][the =pyls= configuration]] in the =lsp-mode= documentation for more details.
Make sure you have the =pyls= language server installed before trying =lsp-mode=!
#+begin_src sh :tangle no
pip install --user "python-language-server[all]"
#+end_src
There are a number of other language servers for Python so if you find that =pyls= doesn't work for you, consult the =lsp-mode= [[https://emacs-lsp.github.io/lsp-mode/page/languages/][language configuration documentation]] to try the others!
#+begin_src emacs-lisp
(use-package python-mode
:ensure t
:hook (python-mode . lsp-deferred)
:custom
;; NOTE: Set these if Python 3 is called "python3" on your system!
;; (python-shell-interpreter "python3")
;; (dap-python-executable "python3")
(dap-python-debugger 'debugpy)
:config
(require 'dap-python))
#+end_src
You can use the pyvenv package to use =virtualenv= environments in Emacs. The =pyvenv-activate= command should configure Emacs to cause =lsp-mode= and =dap-mode= to use the virtual environment when they are loaded, just select the path to your virtual environment before loading your project.
[[http://company-mode.github.io/][Company Mode]] provides a nicer in-buffer completion interface than =completion-at-point= which is more reminiscent of what you would expect from an IDE. We add a simple configuration to make the keybindings a little more useful (=TAB= now completes the selection and initiates completion at the current location if needed).
We also use [[https://github.com/sebastiencs/company-box][company-box]] to further enhance the look of the completions with icons and better overall presentation.
#+begin_src emacs-lisp
(add-hook 'after-init-hook 'global-company-mode)
(use-package company
:after lsp-mode
:hook (lsp-mode . company-mode)
:bind (:map company-active-map
("<tab>" . company-complete-selection))
(:map lsp-mode-map
("<tab>" . company-indent-or-complete-common))
:custom
(company-minimum-prefix-length 1)
(company-idle-delay 0.0))
(use-package company-box
:hook (company-mode . company-box-mode))
#+end_src
** Projectile
[[https://projectile.mx/][Projectile]] is a project management library for Emacs which makes it a lot easier to navigate around code projects for various languages. Many packages integrate with Projectile so it's a good idea to have it installed even if you don't use its commands directly.
#+begin_src emacs-lisp
(use-package projectile
:diminish projectile-mode
:config (projectile-mode)
:custom ((projectile-completion-system 'ivy))
:bind-keymap
("C-c p" . projectile-command-map)
:init
;; NOTE: Set this to the folder where you keep your Git repos!
[[https://magit.vc/][Magit]] is the best Git interface I've ever used. Common Git operations are easy to execute quickly using Magit's command panel system.
Emacs' built in commenting functionality =comment-dwim= (usually bound to =M-;=) doesn't always comment things in the way you might expect so we use [[https://github.com/redguardtoo/evil-nerd-commenter][evil-nerd-commenter]] to provide a more familiar behavior. I've bound it to =M-/= since other editors sometimes use this binding but you could also replace Emacs' =M-;= binding with this command.
[[https://github.com/Fanael/rainbow-delimiters][rainbow-delimiters]] is useful in programming modes because it colorizes nested parentheses and brackets according to their nesting depth. This makes it a lot easier to visually match parentheses in Emacs Lisp code without having to count them yourself.
#+begin_src emacs-lisp
(use-package rainbow-delimiters
:hook (prog-mode . rainbow-delimiters-mode))
#+end_src
* Terminals
** term-mode
=term-mode= is a built-in terminal emulator in Emacs. Because it is written in Emacs Lisp, you can start using it immediately with very little configuration. If you are on Linux or macOS, =term-mode= is a great choice to get started because it supports fairly complex terminal applications (=htop=, =vim=, etc) and works pretty reliably. However, because it is written in Emacs Lisp, it can be slower than other options like =vterm=. The speed will only be an issue if you regularly run console apps with a lot of output.
One important thing to understand is =line-mode= versus =char-mode=. =line-mode= enables you to use normal Emacs keybindings while moving around in the terminal buffer while =char-mode= sends most of your keypresses to the underlying terminal. While using =term-mode=, you will want to be in =char-mode= for any terminal applications that have their own keybindings. If you're just in your usual shell, =line-mode= is sufficient and feels more integrated with Emacs.
With =evil-collection= installed, you will automatically switch to =char-mode= when you enter Evil's insert mode (press =i=). You will automatically be switched back to =line-mode= when you enter Evil's normal mode (press =ESC=).
Run a terminal with =M-x term!=
*Useful key bindings:*
- =C-c C-p= / =C-c C-n= - go back and forward in the buffer's prompts (also =[[= and =]]= with evil-mode)
- =C-c C-k= - Enter char-mode
- =C-c C-j= - Return to line-mode
- If you have =evil-collection= installed, =term-mode= will enter char mode when you use Evil's Insert mode
;;(setq explicit-zsh-args '()) ;; Use 'explicit-<shell>-args for shell-specific args
;; Match the default Bash shell prompt. Update this if you have a custom prompt
(setq term-prompt-regexp "^[^#$%>\n]*[#$%>] *"))
#+end_src
*** Better term-mode colors
The =eterm-256color= package enhances the output of =term-mode= to enable handling of a wider range of color codes so that many popular terminal applications look as you would expect them to. Keep in mind that this package requires =ncurses= to be installed on your machine so that it has access to the =tic= program. Most Linux distributions come with this program installed already so you may not have to do anything extra to use it.
#+begin_src emacs-lisp
(use-package eterm-256color
:hook (term-mode . eterm-256color-mode))
#+end_src
** vterm
[[https://github.com/akermu/emacs-libvterm/][vterm]] is an improved terminal emulator package which uses a compiled native module to interact with the underlying terminal applications. This enables it to be much faster than =term-mode= and to also provide a more complete terminal emulation experience.
Make sure that you have the [[https://github.com/akermu/emacs-libvterm/#requirements][necessary dependencies]] installed before trying to use =vterm= because there is a module that will need to be compiled before you can use it successfully.
#+begin_src emacs-lisp
(use-package vterm
:commands vterm
:config
(setq term-prompt-regexp "^[^#$%>\n]*[#$%>] *") ;; Set this to match your custom shell prompt
;;(setq vterm-shell "zsh") ;; Set this to customize the shell to launch
(setq vterm-max-scrollback 10000))
#+end_src
** shell-mode
[[https://www.gnu.org/software/emacs/manual/html_node/emacs/Interactive-Shell.html#Interactive-Shell][shell-mode]] is a middle ground between =term-mode= and Eshell. It is *not* a terminal emulator so more complex terminal programs will not run inside of it. It does have much better integration with Emacs because all command input in this mode is handled by Emacs and then sent to the underlying shell once you press Enter. This means that you can use =evil-mode='s editing motions on the command line, unlike in the terminal emulator modes above.
*Useful key bindings:*
- =C-c C-p= / =C-c C-n= - go back and forward in the buffer's prompts (also =[[= and =]]= with evil-mode)
- =M-p= / =M-n= - go back and forward in the input history
- =C-c C-u= - delete the current input string backwards up to the cursor
- =counsel-shell-history= - A searchable history of commands typed into the shell
One advantage of =shell-mode= on Windows is that it's the only way to run =cmd.exe=, PowerShell, Git Bash, etc from within Emacs. Here's an example of how you would set up =shell-mode= to run PowerShell on Windows:
#+begin_src emacs-lisp
(when (eq system-type 'windows-nt)
(setq explicit-shell-file-name "powershell.exe")
(setq explicit-powershell.exe-args '()))
#+end_src
** Eshell
[[https://www.gnu.org/software/emacs/manual/html_mono/eshell.html#Contributors-to-Eshell][Eshell]] is Emacs' own shell implementation written in Emacs Lisp. It provides you with a cross-platform implementation (even on Windows!) of the common GNU utilities you would find on Linux and macOS (=ls=, =rm=, =mv=, =grep=, etc). It also allows you to call Emacs Lisp functions directly from the shell and you can even set up aliases (like aliasing =vim= to =find-file=). Eshell is also an Emacs Lisp REPL which allows you to evaluate full expressions at the shell.
The downsides to Eshell are that it can be harder to configure than other packages due to the particularity of where you need to set some options for them to go into effect, the lack of shell completions (by default) for some useful things like Git commands, and that REPL programs sometimes don't work as well. However, many of these limitations can be dealt with by good configuration and installing external packages, so don't let that discourage you from trying it!
*Useful key bindings:*
- =C-c C-p= / =C-c C-n= - go back and forward in the buffer's prompts (also =[[= and =]]= with evil-mode)
- =M-p= / =M-n= - go back and forward in the input history
- =C-c C-u= - delete the current input string backwards up to the cursor
- =counsel-esh-history= - A searchable history of commands typed into Eshell
We will be covering Eshell more in future videos highlighting other things you can do with it.
For more thoughts on Eshell, check out these articles by Pierre Neidhardt:
Dired is a built-in file manager for Emacs that does some pretty amazing things! Here are some key bindings you should try out:
*** Key Bindings
**** Navigation
*Emacs* / *Evil*
- =n= / =j= - next line
- =p= / =k= - previous line
- =j= / =J= - jump to file in buffer
- =RET= - select file or directory
- =^= - go to parent directory
- =S-RET= / =g O= - Open file in "other" window
- =M-RET= - Show file in other window without focusing (previewing files)
- =g o= (=dired-view-file=) - Open file but in a "preview" mode, close with =q=
- =g= / =g r= Refresh the buffer with =revert-buffer= after changing configuration (and after filesystem changes!)
**** Marking files
- =m= - Marks a file
- =u= - Unmarks a file
- =U= - Unmarks all files in buffer
- =* t= / =t= - Inverts marked files in buffer
- =% m= - Mark files in buffer using regular expression
- =*= - Lots of other auto-marking functions
- =k=/ =K= - "Kill" marked items (refresh buffer with =g= /=g r= to get them back)
- Many operations can be done on a single file if there are no active marks!
**** Copying and Renaming files
- =C= - Copy marked files (or if no files are marked, the current file)
- Copying single and multiple files
- =U= - Unmark all files in buffer
- =R= - Rename marked files, renaming multiple is a move!
- =% R= - Rename based on regular expression: =^test= , =old-\&=
*Power command*: =C-x C-q= (=dired-toggle-read-only=) - Makes all file names in the buffer editable directly to rename them! Press =Z Z= to confirm renaming or =Z Q= to abort.
**** Deleting files
- =D= - Delete marked file
- =d= - Mark file for deletion
- =x= - Execute deletion for marks
- =delete-by-moving-to-trash= - Move to trash instead of deleting permanently
**** Creating and extracting archives
- =Z= - Compress or uncompress a file or folder to (=.tar.gz=)
- =c= - Compress selection to a specific file
- =dired-compress-files-alist= - Bind compression commands to file extension
This is an example of configuring another non-Emacs application using org-mode. Not only do we write out the configuration at =.config/some-app/config=, we also compute the value that gets stored in this configuration from the Emacs Lisp block above it.
#+NAME: the-value
#+begin_src emacs-lisp :tangle no
(+ 55 100)
#+end_src
*NOTE*: Set the =:tangle= parameter below to =.config/some-app/config= for this to work!
#+begin_src conf :tangle no :noweb yes
value=<<the-value()>>
#+end_src
* Runtime Performance
Dial the GC threshold back down so that garbage collection happens more frequently but in less time.
#+begin_src emacs-lisp
;; Make gc pauses faster by decreasing the threshold.