#+TITLE: mssola's GNU Emacs configuration
#+AUTHOR: Miquel Sabaté Solà
#+EMAIL: mikisabate@gmail.com
#+HTML_HEAD: <link rel="stylesheet" href="http://jo.mssola.com/stylesheets/main.css" type="text/css" />
#+HTML_HEAD: <link rel="stylesheet" href="http://jo.mssola.com/stylesheets/emacs.css" type="text/css" />
#+BABEL: :cache yes
#+PROPERTY: header-args :tangle ~/.emacs.d/init.el

* Preface

This is my attempt of getting my configuration organized with literate programming and =org-babel=. I took the workflow I'm following from [[https://github.com/larstvei][@larstvei]]. The idea is that the =init.el= file will replace itself on the first execution with the tangled version of this file. This first version will also be byte-compiled. This means that all changes are to be made on the =init.org= file *always*. The initial contents of the =init.el= are:

#+BEGIN_SRC elisp :tangle no
;; We can't tangle without org!
(require 'org)

;; Follow symlinks
(setq vc-follow-symlinks t)

;; Open the configuration
(find-file (concat user-emacs-directory "init.org"))

;; Tangle it
(org-babel-tangle)

;; Load it
(load-file (concat user-emacs-directory "init.el"))

;; Finally byte-compile it
(byte-compile-file (concat user-emacs-directory "init.el"))
#+END_SRC

There is no reason to track the =init.el= file, and no reason to change this file. In order to ensure this, make sure to apply the following command after cloning:

#+BEGIN_SRC sh :tangle no
git update-index --assume-unchanged emacs/init.el
#+END_SRC

From now on our code will be tangled, meaning that it will go into the final =init.el= file. For starters, let's have a good header:

#+BEGIN_SRC elisp
;;; init.el --- init file -*- lexical-binding: t; -*-
;;
;; Copyright (C) 2016-2020 Miquel Sabaté Solà <mikisabate@gmail.com>
;;
;; Author: Miquel Sabaté Solà <mikisabate@gmail.com>
;; Version: 0.1
;; Package-Requires: ((emacs "25.3"))
;; Keywords: convenience, extensions, files, frames, mail, matching, terminals, tools, vc, wp
;; URL: https://github.com/mssola/dotfiles
;;
;; This file is not part of GNU Emacs.
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; 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
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <http://www.gnu.org/licenses/>.
;;
;;; Commentary:
;;
;; This file has been autogenerated by `org-mode', by tangling what I had in my
;; init.org.
;;
;; NOTE: DO NOT MODIFY THIS FILE.  All changes should go into init.org.

;;; Code:
#+END_SRC

Moreover, in order to avoid manually tangling and compiling the =init.org= file
on each change, the following function is provided:

#+BEGIN_SRC elisp
(defun tangle-init ()
  "If the current buffer is 'init.org' the code-blocks are
  tangled, and the tangled file is compiled. Morever, an init.html is generated."

  (when (or (equal (buffer-file-name)
                   (expand-file-name (concat user-emacs-directory "init.org")))
            (string-suffix-p "dotfiles/.emacs.d/init.org" (buffer-file-name)))

    ;; Avoid running hooks when tangling
    (let ((prog-mode-hook nil))
      (org-babel-tangle)
      (byte-compile-file (concat user-emacs-directory "init.el"))
      (remove-hook 'emacs-lisp-mode-hook 'soria-theme-purple-identifiers)
      (org-html-export-to-html)
      (add-hook 'emacs-lisp-mode-hook 'soria-theme-purple-identifiers))))

(add-hook 'after-save-hook 'tangle-init)
#+END_SRC

As you can see, this function will tangle and compile the resulting =init.el= file, and it will also produce an HTML version of it. This HTML version will be pushed into my [[http://jo.mssola.com][personal site]] thanks to a git [[https://github.com/mssola/dotfiles/blob/master/.emacs.d/pre-push][pre-push]] hook. The resulting version being hosted [[http://jo.mssola.com/static/init.html][here]].

Other than that, I run GNU Emacs in server mode, but I don't use systemd for that. Instead, I'm using the =-a= argument of =emacsclient= with an empty string. This instructs =emacsclient= to spawn a new server if there isn't one already. This means that the first time around it will take some time, but in the next time everything will be alright. All this is handled outside of this configuration, by adding some handy scripts like =e= and =emacsclient-a-nw= that can be found inside of the =bin= directory from my dotfiles, and that they are later picked up by various config files such as =.bashrc=, =.gitconfig=, =i3= and such.

* Introduction

I'm using GNU Emacs 27, but everything should be working since GNU Emacs 24. There are some exceptions to this (e.g. webkit support), but these cases are individually handled. In the following block we define some handy constants that will be used throughout this configuration in order to support multiple versions of GNU Emacs. Moreover, this block also checks the version being used and errors out if you are using a GNU Emacs that is just too old for this configuration.

#+BEGIN_SRC elisp
(defconst EMACS-25-OR-LATER (>= emacs-major-version 25)
  "Whether we are using GNU Emacs 25.x or later")

(defconst EMACS-26-OR-LATER (>= emacs-major-version 26)
  "Whether we are using GNU Emacs 26.x or later")

(defconst EMACS-27-OR-LATER (>= emacs-major-version 27)
  "Whether we are using GNU Emacs 27.x or later")

(let ((minver "25.3")
      (recver "26.1"))
  (when (version< emacs-version minver)
    (error "Don't be a cheap bastard and upgrade to at least GNU Emacs v%s" minver))

  (when (version< emacs-version recver)
    (message "Your GNU Emacs is a bit old and some functionality will be disabled.  Consider upgrading to at least v%s" recver)))
#+END_SRC

After that, we do the same for the operating system:

#+BEGIN_SRC elisp
(defconst IS-LINUX (eq system-type 'gnu/linux)
  "Current system is GNU/Linux")

(defconst IS-MAC (eq system-type 'darwin)
  "Current system is MacOS")

(unless (or IS-LINUX IS-MAC)
  (error "This configuration has been checked only on GNU/Linux and MacOS"))
#+END_SRC

Now, here we have a little hack that has been popularized by the community but that I originally took from [[https://github.com/purcell][@purcell]] and later refined by looking at [[https://github.com/hlissner/doom-emacs][doom-emacs]]: let's temporarily reduce garbage collection so startup time is lower. That is, we disable GC and later we enable it back again after GNU Emacs is done evaluating our =init.el= file. This is done so GC does not interfere with the evaluation of a rather big file (and the evaluation of the /many/ packages being installed), and so we gain a good 0.4s in my workstation.

That being said, all of this is done in the =early-init.el= file for GNU Emacs 27 and later, so we have this gain as soon as possible.

#+BEGIN_SRC elisp
(unless EMACS-27-OR-LATER
  (defconst mssola-initial-gc-cons-threshold gc-cons-threshold
    "Initial value of `gc-cons-threshold' at start-up time.")

  (defconst mssola-initial-gc-cons-percentage gc-cons-percentage
    "Initial value of `gc-cons-percentage' at start-up time.")

  ;; Completely disable the GC by having a ginormous threshold.
  (setq gc-cons-threshold most-positive-fixnum
        gc-cons-percentage 0.6))

;; Enable the GC back again to its previous values. This should also be set here
;; for GNU Emacs 27 and later because the early-init.el purposely does not
;; fiddle with this hook.
(add-hook 'after-init-hook
          (lambda ()
            (setq gc-cons-threshold mssola-initial-gc-cons-threshold
                  gc-cons-percentage mssola-initial-gc-cons-percentage)))
#+END_SRC

There are some packages that expect us to have a =user-full-name= and a =user-mail-address= defined. Let's do it now so from now on these packages can get these values right:

#+BEGIN_SRC elisp
(setq user-full-name "Miquel Sabaté Solà"
      user-mail-address "mikisabate@gmail.com")
#+END_SRC

* Lisp packages
** Custom packages

Some years ago I came up with a shell script named [[https://github.com/mssola/g][g]] that deals with path shortcuts. I use this script a *lot* in the shell, and it occurred to me that it would be quite handy to also have a version of it en Emacs Lisp. I don't use it very often (because I usually navigate by projects), but when I do use it it's pretty darn useful. So, before we start dealing with packaging in general, let's compile it now and bind it to @@html:<kbd>M-g</kbd>@@.

#+BEGIN_SRC elisp
(if (file-exists-p (concat user-emacs-directory "lisp/g.elc"))
    (let ((load-prefer-newer t))
      (load-file (concat user-emacs-directory "lisp/g.elc")))
  (byte-compile-file (concat user-emacs-directory "lisp/g.el") t))

(global-set-key (kbd "M-g") 'g)
#+END_SRC

** use-package

GNU Emacs has a built-in packaging utility, =package=, and we rely on that heavily. Now it's the time to setup the repositories (or «package archives», as they are called in GNU Emacs), and initialize packaging. Before doing that, though, let's take a couple of things into account:

1. Since GNU Emacs 27.x I handle this through the =early-init.el= file.
2. GNU Emacs 26.2 had a nasty bug when it comes to gnutls that was work-arounded by setting an algorithm priority.

These are the two main weird things you will see from an otherwise pretty standard code block:

#+BEGIN_SRC elisp
(unless EMACS-27-OR-LATER
  (require 'package)

  (when (version= "26.2" emacs-version)
    (setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3"))

  (setq package-archives
        '(("gnu"          . "https://elpa.gnu.org/packages/")
          ("MELPA Stable" . "https://stable.melpa.org/packages/")
          ("MELPA"        . "https://melpa.org/packages/")
          ("org"          .  "https://orgmode.org/elpa/"))
        package-archive-priorities
        '(("MELPA Stable" . 15)
          ("org"          . 10)
          ("gnu"          . 5)
          ("MELPA"        . 0)))

  (package-initialize))
#+END_SRC

After that has been done we could go around calling =(package-install 'package)= like crazy. However, the community has come up with some tooling around it that makes its usage more appealing. There are quite a lot of options, but I'm sticking with [[https://github.com/jwiegley/use-package][use-package]], simply because it's the first one that I looked into and that filled my needs. With this package I will be able to make sure that all my packages are installed properly in a rather clean way.

#+BEGIN_SRC elisp
(unless (package-installed-p 'use-package)
  (package-refresh-contents)
  (package-install 'use-package))

(require 'use-package)
#+END_SRC

* General
** GUI

Over the years I've come to appreciate more and more minimalistic GUIs. That is, I don't want too many things distracting me from what I care the most: text. As you will see, I disable basically every possible GUI element out there. For starters, let's disable the menu, scroll and tool bars.

#+BEGIN_SRC elisp
(menu-bar-mode -1)
(when (fboundp 'set-scroll-bar-mode)
  (set-scroll-bar-mode nil))
(when (fboundp 'tool-bar-mode)
  (tool-bar-mode -1))
(when (fboundp 'tooltip-mode)
  (tooltip-mode 0))
#+END_SRC

We have nuked the scroll bar, but we have to scroll anyways, so let's tune the relevant variables so this experience is as smooth as possible:

#+BEGIN_SRC elisp
(setq scroll-margin 0
      scroll-conservatively 100000
      scroll-preserve-screen-position 1)
#+END_SRC

That being said, and as to not lose some relevant information hinted by these elements, let's put some additional info into the modeline. That is, let's enable there line, column and size indications.

#+BEGIN_SRC elisp
(line-number-mode 1)
(column-number-mode 1)
(size-indication-mode 1)
#+END_SRC

At this point we have basically cleared away everything between our eyes and the text, but in some cases (i.e. programming) it's useful to have line numbers inside of the window as well. In particular, I've grown quite fond of relative line numbers, which was supported by Vim a long time ago and landed in GNU Emacs 26.1. Let's enable them now (don't worry, you can always toggle that by pressing @@html:<kbd>C-c L</kbd>@@):

#+BEGIN_SRC elisp
(when EMACS-26-OR-LATER
  (add-hook 'prog-mode-hook 'display-line-numbers-mode)
  (setq display-line-numbers-type 'relative)
  (global-set-key (kbd "C-c L") 'display-line-numbers-mode))
#+END_SRC

Now it's the time to talk about the frame title and the icon title. That is, what should GNU Emacs tell the WM which title to display for the window (notice the difference between the concepts of "window" and "frame" in GNU Emacs and the rest of the world). In my case, I like a format like "<login>: <path>" (e.g. "mssola: ~/src/something-cool/main.c"). If we are not editing a file, then the name of the buffer is displayed (e.g. "mssola: *scratch*").

#+BEGIN_SRC elisp
(setq frame-title-format
      (setq icon-title-format '((:eval (concat (user-real-login-name) ": "
                                               (if (buffer-file-name)
                                                   (abbreviate-file-name (buffer-file-name))
                                                 "%b"))))))
#+END_SRC

The final element of the GUI to talk about is the modeline. I've tried in the past to come up with something fancy from my own, but =doom-modeline= is simply way cooler than anything I've tried to setup. Thus, I'm sticking with it. Furthermore, this modeline has a dependency, =all-the-icons=, that needs to download some fonts in order to work. These fonts will be automatically installed to the proper destination if they do not exist yet (unless we are in non-interactive mode). Other than that, =doom-modeline= is quite hackable, but here I only tweak a couple of options when it comes to the display of some of the icons.

#+BEGIN_SRC elisp
(use-package all-the-icons
  :ensure t
  :config
  ;; Check if the fonts have been already been installed. If that is not the
  ;; case, then install it now. The path detection is based from
  ;; all-the-icons.el.
  (let* ((font-dest (if IS-LINUX
                        (concat (or (getenv "XDG_DATA_HOME")
                                    (concat (getenv "HOME") "/.local/share"))
                                "/fonts/")
                      (if IS-MAC
                          (concat (getenv "HOME") "/Library/Fonts/")
                        nil)))
         (ttf-path (concat font-dest "all-the-icons.ttf")))

    ;; If we were able to detect the OS and we don't have a the file installed,
    ;; try to do it now (unless we are running in non-interactive mode).
    (when (and font-dest (not (file-exists-p ttf-path)) (not noninteractive))
      (message "Installing fonts...")
      (all-the-icons-install-fonts))))

(use-package doom-modeline
  :ensure t
  :after all-the-icons
  :init
  ;; We are using the default values except for a couple of values, mainly
  ;; around icons.
  (setq doom-modeline-height 20
        doom-modeline-mu4e t
        doom-modeline-persp-name nil
        doom-modeline-major-mode-icon nil
        doom-modeline-modal-icon t
        doom-modeline-icon t
        doom-modeline-buffer-file-name-style 'relative-from-project)

  ;; And finally enable it.
  (doom-modeline-mode 1))
#+END_SRC

Finally, do not resize the frame when a newly set font is different than the system's default. This does not hit us and it allows some performance gains: around 0.3s when starting GNU Emacs in GUI mode, but negligible when in text mode.

#+BEGIN_SRC elisp
(setq frame-inhibit-implied-resize t)
#+END_SRC

** Basic editing configuration

Now that the GUI is all nice and well, let's configure a bit our editting experience (just a bit, because most of the heavy lifting will be done via packages). First of all, and I cannot stress this enough, use UTF-8 *always*:

#+BEGIN_SRC elisp
  (prefer-coding-system 'utf-8)
  (set-default-coding-systems 'utf-8)
  (set-terminal-coding-system 'utf-8)
  (set-keyboard-coding-system 'utf-8)
  (set-language-environment 'utf-8)
#+END_SRC

GNU Emacs modes typically provide a standard means to change the indentation width (e.g. c-basic-offset), and that will inevitably conflict with the "tabs vs spaces" question and the myriad of code conventions for each programming language. We will deal with all this [[sec:tabsvsspaces][later]]. For this reason we will disable this right now:

#+BEGIN_SRC elisp
(setq-default indent-tabs-mode nil)
(setq-default tab-width 4)
#+END_SRC

As for word wrapping and filling we will take a conservative default, and later we will discard it for some modes. For example, it makes sense to perform auto-fill in =text-mode= (which includes =org-mode=), but there is no point of doing it in source code.

#+BEGIN_SRC elisp
;; Maximum 80 columns (except in text-mode, which includes org mode)
(setq-default fill-column 80)
(setq-default auto-fill-function 'do-auto-fill)

;; Do not break lines
(set-default 'truncate-lines t)
#+END_SRC

It's pretty bananas that I have to say it, but if I've pressed a key when selecting text, I want that text to be nuked and replaced with whatever I've typed. This will be overriden anyways with =evil-mode=, but let's do this now just in case =evil-mode= is disabled or something.

#+BEGIN_SRC elisp
;; Delete the selection with a keypress.
(delete-selection-mode t)
#+END_SRC

There are uncivilized barbarians that do not delete trailing whitespaces. This is not my case.

#+BEGIN_SRC elisp
(add-hook 'before-save-hook #'delete-trailing-whitespace)
#+END_SRC

And finally, let's make the cursor a little more relevant. For starters, the default of the cursor blinking is plain idiotic. Secondly, I don't want special highlighting for the current line. And finally, I'd like matching parenthesis to say something whenever the cursor is on top of one of them.

#+BEGIN_SRC elisp
(blink-cursor-mode 0)
(global-hl-line-mode -1)
(show-paren-mode 1)
#+END_SRC

** Font and theme

I'm using "Droid Sans Mono" simply because I've grown used to it.

#+BEGIN_SRC elisp
(defconst mssola-font
  (if IS-MAC "Droid Sans Mono-12" "Droid Sans Mono Dotted for Powerline-10")
  "The font to be used.")

(add-to-list 'default-frame-alist `(font . ,mssola-font))

;; Emacs in daemon mode does not like `set-face-attribute` because this is only
;; applied if there is a frame in place, which doesn't happen when starting the
;; daemon. Thus, we should call that after the frame has been created (e.g. by
;; emacsclient).  See:
;; https://lists.gnu.org/archive/html/help-gnu-emacs/2015-03/msg00016.html
(add-hook 'after-make-frame-functions-hook
          (lambda ()
            (set-face-attribute 'default t :font mssola-font)))
#+END_SRC

I've hacked my own theme called [[https://github.com/mssola/soria][soria]]. This theme combines the vim theme [[http://www.vim.org/scripts/script.php?script_id=2140][xoria256]] with the [[http://opensuse.github.io/branding-guidelines/][openSUSE branding guidelines]]. This theme lives directly inside of my =~/.emacs.d= directory because I link it from the local copy I have of its git repository.

#+BEGIN_SRC elisp
(load-theme 'soria t)
#+END_SRC

Moreover, let's also enable =highlight-numbers-mode=, so all numbers (regardless of the format) are properly highlighted:

#+BEGIN_SRC elisp
(use-package highlight-numbers
  :ensure t
  :config
  (add-hook 'prog-mode-hook 'highlight-numbers-mode))
#+END_SRC

When hacking your own theme, sometimes you want to know what face is the one that you see on the screen right now. This function from [[https://github.com/thblt/DotFiles][@thblt]] allows me to get exactly that and it's bound to @@html:<kbd>C-c f</kbd>@@:

#+BEGIN_SRC elisp
(defun mssola-face-at-point (pos)
  "Writes a message with the name of the face at the current point.  The POS
  argument contains the current position of the cursor."

  (interactive "d")

  (let ((face (or (get-char-property (point) 'read-face-name)
                  (get-char-property (point) 'face))))
    (if face (message "Face: %s" face) (message "No face at %d" pos))))

(global-set-key (kbd "C-c f") 'mssola-face-at-point)
#+END_SRC

** General global key bindings

Now, this section is full of general miscellaneous stuff. First of all, use =kill-this-buffer= instead of =kill-buffer=, which is utterly pointless when interacting with GNU Emacs as a user. Moreover, I'm using the similar @@html:<kbd>C-x K</kbd>@@ as a binding for killing the current buffer and window.

#+BEGIN_SRC elisp
(global-set-key (kbd "C-x k") 'kill-this-buffer)
(global-set-key (kbd "C-x K") 'kill-buffer-and-window)
#+END_SRC

Window navigation and management is done through =evil-mode=, which basically sets up everything as in the Vim world. That being said, there are a couple of functions that fall out of =evil='s scope which I previously setup with =evil-leader=: creating a window on the right, and creating a window on the right and directly moving to it. This can be done with GNU Emacs' default bindings, but they are not really intuitive, and Vim's default behavior is also not satisfactory. The solution adopted is to trash =vc-mode= and remove its @@html:<kbd>C-x v</kbd>@@ binding, since I never use this mode (which is pointless with =magit= enabled), and it follows the same key chord as I used in my =evil-leader= times. Thus, we have @@html:<kbd>C-x v</kbd>@@ for creating a window on the right, and @@html:<kbd>C-x V</kbd>@@ for creating a window on the right and moving to it.

#+BEGIN_SRC elisp
(global-set-key (kbd "C-x v") 'split-window-right)
(global-set-key (kbd "C-x V") (lambda () (interactive) (split-window-right) (other-window 1)))
#+END_SRC

Disable @@html:<kbd>C-z</kbd>@@, which will be later on be picked up by =evil-mode= configuration as the escape sequence. This is here to make sure that it will be disabled even if =evil-mode= is not on.

#+BEGIN_SRC elisp
  (global-unset-key (kbd "C-z"))
#+END_SRC

Also disable the @@html:<kbd>C-x i</kbd>@@ binding, since I've never used the default behavior, and it will be used as a prefix for inferior modes (e.g. =ielm=).

#+BEGIN_SRC elisp
  (global-unset-key (kbd "C-x i"))
#+END_SRC

Disable all the Fn keys.

#+BEGIN_SRC elisp
  (dotimes (i 12) (global-unset-key (kbd (format "<f%d>" (+ i 1)))))
#+END_SRC

Disable overwrite-mode.

#+BEGIN_SRC elisp
  (define-key global-map [(insert)] nil)
#+END_SRC

Kill GNU Emacs by hitting @@html:<kbd>C-x r q</kbd>@@ (mnemonic /Really quit/).

#+BEGIN_SRC elisp
  (global-set-key (kbd "C-x r q") 'kill-emacs)
#+END_SRC

** Others

Revert buffers automatically when underlying files are changed externally.

#+BEGIN_SRC elisp
  (global-auto-revert-mode t)
#+END_SRC

Follow symlinks.

#+BEGIN_SRC elisp
  (setq vc-follow-symlinks t)
#+END_SRC

Remove the initial message from the scratch buffer.

#+BEGIN_SRC elisp
  (setq initial-scratch-message nil)
#+END_SRC

No backups: they are more of a nuisance that an actual help...

#+BEGIN_SRC elisp
  (setq-default make-backup-files nil)
  (setq-default auto-save-default nil)
#+END_SRC

... but at least save the list of recently opened files (list available by pressing @@html:<kbd>C-x C-r</kbd>@@).

#+BEGIN_SRC elisp
(require 'recentf)

(recentf-mode 1)
(global-set-key "\C-x\ \C-r" 'recentf-open-files)

;; Save the list every 5 minutes
(run-at-time nil (* 5 60) 'recentf-save-list)
#+END_SRC

No welcome screen:

#+BEGIN_SRC elisp
  (setq-default inhibit-startup-message t)
#+END_SRC

Enable y/n answer:

#+BEGIN_SRC elisp
  (fset 'yes-or-no-p 'y-or-n-p)
#+END_SRC

Save custom-variables somewhere else:

#+BEGIN_SRC elisp
  (setq custom-file (expand-file-name "custom.el" user-emacs-directory))
  (if (file-exists-p custom-file)
      (load custom-file))
#+END_SRC

There is somewhere someone who likes to be interrupted with stupid beep sounds. That sorry soul is not me.

#+BEGIN_SRC elisp
(setq ring-bell-function 'ignore)
#+END_SRC

* Calendar

This section used to be more lively because of =evil-mode=, but since I also included =evil-collection= this was largely simplified. Thus, the calendar configuration is only about the week start day and its global key binding @@html:<kbd>M-c</kbd>@@.

#+BEGIN_SRC elisp
(defvar calendar-week-start-day 1)
(global-set-key (kbd "M-c") 'calendar)
#+END_SRC

* General purpose defuns

In this section I stow general purpose functions. Right now there is only one of such kind, =emacs-init-time=, which is useful when debugging the initialization process:

#+BEGIN_SRC elisp
(defun emacs-init-time ()
  "Redefine the `emacs-init-time' function so it is more detailed.
Idea taken from @purcell."

  (interactive)

  (let ((init-time
         (float-time (time-subtract after-init-time before-init-time))))
    (message "%.3fs" init-time)))
#+END_SRC

* Projects

In my case GNU Emacs works in projects (with some exceptions). Working in projects means that I should be able to access them with a simple key binding regardless on how and from where I've started GNU Emacs. This is accomplished mainly with =projectile=. My configuration for it is not too fancy:

#+BEGIN_SRC elisp
(use-package projectile
  :ensure t
  :config
  (setq projectile-dynamic-mode-line nil)
  (projectile-mode 1))
#+END_SRC

Other than that, the silver searcher is quite convenient as well. Ayo silver!

#+BEGIN_SRC elisp
(use-package ag
  :ensure t
  :config
  (setq ag-reuse-buffers t
        ag-reuse-window t))
#+END_SRC

* Completion

Now, completion is pretty important for lazy bastards like me. It comes in two flavors: =helm= and =company=.

** Helm

Helm is a big beast, and it will help me go through stuff like projects, IRC channels, files, commands, etc.

#+BEGIN_SRC elisp
(use-package helm
  :ensure t
  :config
  (setq projectile-completion-system 'helm)

  ;; Allow the search pattern to be on the header. Taken from this Reddit thread:
  ;; https://www.reddit.com/r/emacs/comments/3asbyn/new_and_very_useful_helm_feature_enter_search/
  (setq helm-echo-input-in-header-line t)

  (defun helm-hide-minibuffer-maybe ()
    "Hide the minibuffer if we are in a Helm session"

    (when (with-helm-buffer helm-echo-input-in-header-line)
      (let ((ov (make-overlay (point-min) (point-max) nil nil t)))
        (overlay-put ov 'window (selected-window))
        (overlay-put ov 'face (let ((bg-color (face-background 'default nil)))
                                `(:background ,bg-color :foreground ,bg-color)))
        (setq-local cursor-type nil))))

  (add-hook 'helm-minibuffer-set-up-hook 'helm-hide-minibuffer-maybe)
  (setq helm-split-window-inside-p t)

  ;; Preview files with tab
  (define-key helm-map (kbd "<tab>") 'helm-execute-persistent-action)

  ;; Show available options
  (define-key helm-map (kbd "C-a")  'helm-select-action)

  ;; Some vim-like bindings
  (define-key helm-map (kbd "C-j") 'helm-next-line)
  (define-key helm-map (kbd "C-k") 'helm-previous-line)

  ;; Use Helm for the M-x combo.
  (global-set-key (kbd "M-x") 'helm-M-x))
#+END_SRC

The combination of =helm= and the =ag= package is also pretty useful:

#+BEGIN_SRC elisp
(use-package helm-ag
  :ensure t
  :after helm)
#+END_SRC

Last but not least, the =helm-projectile= is the definitive combo for selecting projects, which will be available with the @@html:<kbd>M-p</kbd>@@ key binding:

#+BEGIN_SRC elisp
(use-package helm-projectile
  :ensure t
  :after helm
  :config
  (helm-projectile-on)

  ;; Define M-p as a way to quickly list all the available projects.
  (with-eval-after-load 'evil
    (define-key evil-normal-state-map (kbd "M-p")
      'helm-projectile-switch-project)))
#+END_SRC

I use @@html:<kbd>C-p</kbd>@@ as the binding for listing relevant files. This binding works either by using =helm-projectile= or the regular =helm-find= function. As a final touch, this binding also works for listing channels in ERC buffers.

#+BEGIN_SRC elisp
(defun mssola-erc-helm-buffer-list ()
  "Returns a list with the ERC buffers."
  (mapcar 'buffer-name (erc-buffer-list)))

(defconst mssola-helm-source-erc-channel-list
      '((name . "ERC Channels")
        (candidates . mssola-erc-helm-buffer-list)
        (action . switch-to-buffer)))

(defun mssola-erc-helm-switch-buffer ()
  "Use helm to select an active ERC buffer."

  (interactive)

  (helm :sources '(mssola-helm-source-erc-channel-list)
        :buffer "*helm-erc-channels*"))

(defun mssola-find-file ()
  "Call the proper Helm function for finding files."

  (interactive)

  (if (string= major-mode "erc-mode")
      (mssola-erc-helm-switch-buffer)
    (condition-case nil
        (helm-projectile-find-file)
      (error
       (helm-find-files nil)))))

(with-eval-after-load 'evil
  (define-key evil-normal-state-map (kbd "C-p") 'mssola-find-file))
#+END_SRC

Similarly, =helm-ag= has two functions for applying =ag= (depending on whether we are in a known project, or we are out in the open). I'm binding to @@html:<kbd>C-c C-s</kbd>@@ a function that calls to the proper function.

#+BEGIN_SRC elisp
(defun mssola-helm-ag ()
  "Call the right ag command for helm-ag."

  (interactive)

  (condition-case nil
      (helm-ag-project-root)
    (error (helm-ag))))

(global-set-key (kbd "C-c C-s") 'mssola-helm-ag)
#+END_SRC

** TODO Company

* Edit
** General

In this section I define some useful packages for editing. First of all, one of the coolest packages out there is =undo-tree=. It allows you to navigate through the undo history in a tree (because GNU Emacs is cool and keeps track of undo actions in a tree structure instead of in a stack). This package is included in recent versions of GNU Emacs.

#+BEGIN_SRC elisp
(with-eval-after-load 'undo-tree
  (global-undo-tree-mode 1)

  (setq undo-tree-visualizer-diff t
        undo-tree-visualizer-timestamps t
        undo-tree-visualizer-relative-timestamps t))
#+END_SRC

A recurring issue in speeches and presentations is that when showing something with your editor, you have to increase/decrease the fonts. I use the =default-text-scale= package for this. The bindings are @@html:<kbd>C-+</kbd>@@ and @@html:<kbd>C--</kbd>@@ which perform the expected thing.

#+BEGIN_SRC elisp
  (use-package default-text-scale
    :ensure t
    :config
    (global-set-key (kbd "C-+") 'default-text-scale-increase)
    (global-set-key (kbd "C--") 'default-text-scale-decrease))
#+END_SRC

Some languages use some delimiters a lot (e.g. lisp languages and parenthesis). For this reason I'm using the =rainbow-delimiters= package, which properly highlights each level in a different way (provided that your theme supports it).

#+BEGIN_SRC elisp
  (use-package rainbow-delimiters
    :ensure t)
#+END_SRC

Enable =electric-pair-mode=, which automatically closes pairs like brackets:

#+BEGIN_SRC elisp
(electric-pair-mode 1)
#+END_SRC

=YASnippet= allows people to define shortcuts for writing some common blocks. Moreover, it comes with a set of builtin snippets already.

#+BEGIN_SRC elisp
(use-package yasnippet
  :ensure t
  :init (yas-global-mode)
  :config
  (yas-global-mode 1))
#+END_SRC


=move-text= is a small package that allows you to move lines with a keybinding. This might be feasible with =evil-mode=, but still this might help when you want to move lines and keep the default registry empty:

#+BEGIN_SRC elisp
(use-package move-text
  :ensure t
  :bind
  (("M-k" . move-text-up)
   ("M-j" . move-text-down)))
#+END_SRC

Enable word wrap and disable =auto-fill-mode= when in =text-mode= (which includes modes such as =org-mode=). Even if simple, this involves doing some heavy lifting in =evil-mode= so commands act accordingly. With the elisp-fu shown below everything should run happily as it should.

#+BEGIN_SRC elisp
(setq-default word-wrap t)
(add-hook 'text-mode-hook (lambda ()
                            (visual-line-mode 1)
                            (auto-fill-mode -1)))

(defun mssola-end-of-line (&rest args)
  "Cycle through visual lines until we reach the real end of line.

This function is meant to be a replacement of the default `end-of-line' function
and the one from Evil mode.  It moves the cursor to the end of the visual line
according to ARGS.  If the cursor is already at the end of the visual line, then
it moves down to the next visual line and then it moves the cursor to the end of
the visual line.  If the cursor is already at the end of the real line, then it
does nothing.  Note that this behavior only applies when in `visual-line' mode.
If this is not the case, then this function is synonimous to `end-of-line'."

  (interactive)

  (let ((orig-point (point))
        (real-eol nil))

    (end-of-visual-line args)

    (when (and line-move-visual
               (= orig-point (point)))
      (save-excursion (progn
                        (let ((line-move-visual nil))
                          (end-of-line))
                        (setq real-eol (= orig-point (point)))))
      (when (not real-eol)
        (end-of-visual-line 2)))))

(with-eval-after-load 'evil
  ;; The advice around `evil-next-line' and `evil-previous-line' has been taken
  ;; from https://stackoverflow.com/a/32660401

  ;; Make evil-next-line (up arrow and k, consider visual-line-mode).
  (defun evil-next-line--check-visual-line-mode (orig-fun &rest args)
    (if line-move-visual
        (apply 'evil-next-visual-line args)
      (apply orig-fun args)))

  (advice-add 'evil-next-line :around 'evil-next-line--check-visual-line-mode)

  ;; Make evil-previous-line (down arrow and j, consider visual-line-mode).
  (defun evil-previous-line--check-visual-line-mode (orig-fun &rest args)
    (if line-move-visual
        (apply 'evil-previous-visual-line args)
      (apply orig-fun args)))

  (advice-add 'evil-previous-line :around 'evil-previous-line--check-visual-line-mode))
#+END_SRC

For whatever reason now I need this to type accents:

#+BEGIN_SRC elisp
(require 'iso-transl)
#+END_SRC

** Spell checking

Basic =flycheck= configuration:

#+BEGIN_SRC elisp
(use-package let-alist
  :ensure t)

(use-package flycheck
  :ensure t
  :config
  (add-hook 'after-init-hook 'global-flycheck-mode)

  ;; Only show the errors buffer if it isn't there and if I'm saving the
  ;; buffer.
  (setq flycheck-emacs-lisp-load-path 'inherit)
  (setq flycheck-check-syntax-automatically '(mode-enabled save))
  (setq flycheck-display-errors-function
    #'flycheck-display-error-messages-unless-error-list))
#+END_SRC

Enable spell checking generally for any text-related mode:

#+BEGIN_SRC elisp
(dolist (hook '(erc-mode-hook org-mode-hook text-mode-hook))
  (add-hook hook (lambda () (flyspell-mode 1))))
#+END_SRC

Also check the spelling of comments in programming languages:

#+BEGIN_SRC elisp
(dolist (mode '(emacs-lisp-mode-hook
                inferior-lisp-mode-hook
                python-mode-hook
                js-mode-hook
                go-mode-hook
                ruby-mode-hook
                rust-mode-hook
                php-mode-hook
                c-mode-common-hook))
  (add-hook mode
            '(lambda ()
               (flyspell-prog-mode))))
#+END_SRC

Let's use =<f8>= for checking words, and =M-<f8>= for moving into the next highlighted word:

#+BEGIN_SRC elisp
(global-set-key (kbd "<f8>") 'ispell-word)

(defun flyspell-check-next-highlighted-word ()
  "Custom function to spell check next highlighted word"
  (interactive)

  ;; If we are in org mode, unfold everything, since flyspell does not work
  ;; smoothly with folded stuff.
  (when (string= major-mode "org-mode")
    (outline-show-all))

  (flyspell-goto-next-error)
  (ispell-word))

(global-set-key (kbd "M-<f8>") 'flyspell-check-next-highlighted-word)
#+END_SRC

If possible, use [[https://hunspell.github.io/][hunspell]] instead of aspell. This program is used by LibreOffice, Firefox, etc. so it's pretty reliable and it supports rather complex languages such as Hungarian. The language being picked is the one from =LC_ALL= and similar environment variables. You can change that by setting =ispell-local-dictionary= and similar:

#+BEGIN_SRC elisp
(cond
 ((executable-find "hunspell")
  (setq ispell-program-name "hunspell")
  (setq ispell-really-hunspell t))

 ((executable-find "aspell")
  (setq ispell-program-name "aspell")))
#+END_SRC

Moreover, let's use [[https://github.com/languagetool-org/languagetool][languagetool]] for further checks:

#+BEGIN_SRC elisp
(use-package langtool
  :ensure t)

(let ((lt-path "/usr/share/languagetool"))
  (setq langtool-language-tool-jar (concat lt-path "/languagetool-commandline.jar")
        langtool-mother-tongue "ca"))

(when (fboundp 'langtool-check)
  (global-set-key (kbd "<f9>") 'langtool-check-buffer)
  (global-set-key (kbd "M-<f9>") 'langtool-correct-buffer))
#+END_SRC

Let flyspell be performant:

#+BEGIN_SRC elisp
(defvar flyspell-issue-message-flag nil)
#+END_SRC

** Abbreviations

An interesting GNU Emacs feature is the configurability of abbreviations. I only need abbrevs for some modes, and I'd like everything to run silently:

#+BEGIN_SRC elisp
(setq abbrev-file-name (concat user-emacs-directory "abbrevs.el")
      save-abbrevs 'silent)

(dolist (hook '(erc-mode-hook org-mode-hook text-mode-hook)) (add-hook hook #'abbrev-mode))
#+END_SRC

** Misc

Sometimes you begin typing a prefix, but then you forget the following chord. For this reason =which-key= was created. It will show the available commands for the current chord as a list (and beautified with =helm=).

#+BEGIN_SRC elisp
(use-package which-key
  :ensure t
  :config
  (which-key-mode))
#+END_SRC

For some modes it is important to count the number of words in the text. For this, we have =wc-mode=.

#+BEGIN_SRC elisp
  (use-package wc-mode
    :ensure t)
#+END_SRC

Editing files as root is a bit of a pain because usually the root user doesn't have the same configuration as the current one, and attempting to do so can be messy. So, instead of that, we could advice the =find-file= function so if the file is not writable by the current user, then GNU Emacs will ask for editing this same file as root:

#+BEGIN_SRC elisp
(defadvice find-file (after find-file-sudo activate)
  "Find file as root if necessary."
  (if (and buffer-file-name
           (not (file-writable-p buffer-file-name)))
    (if (yes-or-no-p "Do you want to edit this file as root?")
        (find-alternate-file (concat "/sudo:root@localhost:" buffer-file-name)))))
#+END_SRC

=bool-flip= is a very simple utility that toggles truthy/falsey values.

#+BEGIN_SRC elisp
(use-package bool-flip
  :ensure t
  :config
  (global-set-key (kbd "C-c b") 'bool-flip-do-flip))
#+END_SRC

* Dired

[[https://www.gnu.org/software/emacs/manual/html_node/emacs/Dired.html][Dired]] (Directory Editor) is a pretty interesting mode, since it allows you to treat the file system as something that can be edited as if it was just text. It's pretty powerful but I have to admit that my muscle memory brings me to the terminal every time, so I don't really use it. That being said, whenever I use it I want some tweaks to apply:

#+BEGIN_SRC elisp
(setq dired-dwim-target t
      dired-omit-mode nil
      dired-recursive-copies 'always
      dired-recursive-deletes 'always
      delete-old-versions t)
#+END_SRC

Also enable =dired-x= which brings some cool stuff like =dired-jump=:

#+BEGIN_SRC elisp
(require 'dired-x)
#+END_SRC

And now instruct dired mode how to attach files when using =mu4e=. This is pretty important because it's the only way I've found in which I can attach documents into =mu4e= buffers. This is taken from the [[https://www.djcbsoftware.nl/code/mu/mu4e/Dired.html#Dired][mu4e documentation]] and it's available by typing @@html:<kbd>C-c RET C-a</kbd>@@.

#+BEGIN_SRC elisp
  (require 'gnus-dired)

  ;; Make the `gnus-dired-mail-buffers' function also work on message-mode derived
  ;; modes, such as mu4e-compose-mode.
  (defun gnus-dired-mail-buffers ()
    "Return a list of active message buffers."

    (let (buffers)
      (save-current-buffer
        (dolist (buffer (buffer-list t))
          (set-buffer buffer)
          (when (and (derived-mode-p 'message-mode)
                  (null message-sent-message-via))
            (push (buffer-name buffer) buffers))))
      (nreverse buffers)))

  (setq gnus-dired-mail-mode 'mu4e-user-agent)
  (add-hook 'dired-mode-hook 'turn-on-gnus-dired-mode)
#+END_SRC

* Evil

Forgive me, [[https://stallman.org/saint.html][Father]], for I have sinned. I've been exposed to modal editing through Vim, and that has changed how I view editing for the foreseeable future. Because of this, I use Evil. The following blocks include some heavy-lifting so Evil and GNU Emacs work without hitting each other, and it also includes some Evil extensions.

First of all, let's define some variables that should be applied before we enter into =evil= itself. For example, we are going to get rid of GNU Emacs' @@html:<kbd>C-u</kbd>@@ binding because we are going to count a-la Vim. This means that @@html:<kbd>C-u</kbd>@@ can return to its Vim behavior: scroll up in normal mode, and delete to the indentation level in insert mode.

#+BEGIN_SRC elisp
(defvar evil-want-C-u-scroll t)
(defvar evil-want-C-u-delete t)
#+END_SRC

Second of all, @@html:<kbd>C-w</kbd>@@ will be the prefix for window management in normal mode, but for insert mode in Vim it meant killing a word. Let's keep that:

#+BEGIN_SRC elisp
(defvar evil-want-C-w-delete t)
#+END_SRC

Now that it has been set, we can tell =use-package= to install and configure =evil=. Let's take the following under consideration first:

1. Window navigation is prefixed with @@html:<kbd>C-w</kbd>@@ and then it uses the @@html:<kbd>C-j</kbd>@@, @@html:<kbd>C-k</kbd>@@, @@html:<kbd>C-l</kbd>@@ and @@html:<kbd>C-h</kbd>@@ bindings for moving around, and @@html:<kbd>C-w</kbd>@@ as a way of moving into other windows more generally. These are the defaults in Vim, but I used to override them with alternatives that had some conflicts (e.g. with the help command). All in all, let's stick with Vim's defaults here.
2. @@html:<kbd>C-a</kbd>@@ and @@html:<kbd>C-e</kbd>@@ are blessed as the bindings for moving the cursor to the beginning and to the end of the line respectively. This will be applied everywhere. The simple explanation for this is consistency: we will have the same binding regardless of the mode. Furthermore, these have the advantage of being the default GNU Emacs bindings for this movements, so all the default bindings of GNU Emacs aren't that shitty after all!
3. @@html:<kbd>C-2</kbd>@@ is the equivalent of executing @@html:<kbd>@ q</kbd>@@. This requires a bit of history. In my Vim times I recorded all my macros on the @@html:<kbd>q</kbd>@@ register out of simplicity: I've never had to store multiple macros for a single operation, and simply pressing that key twice got the job done in a really fast way. That being said, that was also done because then I executed the macro with @@html:<kbd>C-q</kbd>@@, but this is a key binding that I cherrish in GNU Emacs. Thus, I've moved this binding a bit up into @@html:<kbd>C-2</kbd>@@, which has the mnemonic of "where the @ symbol is".
4. I shamelessly use @@html:<kbd>C-s</kbd>@@ for saving the current buffer regardless of the current mode. In fact, from insert mode it's a way of saving the current buffer and getting back into normal mode. It's just easier and faster this way, no matter what Vim gurus might tell ya!

Thus, my configuration enforces what has been mentioned above, and it also sets the initial states for some modes:

#+BEGIN_SRC elisp
(use-package evil
  :ensure t
  :init
  ;; Needed by evil-collection
  (setq evil-want-integration t
        evil-want-keybinding nil)
  :config
  ;; Let's bring back some evil-window mappings into good ol' Vim defaults.
  (define-key evil-window-map (kbd "C-h") #'evil-window-left)
  (define-key evil-window-map (kbd "C-j") #'evil-window-down)
  (define-key evil-window-map (kbd "C-k") #'evil-window-up)
  (define-key evil-window-map (kbd "C-l") #'evil-window-right)
  (define-key evil-window-map (kbd "C-w") #'other-window)

  ;; Go back to Emacs' bindings on beginning/end of line.
  (eval-after-load "evil-maps"
    (dolist (map '(evil-motion-state-map
                   evil-insert-state-map
                   evil-emacs-state-map))
      (define-key (eval map) "\C-a" 'crux-move-beginning-of-line)
      (define-key (eval map) "\C-e" #'mssola-end-of-line)))

  ;; I store macros on the <q> register for convenience, so I used to use the
  ;; <C-q> combo to execute this macro in Vim. In Emacs though, this combo is
  ;; reserved to a rather useful function, and I'd like to keep it that way. So,
  ;; now the mapping is set to <C-2> (mnemonic: where the @ symbol is). Moreover,
  ;; it's applied as many times as specified by the numeric prefix argument.
  (define-key evil-normal-state-map (kbd "C-2")
    (lambda (n)
      (interactive "p")
      (evil-execute-macro n "@q")))

  ;; C-s: switch to normal mode and save the buffer. I know :)
  (define-key evil-normal-state-map (kbd "C-s") 'save-buffer)
  (define-key evil-insert-state-map (kbd "C-s")
    (lambda () (interactive) (save-buffer) (evil-force-normal-state)))

  (evil-mode 1)

  ;; Use the proper initial evil state for the following modes.
  (evil-set-initial-state 'help-mode 'normal)
  (evil-set-initial-state 'debugger-mode 'normal)
  (evil-set-initial-state 'describe-mode 'normal)
  (evil-set-initial-state 'Buffer-menu-mode 'normal)
#+END_SRC

If Evil was properly loaded, then make sure that the following Evil-related packages are installed and configured as well.

For example, instead of hacking our own escape sequence, let's use =evil-escape= for that. This has the advantage of maintainability: before I had to make sure that my escape sequence was being applied correctly for all modes and that no mode replaced my sequence afterwards. In particular, we will set @@html:<kbd>C-z</kbd>@@ as an escape key. This is because in Vim there was @@html:<kbd>C-c</kbd>@@ for this as well (which was convenient because you always have the pinky on the @@html:<kbd>Caps Lock</kbd>@@ key anyway, since that is remapped as a @@html:<kbd>Control</kbd>@@ key). That being said, that key binding is super duper important in GNU Emacs, and you really don't want to mess around with it. Now, if you remember correctly, we have disabled this key binding before (because the bound function to it is simply absurd, and more so on =i3= and similar WM), so we can use this binding for this task. Moreover, the @@html:<kbd>C-g</kbd>@@ key binding has also been setup as an escape sequence in modes were it makes sense.

#+BEGIN_SRC elisp
(use-package evil-escape
  :ensure t
  :after evil
  :init
  (setq evil-escape-excluded-states '(normal visual multiedit emacs motion))
  (evil-define-key* '(insert replace visual operator) 'global "\C-g" #'evil-escape)
  :config
  ;; no `evil-escape' in minibuffer
  (add-hook 'evil-escape-inhibit-functions #'minibufferp)

  (evil-escape-mode +1)

  (define-key key-translation-map (kbd "C-z") [escape])
  (define-key evil-operator-state-map (kbd "C-z") 'evil-escape))
#+END_SRC

A handy Vim plugin that has made it into Evil is =evil-surround=, which defines a new text object for surrounding characters (e.g. change a string from having double quotes with single quotes in a single command).

#+BEGIN_SRC elisp
  (use-package evil-surround
    :ensure t
    :config
    (global-evil-surround-mode 1))
#+END_SRC

Next is another Vim plugin that has been ported to Evil: =evil-commentary=. This package defines a new motion for comments, which is bound to @@html:<kbd>gc</kbd>@@. So, for example, @@html:<kbd>gcc</kbd>@@ will comment the current line, regardless of the programming language.

#+BEGIN_SRC elisp
  (use-package evil-commentary
    :ensure t
    :config
    (evil-commentary-mode t))
#+END_SRC

Add Vim-like keybindings to as many modes as possible. Note that this list is not exhaustive, since some of these modes are better off with specific packages (e.g. =evil-magit=), and in some cases my bindings feel more intuitive to me (e.g. =woman=):

#+BEGIN_SRC elisp
(use-package evil-collection
  :ensure t
  :after evil
  :config
  ;; Doing this one by one so it's not too bloated.
  (evil-collection-init 'ag)
  (evil-collection-init 'calendar)
  (evil-collection-init 'dired)
  (evil-collection-init 'help)
  (evil-collection-init 'mu4e))
#+END_SRC

Last but not least, =evil-numbers= brings a couple of bindings available on Vim into Evil: @@html:<kbd>C-c +</kbd>@@ for increasing a number, and @@html:<kbd>C-c -</kbd>@@ for decreasing it.

#+BEGIN_SRC elisp
  (use-package evil-numbers
    :ensure t
    :config
    (define-key evil-normal-state-map (kbd "C-c +") 'evil-numbers/inc-at-pt)
    (define-key evil-normal-state-map (kbd "C-c -") 'evil-numbers/dec-at-pt)))
#+END_SRC

* Git

[[https://magit.vc/][Magit]] is a git porcelain inside GNU Emacs. I've grown really fond of it, since it makes some git operations dead easier and faster to perform (e.g. rebasing). Moreover, some other commands are way prettier and more useful with Magit (e.g. the =log= command, staging, showing diffs, etc). So right now my situation is that I use Magit most of the time, and bare git when I want to do something fishy. Some notes on this setup:

1. I set @@html:<kbd>C-x g</kbd>@@ as a binding for =magit-status= and @@html:<kbd>C-c l</kbd>@@ as a binding for =magit-log-buffer-file=. These are the most useful =magit= entries.
2. I install =evil-magit=, which could've been replaced by =evil-collection= but it really falls short. Thus, I keep this package.

#+BEGIN_SRC elisp
(use-package magit
  :ensure t
  :config
  (global-set-key (kbd "C-x g") 'magit-status)
  (global-set-key (kbd "C-c l") 'magit-log-buffer-file)

  (with-eval-after-load 'evil
    (use-package evil-magit
      :ensure t)))

#+END_SRC

=git-timemachine= is a package that goes hand-in-hand with Magit, and it provides a very easy way to go through the history of a file (while providing ways of jumping into Magit). You can enter it with @@html:<kbd>C-x t m</kbd>@@ (hopefully the mnemonic is self-evident).

#+BEGIN_SRC elisp
(use-package git-timemachine
  :ensure t
  :bind (("C-x t m" . git-timemachine-toggle)))
#+END_SRC

[[https://github.com/magit/git-modes][git-modes]] provides minor modes for various git files, which are listed below:

#+BEGIN_SRC elisp
(use-package gitattributes-mode
  :ensure t)

(use-package gitconfig-mode
  :ensure t)

(use-package gitignore-mode
  :ensure t)
#+END_SRC

* Email

I use [[http://www.djcbsoftware.nl/code/mu/][mu]] and [[http://www.djcbsoftware.nl/code/mu/mu4e.html][mu4e]] to manage my email. =mu= is the indexer itself, and =mu4e= is the interface for GNU Emacs. The configuration for this has been taken mainly from the documentation, plus some cool remarks on Reddit.

I'm using [[https://build.opensuse.org/package/show/server:mail/maildir-utils][this package from OBS]] to install =mu= and =mu4e=, which installs things globally. Moreover, because of this, I expect =mu= to be on its latest and shiniest release always.

=mu= only takes care of the indexing part, but the retrieval of emails is handled via =mbsync= which I take from [[https://build.opensuse.org/package/show/server:mail/isync][obs://server:mail]] and that is configured with [[https://github.com/mssola/dotfiles/blob/master/.mbsyncrc][this file]]. The sending is done through the =smtpmail-send-it= function, which is built in GNU Emacs. This part is not optimal since it blocks the GNU Emacs instance whenever we are sending en email. I plan to look into =msmtp= as soon as possible.

#+BEGIN_SRC elisp
(unless (file-directory-p "/usr/share/emacs/site-lisp/mu4e")
  (message "Skipping mu4e because it's not installed."))

(when (file-directory-p "/usr/share/emacs/site-lisp/mu4e")
  (require 'mu4e)

  (when (version< mu4e-mu-version "1.4.0")
    (warn "You need at least mu 1.4.0 to get things working..."))

  (when (featurep 'mu4e)
#+END_SRC

Set =mu4e= as the default user agent. This will be picked up by =compose-mail=.

#+BEGIN_SRC elisp
(setq mail-user-agent 'mu4e-user-agent)
#+END_SRC

Now we can set some SMTP settings which are independent of each context. That being said, I plan on investigating the usage of tools such as =msmtp=, so maybe these variables will fade away once I move into that kind of setup.

#+BEGIN_SRC elisp
  (setq message-send-mail-function 'smtpmail-send-it
        starttls-use-gnutls t)
#+END_SRC

After that, I am defining some functions that will be used in various parts of the configuration. Some observations:

- =mssola-smtp= is expected to be called only by each context. This will set the different variables properly for each context. This is rather ugly, since you could use the =:var= keyword on each context, but on the other hand this might be removed once we move into =msmtp= or something of that sorts.
- =mu4e-message-maildir-matches= and =suse-refile-folder= are just helper functions for the different contexts.

#+BEGIN_SRC elisp
(defun mssola-smtp (server port)
  "Set SMTP variables depending on the given SERVER and PORT."

  (require 'smtpmail)

  (setq smtpmail-default-smtp-server server
        smtpmail-smtp-server server
        message-send-mail-function 'smtpmail-send-it
        smtpmail-smtp-service port))

;; https://www.reddit.com/r/emacs/comments/47t9ec/share_your_mu4econtext_configs/d0fsih6
(defun mu4e-message-maildir-matches (msg rx)
  "Returns true if the maildir of MSG matches the given regexp RX."

  (when rx
    (if (listp rx)
        ;; if rx is a list, try each one for a match
        (or (mu4e-message-maildir-matches msg (car rx))
            (mu4e-message-maildir-matches msg (cdr rx)))
      ;; not a list, check rx
      (string-match rx (mu4e-message-field msg :maildir)))))

(defun suse-refile-folder (key)
  "Returns the refile folder for the given SUSE account in the KEY arg"

  (if (string= key "susecom")
      (setq archives-dir "/Arxiu/")
    (setq archives-dir "/Archives/"))
  (concat "/" key archives-dir
          (format-time-string "%Y" (current-time))))
#+END_SRC

Depending on the context, it's better a signature or another:

#+BEGIN_SRC elisp
(defun mssola-mu4e-signature (key)
  "Returns a string containing the mail signature for the given KEY."

  (if (string= key "ajuntament")
      (concat
       "Miquel Sabaté Solà,\n"
       "Regidor de Joventut, Participació ciutadana i Transparència\n"
       "\n"
       "Ajuntament de Capellades\n"
       "Carrer de Ramon Godó, 9, 08786 - Capellades\n"
       "Tel. 93 801 10 01 – mòbil 677 12 72 07\n"
       "sabatesm@capellades.cat\n")
    (concat
     "Miquel Sabaté Solà,\n"
     "PGP: 4096R / 1BA5 3C7A C93D CA2A CFDF DA97 96BE 8C6F D89D 6565\n")))
#+END_SRC

Now it's time to define the different contexts that I have. Defining contexts this way is relatively new (since mu 0.9.16). The different contexts are quite self-explanatory (and quite boring to look at).

#+BEGIN_SRC elisp
(setq mu4e-contexts
      `(
        ;; GMail
        ,(make-mu4e-context
          :name "gmail"
          :enter-func (lambda ()
                        (mu4e-message "Switching to gmail.com")
                        (setq mu4e-compose-signature (mssola-mu4e-signature "gmail"))
                        (setq mu4e-sent-messages-behavior 'delete)
                        (mssola-smtp "smtp.gmail.com" 587))
          :match-func (lambda (msg)
                        (when msg
                          (mu4e-message-maildir-matches msg "^/gmail")))
          :vars '(
                  (user-mail-address     . "mikisabate@gmail.com")
                  (mu4e-reply-to-address . "mikisabate@gmail.com")
                  (mu4e-drafts-folder    . "/gmail/Drafts")
                  (mu4e-sent-folder      . "/gmail/Sent")
                  (mu4e-refile-folder    . "/gmail/All")
                  (mu4e-trash-folder     . "/gmail/Trash")))

        ;; City hall
        ,(make-mu4e-context
          :name "ajuntament"
          :enter-func (lambda ()
                        (mu4e-message "Switching to mail.diba.cat")
                        (setq mu4e-compose-signature (mssola-mu4e-signature "ajuntament"))
                        (setq mu4e-sent-messages-behavior 'sent)
                        (mssola-smtp "mail.diba.cat" 587)
                        (setq smtpmail-local-domain "capellades.cat"))
          :match-func (lambda (msg)
                        (when msg
                          (mu4e-message-maildir-matches msg "^/ajuntament")))
          :vars '(
                  (user-mail-address     . "sabatesm@capellades.cat")
                  (mu4e-reply-to-address . "sabatesm@capellades.cat")
                  (mu4e-drafts-folder    . "/ajuntament/Esborranys")
                  (mu4e-sent-folder      . "/ajuntament/Elements enviats")
                  (mu4e-refile-folder    . "/ajuntament/Arxiu")
                  (mu4e-trash-folder     . "/ajuntament/Elements suprimits")))

        ;; suse.com
        ,(make-mu4e-context
          :name "comsuse"
          :enter-func (lambda ()
                        (mu4e-message "Switching to suse.com")
                        (setq mu4e-compose-signature (mssola-mu4e-signature "comsuse"))
                        (setq mu4e-sent-messages-behavior 'sent)
                        (mssola-smtp "smtp.office365.com" 587))
          :match-func (lambda (msg)
                        (when msg
                          (mu4e-message-maildir-matches msg "^/susecom")))
          :vars `(
                  (user-mail-address     . "msabate@suse.com")
                  (mu4e-reply-to-address . "msabate@suse.com")
                  (mu4e-drafts-folder    . "/susecom/Esborranys")
                  (mu4e-sent-folder      . "/susecom/Elements enviats")
                  (mu4e-refile-folder    . ,(suse-refile-folder "susecom"))
                  (mu4e-trash-folder     . "/susecom/Elements suprimits")))

        ;; suse.de
        ,(make-mu4e-context
          :name "desuse"
          :enter-func (lambda ()
                        (mu4e-message "Switching to suse.de")
                        (setq mu4e-compose-signature (mssola-mu4e-signature "desuse"))
                        (setq mu4e-sent-messages-behavior 'sent)
                        (mssola-smtp "imap.suse.de" 587))
          :match-func (lambda (msg)
                        (when msg
                          (mu4e-message-maildir-matches msg "^/susede")))
          :vars `(
                  (user-mail-address     . "msabate@suse.de")
                  (mu4e-reply-to-address . "msabate@suse.de")
                  (mu4e-drafts-folder    . "/susede/Drafts")
                  (mu4e-sent-folder      . "/susede/Sent")
                  (mu4e-refile-folder    . ,(suse-refile-folder "susede"))
                  (mu4e-trash-folder     . "/susede/Trash")))))
#+END_SRC

If mu4e cannot figure things out, ask me:

#+BEGIN_SRC elisp
  (setq mu4e-context-policy 'ask)
  (setq mu4e-compose-context-policy 'ask)
#+END_SRC

You can setup bookmarks, which are a way to perform a search with a single key chord. I define pretty standard ones:

#+BEGIN_SRC elisp
(setq mu4e-bookmarks
      '(("maildir:/gmail/inbox OR maildir:/susecom/inbox OR maildir:/susede/inbox OR maildir:/ajuntament/inbox" "Inbox Folders" ?n)
        ("maildir:/gmail/Sent OR maildir:/susecom/Elements\\ enviats OR maildir:/susede/Sent OR maildir:/ajuntament/Elements\\ enviats" "Sent Folders" ?s)
        ("flag:unread AND NOT flag:trashed" "Unread messages" ?u)
        ("date:today..now" "Today's messages" ?t)))
#+END_SRC

Sign outgoing emails always. This used to be pretty straight forward, but since GNU Emacs 27.x we have to set some variables to make the sender happier.

#+BEGIN_SRC elisp
;; For some reason, as of GNU Emacs 27.x, I need to define the default openpgp
;; signer so it can automatically pick my only key I have for signing.
(when EMACS-27-OR-LATER
  (setq mml-secure-openpgp-signers '("0x96BE8C6FD89D6565")
        mml-secure-openpgp-sign-with-sender t))

(add-hook 'message-send-hook 'mml-secure-message-sign-pgpmime)
#+END_SRC

To avoid UID clashes we have to set this variable. See [[http://pragmaticemacs.com/emacs/fixing-duplicate-uid-errors-when-using-mbsync-and-mu4e/][this]].

#+BEGIN_SRC elisp
  (setq mu4e-change-filenames-when-moving t)
#+END_SRC

Miscellaneous settings, nothing too interesting (e.g. format flowed, fetcher command, attachment directory, etc).

#+BEGIN_SRC elisp
(setq mu4e-html2text-command "w3m -T text/html"
      mu4e-attachment-dir  (or (getenv "XDG_DOWNLOAD_DIRECTORY") (getenv "HOME"))
      mu4e-headers-date-format "%Y-%m-%d %H:%M"
      message-citation-line-format "%N @ %Y-%m-%d %H:%M %Z:\n"
      message-citation-line-function 'message-insert-formatted-citation-line
      message-kill-buffer-on-exit t
      mu4e-get-mail-command "mbsync -aqV"
      mu4e-update-interval 600
      mu4e-compose-dont-reply-to-self t
      mu4e-compose-format-flowed t
      mu4e-view-show-addresses t
      mu4e-headers-skip-duplicates t
      mu4e-headers-include-related t
      mu4e-headers-auto-update t)
#+END_SRC

The headers to show in the headers list a pair of a field and its width, with `nil' meaning 'unlimited' (better only use that for the last field). These are the defaults:

#+BEGIN_SRC elisp
  (setq mu4e-headers-fields
        '( (:date          .  18)
           (:mailing-list  .  15)
           (:from-or-to    .  20)
           (:subject       .  nil)))
#+END_SRC

Add as a header action to toggle gnus mode for the view mode. I'm doing this because this is way better to visualize attached .eml emails.

#+BEGIN_SRC elisp
(defun mssola-toggle-gnus-mode (_msg)
  "Toggle gnus on view mode from now on."
  (if mu4e-view-use-gnus
      (setq mu4e-view-use-gnus nil)
    (setq mu4e-view-use-gnus t)))

(add-to-list 'mu4e-headers-actions
   '("gnus mode toggle" . mssola-toggle-gnus-mode) t)
#+END_SRC

Show images:

#+BEGIN_SRC elisp
  (setq mu4e-view-show-images t
        mu4e-view-image-max-width 800)

  ;; Use imagemagick, if available
  (when (fboundp 'imagemagick-register-types)
    (imagemagick-register-types))
#+END_SRC

Correct some key bindings that are screwed up by =evil-mode=:

#+BEGIN_SRC elisp
(evil-define-key 'normal mu4e-view-mode-map
  ";" 'mu4e-context-switch
  "e" 'mu4e-view-save-attachment
  "F" 'mu4e-compose-forward)
#+END_SRC

As of 0.9.18 and GNU Emacs 25, the =mu4e-action-with-xwidget= can be used to render an HTML message with Webkit.

#+BEGIN_SRC elisp
(when EMACS-25-OR-LATER
  (add-to-list 'mu4e-view-actions '("webkit" . mu4e-action-view-with-xwidget)))
#+END_SRC

Look for =mu4e-msg2pdf= in the exec path. The reason for this is that the OBS package installs mu's =toys= into the exec path, but =mu4e= doesn't really count on it.

#+BEGIN_SRC elisp
  (let ((exec (locate-file "msg2pdf" exec-path exec-suffixes)))
    (if exec
        (setq mu4e-msg2pdf exec)))
#+END_SRC

Adding hooks for composing and viewing messages. These include stuff like enabling =visual-line-mode=, enabling =epa-mail-mode= so it's easier to encrypt/decrypt emails, determining which evil state to enter in, etc.

#+BEGIN_SRC elisp
  (defun mssola-compose-mode ()
    "My settings for message composition."

    ;; If we are composing an email from scratch, it's more convenient to be in
    ;; insert mode. Otherwise start with normal mode.
    (with-eval-after-load 'evil
      (if mu4e-compose-parent-message
          (evil-set-initial-state 'mu4e-compose-mode 'normal)
        (evil-set-initial-state 'mu4e-compose-mode 'insert)))

    ;; Guess hard newlines
    (use-hard-newlines t 'guess)

    ;; So it's easy to encrypt/decrypt emails.
    (epa-mail-mode))

  (add-hook 'mu4e-compose-mode-hook 'mssola-compose-mode)

  ;; I want to read messages in the format that the sender used. I'm also
  ;; enabling epa-mail-mode, so it's easy to decrypt received emails.
  (add-hook 'mu4e-view-mode-hook
            (lambda ()
              (epa-mail-mode)
              (visual-line-mode 1)))
#+END_SRC

=mu4e-alert= is needed by =doom-modeline= in order to inform incoming emails into the modeline. So let's install it now:

#+BEGIN_SRC elisp
(use-package mu4e-alert
  :ensure t
  :config
  (add-hook 'after-init-hook #'mu4e-alert-enable-mode-line-display)
  (setq mu4e-alert-interesting-mail-query
        (concat
         "(maildir:/gmail/inbox OR maildir:/susecom/inbox OR maildir:/susede/inbox OR maildir:/ajuntament/inbox) "
         "AND flag:unread AND NOT flag:trashed"))
  (setq mu4e-alert-email-notification-types '(count)))
#+END_SRC

And finally we define @@html:<kbd>C-c m</kbd>@@ as the entrypoint to =mu4e=:

#+BEGIN_SRC elisp
;; The trailing parenthesis closes the "(when (featurep 'mu4e)" statement from
;; the very beginning ;-)
(global-set-key (kbd "C-c m") 'mu4e)))
#+END_SRC

* org

[[https://orgmode.org/][org-mode]] is one of the most well-known "killing features" of GNU Emacs, but I have to admit that I don't use it to its full potential. Instead, I've organized myself in my own dirty way: with org files, but out from the whole agenda/capture workflow. That's why you will see that my current configuration is more about general settings on how to write individual org files, and how to export them.

** General settings

Let's set some basic org variables. That is, where my org files reside, how tabs should act and no indentation (I don't use those fancy bullets that some people install either, I find them tedious and a waste of blank space). On another note, I have my org directory shared with my [[https://nextcloud.com/][Nextcloud]] instance, so all my org files are available everywhere.

#+BEGIN_SRC elisp
(setq org-src-tab-acts-natively t
      org-confirm-babel-evaluate nil
      org-agenda-files '("~/org/")
      org-edit-src-content-indentation 0)

(setq org-todo-keywords
      '((sequence "TODO(t)"  "|"  "DONE(d!)")
        (sequence "IDEA(i)"  "WORKING(w)"  "|"  "USED(u@/!)"  "DISCARDED(x@/!)")))

(setq org-todo-keyword-faces
      '(("TODO"      . org-todo)
        ("IDEA"      . font-lock-constant-face)
        ("WORKING"   . font-lock-constant-face)
        ("DONE"      . org-done)
        ("USED"      . org-done)
        ("DISCARDED" . org-done)))
#+END_SRC

I believe I don't use =org-log=, but when I tried it I liked the following settings:

#+BEGIN_SRC elisp
(setq org-log-done t
      org-log-redeadline (quote time)
      org-log-reschedule (quote time))
#+END_SRC

** Publishing

Publishing is for me one of the most important features of =org-mode= and I abuse it a *lot*. For instance, my =init.org= file needs to be exported into HTML if I want it [[http://jo.mssola.com/static/init.html][online]]. That is done in combination with =htmlize=, which allows org to export to HTML in a better way (e.g. allowing code blocks to be converted into HTML as well, so we can properly colorize it).

#+BEGIN_SRC elisp
(use-package htmlize
  :ensure t
  :after org)
#+END_SRC

With that already established, we can tweak some relevant variables so HTML is exported properly with all the full potential of =htmlize=:

#+BEGIN_SRC elisp
(setq org-src-fontify-natively t
      org-html-include-timestamps nil
      org-html-toplevel-hlevel 2
      org-html-htmlize-output-type 'css
      org-export-with-section-numbers nil
      org-export-with-sub-superscripts nil
      org-export-htmlize-output-type 'css)
#+END_SRC

Another important format to export to is ODT. In order to do so, I instruct =org-mode= to follow the given template:

#+BEGIN_SRC elisp
(setq org-odt-styles-file
      (concat (or (getenv "XDG_DOCUMENTS_DIRECTORY") (getenv "HOME"))
              "/Templates/mssola.ott"))
#+END_SRC

And finally, another crucial format is PDF, which uses LaTeX underneath. Therefore, it's a good idea to sort out LaTeX in order to get PDFs right:

#+BEGIN_SRC elisp
(require 'ox-latex)

(unless (boundp 'org-latex-classes)
  (setq org-latex-classes nil))

(add-to-list 'org-latex-classes
             '("article"
               "\\documentclass{article}"
               ("\\section{%s}" . "\\section*{%s}")
               ("\\subsection{%s}" . "\\subsection*{%s}")
               ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
               ("\\paragraph{%s}" . "\\paragraph*{%s}")
               ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
#+END_SRC

After all that, we can have other esoteric exporters, like the one that exports into man pages which is funny enough:

#+BEGIN_SRC elisp
(require 'ox-man)
#+END_SRC

Not using the following function that much, but I've had a couple of instances where I wanted to toggle =org-publish-current-file= on save:

#+BEGIN_SRC elisp
(defun toggle-org-publish-current-file-on-save ()
  (interactive)
  (if (memq 'org-publish-current-file after-save-hook)
      (progn
        (remove-hook 'after-save-hook 'org-publish-current-file t)
        (message "Disabled org-publish-current-file for current buffer..."))
    (add-hook 'after-save-hook 'org-publish-current-file nil t)
    (message "Enabled org-publish-current-file for current buffer...")))
#+END_SRC

Last but not least, hide the "Footnotes: " title on footnotes:

#+BEGIN_SRC elisp
(setq org-html-footnotes-section "<div id=\"footnotes\">
<!-- Hack: %s -->
<div id=\"text-footnotes\">
%s
</div>
</div>")
#+END_SRC

** Profiles

I organize myself in what I call "profiles". That is a really bare-bones and hacky way to mock =org-agenda=, but I found it quite useful. As you will see, I have an org file that takes into account the whole week, and another that organizes the year itself. The week file is called a "minimal" profile, and the other is the "monthly" one. Then, you can pick your own profile or choose the default one. The default one is taken with the @@html:<kbd>C-c C-o</kbd>@@ binding, and you can choose with the @@html:<kbd>C-c M-o</kbd>@@ binding. It's nothing too fancy, but I like it.

#+BEGIN_SRC elisp
;; Variables

(defvar mssola-org-profiles
  '(("minimal" . mssola-org-minimal)
    ("monthly" . mssola-org-monthly))
  "Defined profiles for organization matters.")

(defvar mssola-org-default-profile "minimal"
  "The default profile for mssola-org.")

;; Profiles

(defun mssola-org-minimal ()
  "Load a minimal set of files."
  (find-file (concat (file-name-as-directory org-directory) "setmana.org")))

(defun mssola-org-monthly ()
  "Load a set of files useful for monthly planning."
  (find-file (concat (file-name-as-directory org-directory) "setmana.org"))
  (split-window-right)
  (windmove-right)
  (find-file (concat (file-name-as-directory org-directory) "any.org"))
  (windmove-left))

;; Functions

(defun mssola-org (&optional profile)
  "Setup a frame for organizational matters.
PROFILE is the profile to be picked when given.  If it's not given, then the
user will be prompted to provide it."
  (interactive)

  (delete-other-windows)
  (unless profile
    (setq profile (completing-read "Give me the profile: "
                                   (mapcar 'car mssola-org-profiles) nil t)))
  (funcall (cdr (assoc profile mssola-org-profiles))))

(defun mssola-org-default ()
  "Setup a frame for organizational matters given a default profile has been set."
  (interactive)

  (mssola-org mssola-org-default-profile))

(define-key global-map (kbd "C-c C-o") #'mssola-org-default)
(define-key global-map (kbd "C-c M-o") #'mssola-org)
#+END_SRC

** Other

As you will notice, this document is full of <kbd> HTML tags, which if you look into the raw document you will see that it's a tag which is pretty cumbersome to insert. I'm not mad, I have the following function to do the heavy lifting (which has been taken by this [[http://emacs.stackexchange.com/questions/2206/i-want-to-have-the-kbd-tags-for-my-blog-written-in-org-mode][StackExchange answer]]). This is available in =org-mode= with the key binding @@html:<kbd>C-c k</kbd>@@.

#+BEGIN_SRC elisp
(defun endless/insert-key (key)
  "Ask for a key then insert its description.
Will work on both org-mode and any mode that accepts plain html."
  (interactive "kType key sequence: ")
  (let* ((is-org-mode (derived-mode-p 'org-mode))
         (tag (if is-org-mode
                  "@@html:<kbd>%s</kbd>@@"
                "<kbd>%s</kbd>")))
    (if (null (equal key "\r"))
        (insert
         (format tag (help-key-description key nil)))
      (insert (format tag ""))
      (forward-char (if is-org-mode -8 -6)))))

(define-key org-mode-map "\C-ck" #'endless/insert-key)
#+END_SRC

** TODO shortcut for making an org link, and transforming a link into a proper org link
** TODO make it work with evil
** TODO Proper keybindings for quick access.

* writer-mode

There is this handy minor mode I've built which is [[https://github.com/mssola/writer-mode][writer-mode]]. This is under development, so I load it from my own local development path:

#+BEGIN_SRC elisp
(let ((writer-source (concat (getenv "HOME") "/src/github.com/mssola/writer-mode")))
  (when (file-directory-p writer-source)
    ;; Call `make build', which will, in turn, byte-compile all the relevant files.
    (let ((default-directory writer-source))
      (shell-command "make build"))

    ;; Then load the byte-compiled files.
    (let ((list (directory-files writer-source t ".elc$"))
          (load-prefer-newer t))
      (while list
        (load-file (car list))
        (setq list (cdr list))))

    ;; Declare that =writer-mode= has been loaded.
    (setq writer-mode-loaded t)))
#+END_SRC

After that, I can configure it further. For example, I want @@html:<kbd>f1</kbd>@@ and @@html:<kbd>f2</kbd>@@ to export my current project into PDF and ODT respectively:

#+BEGIN_SRC elisp
(when (boundp 'writer-mode-loaded)
  (define-key org-mode-map (kbd "<f1>") 'writer-org-export-to-pdf)
  (define-key org-mode-map (kbd "<f2>") 'writer-org-export-to-odt))
#+END_SRC

* IRC

I'm using [[https://www.gnu.org/software/emacs/manual/html_mono/erc.html][ERC]] for IRC, even though it's been quite a lot since we have used IRC at work (now we are using other chat alternatives). Anyhow, it's good to still have it here.

#+BEGIN_SRC elisp
(use-package erc
  :config
#+END_SRC

First of all, let's add some basic modules:

#+BEGIN_SRC elisp
  (dolist (mod '(autojoin track truncate))
    (add-to-list 'erc-modules mod))
#+END_SRC

Now we can set all your typical =erc= variables. There is nothing too interesting here.

#+BEGIN_SRC elisp
(setq erc-hide-list '("PART")
      erc-prompt (lambda () (concat (buffer-name) ">"))
      erc-track-exclude-types '("JOIN" "NICK" "PART" "QUIT" "MODE")
      erc-server-coding-system '(utf-8 . utf-8)
      erc-kill-buffer-on-part t
      erc-kill-queries-on-quit t
      erc-kill-server-buffer-on-quit t
      erc-fill-column 100
      erc-fill-prefix ""
      erc-timestamp-format "[%H:%M] "
      erc-insert-timestamp-function 'erc-insert-timestamp-left
      erc-insert-away-timestamp-function 'erc-insert-timestamp-left
      erc-hide-timestamps nil
      erc-whowas-on-nosuchnick t
      erc-public-away-p nil
      erc-echo-notice-always-hook '(erc-echo-notice-in-minibuffer)
      erc-auto-set-away nil
      erc-autoaway-message "%i seconds out..."
      erc-away-nickname "msabate"
      erc-enable-logging t
      erc-query-on-unjoined-chan-privmsg t
      erc-prompt-for-password nil)
#+END_SRC

Let's log messages whenever I receive/send them. The other option is to only do that on =/quit= or =/part=, but it's better to be safe than sorry.

#+BEGIN_SRC elisp
  (require 'erc-log)
  (erc-log-enable)

  (setq erc-log-channels-directory (concat user-emacs-directory "erc")
        erc-save-buffer-on-part nil
        erc-save-queries-on-quit nil
        erc-log-write-after-send t
        erc-log-write-after-insert t)
#+END_SRC

Servers and channels to auto-join:

#+BEGIN_SRC elisp
  (setq erc-autojoin-channels-alist
        '(("irc.freenode.net" "#gnu" "#emacs")
          ("irc.nue.suse.com" "#suse" "#docker")))
#+END_SRC

Use the =erc-hl-nicks= package, so highlight support for nicknames is better.

#+BEGIN_SRC elisp
(use-package erc-hl-nicks
  :ensure t
  :init
  (with-eval-after-load 'erc
    (add-to-list 'erc-modules 'hl-nicks)))
#+END_SRC

I want to have a desktop notification whenever someone mentions my name. For this, I'm using the =erc-notifications= package which is built in =erc= since GNU Emacs 24.3.

#+BEGIN_SRC elisp
(with-eval-after-load 'erc
  (setq erc-notifications-icon
        (concat
         "/usr/share/emacs/"
         (format "%s.%s" emacs-major-version emacs-minor-version)
         "/etc/images/icons/hicolor/24x24/apps/emacs.png"))
  (add-to-list 'erc-modules 'notifications))
#+END_SRC

At this point, we can safely update all the loaded ERC modules.

#+BEGIN_SRC elisp
  (add-hook 'erc-connect-pre-hook
            (lambda (_x) (erc-update-modules)))
#+END_SRC

Start some modules which won't do it by default. Moreover, according to the [[https://www.emacswiki.org/emacs/ErcFilling][wiki]] =auto-fill-mode= should be disabled if I'm using =erc-fill-mode=.

#+BEGIN_SRC elisp
  (add-hook 'erc-mode-hook
            '(lambda ()
               (erc-track-mode t)
               (auto-fill-mode -1)
               (erc-log-mode 1)
               (erc-autojoin-mode 1)))
#+END_SRC

And now define a function to connect to both IRC servers, which is bound to @@html:<kbd>C-c i</kbd>@@.

#+BEGIN_SRC elisp
  (defun mssola-erc ()
    "Join pre-specified servers and channels."

    (interactive)

    (erc :server "irc.freenode.net" :port 6667 :nick "mssola")
    (erc-tls :server "irc.nue.suse.com" :port 6697 :nick "mssola"))

  (global-set-key (kbd "C-c i") 'mssola-erc))
#+END_SRC

* Languages
** General

First of all, define a function that identifies some warning keywords (e.g. TODO). This function can then be applied to the proper mode.

#+BEGIN_SRC elisp
  (defun warnings-mode-hook ()
    "Hook for enabling the warning face on strings with a warning prefix."

    (font-lock-add-keywords nil
      '(("\\(XXX\\|FIXME\\|TODO\\|HACK\\|NOTE\\|BUG\\)"
      1 font-lock-warning-face prepend))))
#+END_SRC

Text mode is not a programming language, but it's used quite often in this context too. In this case, I want =wc-mode= activated.

#+BEGIN_SRC elisp
  (add-hook 'text-mode-hook (lambda () (wc-mode 1)))
#+END_SRC

** Tabs vs spaces
<<sec:tabsvsspaces>>

Tabs or spaces? [[https://www.emacswiki.org/emacs/TabsSpacesBoth][Both]]. The =smart-tabs-mode= has the philosophy of: tabs for indentation, spaces for alignment. This is only applied in languages where I'm usings tabs for indentation (C, C++ and Go).

#+BEGIN_SRC elisp
  (use-package smart-tabs-mode
    :ensure t
    :config
    (smart-tabs-add-language-support golang go-mode-hook
      ((c-indent-line . c-basic-offset)
       (c-indent-region . c-basic-offset)))
    (smart-tabs-insinuate 'c 'c++ 'golang))
#+END_SRC

** Shell

GNU Emacs already comes with =shell-mode= out of the box, and it's quite fine. That being said, I'd also like to add =bats-mode=:

#+BEGIN_SRC elisp
(use-package bats-mode
  :ensure t)
#+END_SRC

** Lisp

Emacs lisp needs =rainbow-delimiters= so the amount of parenthesis is less confusing. Moreover, I'm also enabling =eldoc-mode= and the aforementioned =warnings-mode-hook=.

#+BEGIN_SRC elisp
  (add-hook 'emacs-lisp-mode-hook
            (lambda ()
              (eldoc-mode 1)
              (warnings-mode-hook)
              (rainbow-delimiters-mode 1)
              ; https://github.com/jhenahan/emacs.d/blob/master/emacs-init.org#emacs-lisp
              (setq mode-name "ξ")))
#+END_SRC

Configure =ielm= with the proper ELisp utilities. As mentioned earlier, all these inferior modes are prefixed with @@html:<kbd>C-x i</kbd>@@ (mnemonic: "inferior"). =ielm= in particular is bound to @@html:<kbd>C-x i e</kbd>@@ and @@html:<kbd>C-x i l</kbd>@@, which follow the mnemonics "Emacs Lisp" and "Lisp" (I use both interchangeably, that's why I bind =ielm= twice).

#+BEGIN_SRC elisp
(use-package ielm
  :config
  (add-hook 'ielm-mode-hook #'eldoc-mode)
  (add-hook 'ielm-mode-hook #'rainbow-delimiters-mode)
  (global-set-key (kbd "C-x i e") 'ielm)
  (global-set-key (kbd "C-x i l") 'ielm))
#+END_SRC

Add =rainbow-delimiters= and =warnings-mode-hook= also for =lisp-mode= (that is, for Common Lisp and other variants, not Emacs Lisp):

#+BEGIN_SRC elisp
(add-hook 'lisp-mode-hook
          (lambda ()
            (warnings-mode-hook)
            (rainbow-delimiters-mode 1)
            (setq mode-name "λ")))
#+END_SRC

** C and C++

I have plans of bringing the extremely aptly named [[https://github.com/Sarcasm/irony-mode][irony-mode]] into my setup, but I haven't had the time for it yet. This mode implements a Clang backend through LSP in which you can power up GNU Emacs into being a fully featured C/C++ IDE. But as I said, I haven't looked into it yet, so for now let's just require the =warnings-mode-hook= function and the usage of tabs instead of spaces.

#+BEGIN_SRC elisp
;; Note that C-common includes languages with a similar syntax of C.
(add-hook 'c-mode-common-hook 'warnings-mode-hook)

;; C
(add-hook 'c-mode-hook
  (lambda () (setq indent-tabs-mode t)))

;; C++
(add-hook 'c++-mode-hook
  (lambda () (setq indent-tabs-mode t)))
#+END_SRC

The =clang-format+= package supersedes the =clang-format.el= file from the Clasp authors and it adds all the nuts and bolts to have =clang-format= work for the whole file automatically:

#+BEGIN_SRC elisp
(use-package clang-format+
  :ensure t
  :config
  (add-hook 'c-mode-common-hook #'clang-format+-mode))
#+END_SRC

CMake for y'all.

#+BEGIN_SRC elisp
  (use-package cmake-mode
    :ensure t
    :config

    (setq auto-mode-alist
          (append
           '(("CMakeLists\\.txt\\'" . cmake-mode))
           '(("\\.cmake\\'" . cmake-mode))
           auto-mode-alist))

    (use-package cmake-font-lock
      :ensure t
      :config

      (add-hook 'cmake-mode-hook 'cmake-font-lock-activate)
      (add-hook 'yaml-mode-hook 'warnings-mode-hook)))
#+END_SRC

** Ruby

Even if Ruby is one of my favorite languages and I use it very often, I don't do much about it in my configuration. I just include warning keywords and disallow the automatic including of the encoding magic comment:

#+BEGIN_SRC elisp
(use-package ruby-mode
  :config
  (setq ruby-insert-encoding-magic-comment nil)
  (add-hook 'ruby-mode-hook #'subword-mode)
  (add-hook 'ruby-mode-hook 'warnings-mode-hook))
#+END_SRC

That being said, give me the inferior mode for it (which following the aforementioned logic for inferior modes, it's bound to @@html:<kbd>C-x i r</kbd>@@):

#+BEGIN_SRC elisp
(use-package inf-ruby
  :ensure t
  :config
  (add-hook 'ruby-mode-hook #'inf-ruby-minor-mode)
  (global-set-key (kbd "C-x i r") 'inf-ruby))
#+END_SRC

** Go

My =golang= setup isn't that complicated either. As always, I include the =warnings-mode= hook. Other than that I've put some glue into the various golang tools available out there. This includes stuff like the usage of =goimports=, =gofmt= on save, among many other useful things.

#+BEGIN_SRC elisp
  (defun mssola-go-mode ()
    "My configuration for Go mode."

    ; Use goimports instead of go-fmt
    (setq gofmt-command "goimports")

    ; Call Gofmt before saving
    (add-hook 'before-save-hook 'gofmt-before-save)

    ; Integration flycheck with Go
    (add-to-list 'load-path
      (concat (getenv "GOPATH") "/src/github.com/dougm/goflymake"))
    (require 'go-flycheck)

    (setq indent-tabs-mode t)

    ; eldoc support
    (use-package go-eldoc
      :ensure t
      :config
      (require 'go-eldoc)))

  ;; Go
  (use-package go-mode
    :ensure t
    :config

    (add-hook 'go-mode-hook 'warnings-mode-hook)
    (add-hook 'go-mode-hook 'go-eldoc-setup)
    (add-hook 'go-mode-hook 'mssola-go-mode))
#+END_SRC

** Python

Install =elpy= as the environment for Python support:

#+BEGIN_SRC elisp
(use-package elpy
  :ensure t
  :config
  (advice-add 'python-mode :before 'elpy-enable)
  (when (require 'flycheck nil t)
    (setq elpy-modules (delq 'elpy-module-flymake elpy-modules))
    (add-hook 'elpy-mode-hook 'flycheck-mode)))
#+END_SRC

Automatically use =autopep8= on save:

#+BEGIN_SRC elisp
(use-package py-autopep8
  :ensure t
  :config
  (add-hook 'elpy-mode-hook 'py-autopep8-enable-on-save))
#+END_SRC

** Rust

Install =rust-mode= and add some hooks to make it friendlier.

#+BEGIN_SRC elisp
(use-package rust-mode
  :ensure t
  :config

  (add-hook 'before-save-hook
            #'(lambda ()
                (when (eq major-mode 'rust-mode)
                  (rust-format-buffer))))

  (use-package flycheck-rust
    :ensure t
    :config

    (add-hook 'flycheck-mode-hook #'flycheck-rust-setup)))
#+END_SRC

** JVM-based

Install =groovy-mode=, which I mainly use for [[https://www.jenkins.io/doc/pipeline/steps/workflow-cps/][Jenkins pipelines]].

#+BEGIN_SRC elisp
(use-package groovy-mode
  :ensure t)
#+END_SRC

** Other markup languages.

In here I put some markup languages which are not org. I don't do anything crazy with YAML, I just install its support and add it the =warnings-mode= hook:

#+BEGIN_SRC elisp
(use-package yaml-mode
  :ensure t
  :config

  (add-hook 'yaml-mode-hook 'warnings-mode-hook))
#+END_SRC

Same goes for =adoc= support:

#+BEGIN_SRC elisp
(use-package adoc-mode
  :ensure t
  :config

  (add-hook 'yaml-mode-hook 'warnings-mode-hook))
#+END_SRC

Now, for Markdown I have =markdown-preview-mode=, which allows me to preview a markdown document into HTML live (in combination with =markdown-calibre=, which is the tool available for openSUSE).

#+BEGIN_SRC elisp
(use-package markdown-mode
  :ensure t
  :config

  ;; This is the one that I got from openSUSE.
  (custom-set-variables
   '(markdown-command "/usr/bin/markdown-calibre"))

  ;; Preview mode does its things through websockets, so it's a requirement.
  ;; After that, we can safely require it.
  (use-package websocket
    :ensure t
    :config
    (use-package markdown-preview-mode
      :ensure t)))
#+END_SRC

** Web-related stuff.

Slim, SCSS and such shenanigans...

#+BEGIN_SRC elisp
(use-package slim-mode
  :ensure t)

(use-package scss-mode
  :ensure t
  :config

  (setq scss-compile-at-save nil)
  (add-hook 'scss-mode-hook 'warnings-mode-hook))

(use-package coffee-mode
  :ensure t)
#+END_SRC

Languages specific for backend code like PHP, and =web-mode=, which provides a bundle of features which are interesting for web-related stuff.

#+BEGIN_SRC elisp
(use-package php-mode
  :ensure t)

(use-package web-mode
  :ensure t
  :config

  (add-to-list 'auto-mode-alist '("\\.erb\\'" . web-mode))
  (add-to-list 'auto-mode-alist '("\\.jinja\\'" . web-mode))
  (add-to-list 'auto-mode-alist '("\\.html?\\'" . web-mode))

  (setq web-mode-markup-indent-offset 2
        web-mode-css-indent-offset 2
        web-mode-code-indent-offset 2)

  (use-package vue-mode
    :ensure t
    :config
    (setq mmm-submode-decoration-level 0)))
#+END_SRC

The =json-reformat= package provides functions for reformatting JSON strings. It happens from time to time that I have to read JSON output from responses, and it can be frustrating without proper formatting.

#+BEGIN_SRC elisp
(use-package json-reformat
  :ensure t)
#+END_SRC

** Devops

The new cool kids in the block (oh well, not so new anymore!). Here we have support for Dockerfiles, Hashicorp tooling, and Saltstack.

#+BEGIN_SRC elisp
(use-package dockerfile-mode
  :ensure t
  :config

  (add-to-list 'auto-mode-alist '("Dockerfile" . dockerfile-mode)))

(use-package terraform-mode
  :ensure t
  :config

  (terraform-format-on-save-mode))

(use-package hcl-mode
  :ensure t)

(use-package salt-mode
  :ensure t)
#+END_SRC

** Others

The [[https://github.com/mssola/soria][soria]] theme has the =soria-theme-purple-identifiers= hook. This hook instructs the theme to use purple for identifiers instead of the default color. This is a remnant from my Vim times, and I only apply it to some languages (random criteria really).

#+BEGIN_SRC elisp
  (dolist (lang-hook '(ruby-mode-hook
                       php-mode-hook
                       perl-mode-hook
                       emacs-lisp-mode-hook))
    (add-hook lang-hook 'soria-theme-purple-identifiers))
#+END_SRC

** LaTeX

Let's use [[https://www.gnu.org/software/auctex/][Auctex]] for LaTeX files. There are people doing crazy stuff with it. I keep it really simple because I don't have to face so many LaTeX files nowadays.

#+BEGIN_SRC elisp
(use-package tex
  :ensure auctex
  :config
  (setq TeX-auto-save t)
  (setq TeX-parse-self t)
  (setq-default TeX-master nil))
#+END_SRC

* WoMan

=WoMan= is a package that is included inside of GNU Emacs by default and that takes care of visualizing man pages. I don't do much here, I just tell =WoMan= to fill all the frame, and setup @@html:<kbd>C-h C-m</kbd>@@ as the key binding for it:

#+BEGIN_SRC elisp
(setq woman-fill-frame t)
(define-key 'help-command (kbd "C-m") #'woman)
#+END_SRC

* Misc

Install a set of useful functions from [[https://github.com/bbatsov][@bbatsov]]. The bindings are following Emacs style instead of being more Vim-like on purpose. For now we have the following bindings:

| Binding                         | Description                                                                                                                    |
|---------------------------------+--------------------------------------------------------------------------------------------------------------------------------|
| @@html:<kbd>C-c d</kbd>@@       | Delete the current file and its buffer. Note that this might not work well inside of a git project with staged stuff.          |
| @@html:<kbd>C-c r</kbd>@@       | Rename the current file and its buffer. In order to take this into effect you will have to change the file and save it though. |
| @@html:<kbd>C-c n</kbd>@@       | Cleanup the whole buffer or just a selected region.                                                                            |
| @@html:<kbd>C-backspace</kbd>@@ | Kill a given line backwards. That is, this is the reverse of Vim's @@html:<kbd>D</kbd>@@ in normal mode.                       |
| @@html:<kbd>C-a</kbd>@@         | The beginning of line has been remapped into crux's one, which takes indentation into account.                                 |
| @@html:<kbd>C-c o</kbd>@@       | Open the given resource as it would with plain =xdg-open=.                                                                     |

#+BEGIN_SRC elisp
(use-package crux
  :ensure t
  :custom
  (crux-move-visually t "Move lines visually")
  :config
  (global-set-key (kbd "C-c d") 'crux-delete-file-and-buffer)
  (global-set-key (kbd "C-c r") 'crux-rename-file-and-buffer)
  (global-set-key (kbd "C-c n") 'crux-cleanup-buffer-or-region)
  (global-set-key (kbd "C-<backspace>") 'crux-kill-line-backwards)
  (global-set-key [remap move-beginning-of-line] 'crux-move-beginning-of-line)
  (global-set-key (kbd "C-c o") 'crux-open-with))
#+END_SRC

** Screencast

Some utilities when recording my GNU Emacs adventures. First of all, =keycast= shows the keys being pressed in the mode line (it requires GNU Emacs 25.1 minimum). Moreover, we have =gif-screencast=, which allows you to record your GNU Emacs activity and saves it into a gif (unless you have specified the =XDG_VIDEOS_DIR=, it will use =~/Videos/emacs/<name>.gif=). =gif-keycast= requires GNU Emacs 26.1 or above:

#+BEGIN_SRC elisp
(if EMACS-25-OR-LATER
  (use-package keycast
    :ensure t))

(if EMACS-26-OR-LATER
  (use-package gif-screencast
    :ensure t
    :config
    (with-eval-after-load 'gif-screencast
      (define-key gif-screencast-mode-map (kbd "<f8>") 'gif-screencast-toggle-pause)
      (define-key gif-screencast-mode-map (kbd "<f9>") 'gif-screencast-stop))

    (global-set-key (kbd "<f7>") 'mssola-screencast)))
#+END_SRC

Last but not least, I use a wrapper to start a screencast, which is bound to @@html:<kbd>f7</kbd>@@. In order to pause the screencast you can press @@html:<kbd>f8</kbd>@@, and to completely stop it you can use @@html:<kbd>f9</kbd>@@:

#+BEGIN_SRC elisp
(defun mssola-screencast ()
  "Start keycast-mode and then start a gif screencast."

  (interactive)

  (if EMACS-26-OR-LATER
      (progn
        (keycast-mode)
        (gif-screencast))
    (error "Requires 26.1 or later.")))
#+END_SRC

** Emojis

Display emojis in buffer!

#+BEGIN_SRC elisp
(use-package emojify
  :ensure t
  :config

  (add-hook 'after-init-hook #'global-emojify-mode)
  (setq emojify-composed-text-p nil)
  (setq emojify-emoji-styles '(unicode github)))
#+END_SRC

* Installation

The installation process of my GNU Emacs configuration should already be handled by the =install.sh= script that can be found in the root of this project. If you want to do it manually:

- Create the =~/.emacs.d= directory if it has not been created yet.
- Copy the =init.el= into the =~/.emacs.d= directory. This is the only file that should be copied instead of linked because it will get replaced on the first run by =org-babel=.
- Link the =init.org=, =custom.el=, =abbrevs.el= and =gtkrc= files into the =~/.emacs.d= directory.
- Create the =~/.emacs.d/lisp= subdirectory and link the =lisp/g.el= file there.
- Clone the [[https://github.com/mssola/soria][soria]] project and link the =soria-theme.el= file into the =~/.emacs.d= directory.

Other than that, in the =dependencies.sh= script you will be able to find the **runtime dependencies** that should be installed in order to get everything working. Note that this script assumes that you are running openSUSE, so don't run it blindly. All the software installed by this script has already been explained during this configuration.

* Credits

I've built this file by simply scavenging from other people's emacs.d/dotfiles repositories. I have taken lots of pieces from here and there, but most notably:

- [[https://github.com/ereslibre/dotfiles][@ereslibre]]
- [[https://github.com/dmacvicar/dotfiles][@dmacvicar]]
- [[https://github.com/bbatsov/emacs.d][@bbatsov]]
- [[https://github.com/aaronbieber/dotfiles][@aaronbieber]]
- [[https://github.com/purcell/emacs.d][@purcell]]
- [[https://github.com/sachac/.emacs.d][@sachac]] ([[http://pages.sachachua.com/.emacs.d/Sacha.html][HTML version]])
- [[https://github.com/larstvei/dot-emacs][@larstvei]]
- [[https://github.com/hlissner/doom-emacs][doom-emacs]]
- [[https://gitlab.com/protesilaos/dotfiles][@protesilaos]]

* License

#+BEGIN_SRC text :tangle no
  Copyright (C) 2014-2020 Miquel Sabaté Solà <mikisabate@gmail.com>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  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
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#+END_SRC
