Surgot's Emacs Config

Table of Contents

1. Introduction

This is an Elisp program that runs every time I start my Emacs editor. Some people also call it an emacs config. Why am I writing it under Org mode? Literate Programming, Bitch!

real_programmers.png

Figure 1: XKCD Emacs Comic

2. Installation

You can use my Emacs config anytime; the installation is pretty simple.

Note: I won't suggest you use it without understanding the code.

  • First, get rid of your ~/.emacs.d and ~/.emacs.
  • Run git clone git@surgot.tech:emacs.d ~/.emacs.d
  • Open Emacs with fingers crossed!

3. Package Management

Emacs is like an operating system; it is highly extensible. You can install new functionality by just installing a package, similar to how you do it in an OS. You can also configure these programs by changing some Elisp variables.

An average Emacs user can easily end up installing 100+ packages.

3.1. Melpa

By default, Emacs contains a limited number of package choices. This is why we need Melpa. It's a package repository for Emacs.

MELPA is an ELPA-compatible package repository that contains an enormous number of useful Emacs packages.

Think of it like the VSCode Plugin Marketplace (eww).

(require 'package)
(setq package-enable-at-startup nil)

(add-to-list 'package-archives
	     '("melpa" . "https://melpa.org/packages/"))
(package-initialize)

3.2. Package Manager

The use-package macro allows you to isolate package configuration in your .emacs file in a way that is both performance-oriented and, well, tidy.

(unless (package-installed-p 'use-package)
  (package-refresh-contents)
  (package-install 'use-package))

4. Better Appearance

4.1. Basic Interface Settings

  • Disable dialog boxes: This setting disables the display of dialog boxes, such as confirmation or warning pop-ups, in Emacs. It allows for a smoother and uninterrupted workflow.

    (setq use-dialog-box nil)
    
  • Disable file dialogs: This setting disables the use of file selection dialogs in Emacs. Instead, Emacs will rely on command-line or programmatic methods for file operations.

    (setq use-file-dialog nil)
    
  • Disable backup files: By setting this variable to `nil`, Emacs will not create backup files. This helps to avoid cluttering the file system with unnecessary backup copies.

    (setq make-backup-files nil)
    
  • Disable auto-save: Auto-save automatically saves buffer contents periodically in case of unexpected Emacs or system crashes. However, if you prefer to disable this feature, you can set this variable to `nil`.

    (setq auto-save-default nil)
    
  • Hide menu bar: This setting hides the menu bar in Emacs, providing more vertical space for your text and reducing visual distractions.

    (menu-bar-mode -1)
    
  • Hide tool bar: This setting hides the tool bar, which contains various icons and shortcuts, in Emacs. It further maximizes the available space for editing and reduces clutter.

    (tool-bar-mode -1)
    
  • Hide fringes: Fringes are the narrow areas on the left and right sides of the Emacs window. By disabling them, you can utilize the full width of the window for your text.

    (fringe-mode -1)
    
  • Hide scroll bar: Emacs provides a scroll bar for navigating through the buffer. If you prefer a more minimalistic interface, you can hide the scroll bar with this setting.

    (scroll-bar-mode -1)
    
  • Enable subword navigation: Subword navigation allows moving the cursor through CamelCase or snakecase words more intelligently. This setting enables subword navigation globally in Emacs.

    (global-subword-mode 1)
    
  • Use y-or-n-p for prompts: By default, Emacs prompts for user confirmation using 'yes' or 'no.' This setting changes it to use 'y' or 'n' for shorter and faster responses.

    (defalias 'yes-or-no-p 'y-or-n-p)
    

4.2. Theme

The ef-themes package is an Emacs package that provides a collection of visually appealing themes for Emacs. It enhances the visual experience of Emacs by offering different color schemes and styles that can be applied to the editor.

(use-package ef-themes
  :if window-system
  :ensure t
  :config
  ;; Enable the theme
  (load-theme 'ef-winter t))

4.3. Font

I love JetBrains Mono. Best for programming. Using it since 2018. Make sure to install it in your system. I use Arch, so I run sudo pacman -S ttf-jetbrains-mono.

(add-to-list 'default-frame-alist
	     '(font . "JetBrains Mono-14"))

5. Editing Features

5.1. Hungry Delete

Hungry Delete is a minor-mode that causes deletion to delete all whitespace in the direction you are deleting. Works exactly like c-hungry-delete-mode, which is where the code was from. This just packages it up to be easier to use in other modes.

(use-package hungry-delete
  :ensure t
  :defer t
  :config (global-hungry-delete-mode))

6. Better Emacs

6.1. Startup Screen (dashboard)

The "emacs-dashboard" package elevates your Emacs startup experience by providing an extensible and customizable startup screen. It presents you with important information, such as recent files, project directories, and agenda items, in a visually appealing layout. With "emacs-dashboard," you can quickly access frequently used commands, navigate to recent projects, and stay organized, all while setting the right mood for your Emacs sessions.

(use-package dashboard
  :ensure t
  :config
  (dashboard-setup-startup-hook)
  (setq dashboard-startup-banner "~/.emacs.d/avatar.png")
  (setq dashboard-banner-logo-title "I am just a coder for fun"))
(setq inhibit-startup-screen t)

6.2. Modeline (moodline)

"Mood-line" is an Emacs package that enhances the mode line, providing a visually appealing and informative display. It enriches your editing experience by showing essential details about the buffer, active modes, and other relevant information, all in a sleek and elegant format.

(use-package mood-line
  :ensure t
  :if window-system
  :init
  (mood-line-mode))

6.3. Command Menu

After pressing M-x, Emacs users see a prompt below; this prompt allows us to run any command within Emacs. This is what I loved about Emacs when I was learning it first. Almost anything, any functionality, any program, everything is a function, and I can access that function by just pressing M-x. But memorizing all these commands is hard, also typing it. Emacs does provide tab completion, but it sucks. So we are gonna pull up the Emacs magic and install some packages to make it better.

6.3.1. Ido Mode

The Ido package lets you switch between buffers and visit files and directories with a minimum of keystrokes. It is a superset of Iswitchb, the interactive buffer switching package by Stephen Eglen.

(use-package ido-vertical-mode
  :ensure t
  :config
  (setq ido-enable-flex-matching t)
  (setq ido-everywhere t)
  (setq ido-vertical-define-keys 'C-n-and-C-p-only)      
  :init
  (ido-mode 1)
  (ido-vertical-mode 1))

6.3.2. Smex

Smex is an M-x enhancement for Emacs. Built on top of Ido, it provides a convenient interface to your recently and most frequently used commands. And to all the other commands, too.

(use-package smex
  :ensure t
  :init (smex-initialize)
  :bind
  ("M-x" . smex))

6.4. Emacs Config

6.4.1. Custom Variables File

(setq custom-file (expand-file-name "custom.el" user-emacs-directory))  

7. IDE Features

7.1. Centaur Tabs

Centaur Tabs is an Emacs package that enhances the tab bar functionality, providing a more visually appealing and user-friendly way to manage multiple open buffers (files) within the editor. It may offer features such as clickable tabs, grouping tabs based on projects or file types, tab previews, and convenient tab navigation options. For more detailed information about Centaur Tabs and its specific functionalities, it is recommended to refer to its documentation or source code repository.

(use-package centaur-tabs
  :if window-system
  :demand
  :init
  ;; Set the style to rounded with icons
  (setq centaur-tabs-style "bar")
  (setq centaur-tabs-set-icons t)

  :config
  ;; Enable centaur-tabs
  (centaur-tabs-mode t))

7.2. Treemacs

"Treemacs" is an Emacs package that brings a tree-style file explorer directly into your Emacs workspace. With its intuitive and organized display, Treemacs allows you to navigate and manage files and directories effortlessly. It provides a visual representation of your project's structure, making it easy to switch between different files, directories, and buffers. Treemacs supports various project management features and integrates seamlessly with popular version control systems like Git. This powerful package enhances your Emacs workflow, making file management and project navigation a breeze.

(use-package treemacs
  :ensure t
  :defer t
  :bind
  (("C-c t" . treemacs))
  :config
  (setq treemacs-width 30)
  (setq-local mode-line-format nil))

7.3. Highlight Indent Guides

The "highlight-indent-guides" package is an Emacs extension that enhances code readability by providing visual indent guides. As you work with code, it displays vertical lines at each level of indentation, making it easier to distinguish different blocks and understand the code's structure. This feature is particularly useful for languages with significant indentation, such as Python. "highlight-indent-guides" helps maintain consistent and well-organized code, ensuring a more pleasant coding experience in Emacs.

(use-package highlight-indent-guides
  :ensure t
  :defer t
  :hook (prog-mode . highlight-indent-guides-mode)
  :config
  (setq highlight-indent-guides-method 'character)
  (setq highlight-indent-guides-character ?\|)
  (setq highlight-indent-guides-responsive 'top))

7.4. Format all

A "format all" package in Emacs typically aims to automate and simplify the process of formatting code in various programming languages. It offers a unified command to apply code formatting rules across the entire buffer or project, ensuring consistent code style. Such packages may support multiple programming languages and use popular code formatters (e.g., Prettier, Black, clang-format) to automatically reformat code according to predefined configurations. By using the "format all" package, Emacs users can save time and effort in maintaining clean and well-formatted code. For specific details on a particular "format all" package, users should refer to its documentation or repository.

(use-package format-all
  :ensure t)

7.5. Company

Company mode in Emacs is a versatile and intelligent completion framework that enhances coding productivity by providing context-aware code suggestions. As you type, Company mode offers a list of potential completions based on the current context, language, and installed backends. It supports various programming languages and can integrate with external completion tools like LSP (Language Server Protocol) servers. With its seamless and customizable integration, Company mode enables faster and more accurate code writing, streamlining the coding process and making Emacs an efficient and powerful text editor for developers.

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

7.6. Projectile

Projectile is a powerful project interaction library for Emacs that enhances project management and navigation. It provides a unified interface to work with multiple projects, enabling developers to switch between projects effortlessly, find files quickly, and execute project-specific commands with ease. Projectile indexes project files for speedy searches and supports various version control systems. With its intuitive keybindings and customizable behavior, Projectile simplifies project-related tasks and significantly improves productivity, making Emacs a more efficient and developer-friendly text editor for managing and working with projects of all sizes.

(use-package projectile
  :ensure t
  :defer t
  :config
  ;; Enable Projectile globally
  (setq projectile-completion-system 'ido)
  (setq ido-enable-flex-matching t)
  (projectile-mode 1))

8. Advance IDE Features

Emacs is a versatile tool that can serve as a writer's machine, enabling tasks like writing books, creating spreadsheets, and crafting theses, among other uses. Personally, I primarily utilize Emacs for programming, blogging, and journaling.

While I prefer a minimalist text editor with fewer distractions, I recognize the need for more robust IDE features, especially for larger projects involving frameworks. Auto-completion and type checking are indispensable in such scenarios. Therefore, I appreciate the flexibility of Emacs, as it allows me to tailor the environment to suit my various programming needs.

8.1. Emacs LSP

The "emacs-lsp" project is a collection of Emacs packages and tools that implement the Language Server Protocol (LSP) in Emacs. LSP is a standardized communication protocol that enables integration with language servers, which are external programs providing advanced code analysis and language-specific features.

The goal of the "emacs-lsp" project is to enhance the Emacs text editor and turn it into a powerful Integrated Development Environment (IDE) by leveraging the capabilities of language servers. These packages provide language-specific features such as autocompletion, real-time error checking, code navigation, and more. By adhering to the LSP, developers can use a consistent approach across various programming languages, streamlining their workflow and improving productivity.

The project offers a diverse range of packages, each tailored to specific programming languages and their corresponding language servers. This initiative fosters an integrated and standardized environment for Emacs users, enabling them to efficiently code in different languages and benefit from advanced language-specific tooling within their favorite text editor. The "emacs-lsp" project is a valuable resource for developers seeking a robust and unified coding experience in Emacs.

8.1.1. LSP Mode

LSP mode (Language Server Protocol mode) in Emacs is a powerful extension that brings IDE-like capabilities to various programming languages. It provides integration with language servers, which are separate programs that offer advanced code analysis, autocompletion, and other language-specific features. LSP mode allows developers to benefit from a consistent development experience across different programming languages, eliminating the need for language-specific configurations and setups. With LSP mode, Emacs users can enjoy enhanced code navigation, error checking, and automatic code formatting, significantly improving their productivity and coding efficiency.

completion.gif

Figure 2: LSP mode completion

(use-package lsp-mode
  :ensure t
  :defer t
  :init
  (setq lsp-keymap-prefix "C-c l")
  :config
  (setq lsp-headerline-breadcrumb-enable nil))

8.1.2. LSP UI

In Emacs, lsp-ui is a complementary extension to lsp-mode (Language Server Protocol mode). It enhances the Language Server Protocol experience by offering a user-friendly interface with features like real-time error checking, code actions, and code lenses. lsp-ui also enables convenient peeking into definitions and references. With lsp-ui, Emacs users can enjoy a more interactive and productive coding experience with language servers.

(use-package lsp-ui
  :ensure t
  :defer t)

8.1.3. DAP mode

DAP mode (Debug Adapter Protocol mode) in Emacs is an extension that provides a powerful debugging experience within the text editor. By leveraging the Debug Adapter Protocol, DAP mode enables seamless integration with debug servers, allowing developers to debug their programs efficiently. With DAP mode, users gain access to essential debugging features such as breakpoints, stepping through code, inspecting variables, and evaluating expressions. This extension facilitates a smooth and consistent debugging process across various programming languages, empowering developers to identify and resolve issues with ease, all within the familiar environment of Emacs.

(use-package dap-mode
  :after lsp-mode
  :ensure t
  :defer t)

8.2. Languages

Now, we will configure language server protocol and other settings for each, languages I work on, one by one.

8.2.1. Web (html/css/js)

  1. Web Mode

    Web Mode in Emacs is a major mode that enhances web development by providing specialized editing features for working with HTML, CSS, JavaScript, and other web-related languages. It intelligently handles nested tags, auto-closes HTML tags, and offers indentation and syntax highlighting tailored for web development. Web Mode also supports embedded templates and server-side code, making it a versatile tool for web developers to efficiently create and edit web pages and applications within the Emacs text editor.

    (use-package web-mode
      :ensure t
      :defer t
      :config
      (setq
       web-mode-markup-indent-offset 2
       web-mode-css-indent-offset 2
       web-mode-code-indent-offset 2
       web-mode-style-padding 2
       web-mode-script-padding 2
       web-mode-enable-auto-closing t
       web-mode-enable-auto-opening t
       web-mode-enable-auto-pairing t
       web-mode-enable-auto-indentation t)
      :mode
      (".html$" "*.php$" "*.tsx"))
    
  2. Emmet-mode

    Emmet Mode in Emacs is an extension that significantly boosts web development productivity by enabling advanced HTML and CSS abbreviations. Originally inspired by the Emmet toolkit, this mode allows developers to write complex markup with ease using intuitive shortcuts and expand them into full HTML or CSS code. It supports dynamic placeholders, numeric repetition, and custom abbreviation expansion, making it a powerful tool for rapidly generating and editing HTML and CSS structures. With Emmet Mode, Emacs users can streamline their web development workflow, saving time and effort while maintaining clean and well-structured code.

    emmet.gif

    Figure 3: Emmet Mode Demo

    (use-package emmet-mode
      :ensure t
      :defer t)
    

8.2.2. Typescript

  1. Tide Mode

    TypeScript Interactive Development Environment for Emacs.

    (use-package tide
      :ensure t
      :defer t
      :config
      (setq company-tooltip-align-annotations t)
      (add-hook 'before-save-hook 'tide-format-before-save))
    (add-hook 'typescript-mode-hook #'setup-tide-mode)
    
    (defun setup-tide-mode ()
      "Set up Tide mode."
      (interactive)
      (tide-setup)
      (flycheck-mode +1)
      (setq flycheck-check-syntax-automatically '(save-mode-enabled))
      (eldoc-mode +1)
      (tide-hl-identifier-mode +1)
      (company-mode +1))
    
  2. TSX

    Tide also support TSX, just need to enable web-mode with tsx files.

    (add-hook 'web-mode-hook
    	  (lambda ()
    	    (when (string-equal "tsx" (file-name-extension buffer-file-name))
    	      (setup-tide-mode))))
    

8.2.3. Python

  1. Language Server Protocol

    Pyright is a fast type checker meant for large Python source bases. It can run in a “watch” mode and performs fast incremental updates when files are modified. For python I decided to use pyright language server protocol.

    (use-package lsp-pyright
      :ensure t
      :defer t
      :hook (python-mode . (lambda ()
    			 (setq indent-tabs-mode t)
    			 (setq tab-width 4)
    			 (setq python-indent-offset 4)
    			 (company-mode 1)
    			 (require 'lsp-pyright)
    			 (pyvenv-autoload)
    			 (lsp))))
    
  2. Virutal Environment

    This is a simple global minor mode which will replicate the changes done by virtualenv activation inside Emacs, basically it helps me loading my python virtualenv for IDE features like autocompletion.

    (use-package pyvenv
      :ensure t
      :defer t)  
    

    I use my self made elisp function, for automatically load python virtualenv, I always use env dir as virtualenv inside project root. So everytime I open python-mode (aka python file), it looks for any env dir and load the env.

    (defun pyvenv-autoload ()
      (require 'pyvenv)
      (require 'projectile)
      (interactive)
      "auto activate venv directory if exists"
      (f-traverse-upwards (lambda (path)
    			(let ((venv-path (f-expand "env" path)))
    			  (when (f-exists? venv-path)
    			    (pyvenv-activate venv-path))))))
    (add-hook 'python-mode 'pyvenv-autoload)
    

8.3. Git Integration

I can't use git without Magit. Magit is a complete text-based user interface to Git. It fills the glaring gap between the Git command-line interface and various GUIs, letting you perform trivial as well as elaborate version control tasks with just a couple of mnemonic key presses. Magit looks like a prettified version of what you get after running a few Git commands but in Magit every bit of visible information is also actionable to an extent that goes far beyond what any Git GUI provides and it takes care of automatically refreshing this output when it becomes outdated. In the background Magit just runs Git commands and if you wish you can see what exactly is being run, making it possible for you to learn the git command-line by using Magit. I ❤ Magit.

(use-package magit
  :ensure t
  :defer t)

9. Org Mode

Org Mode in Emacs is a powerful and versatile outlining and organizing tool that extends the text editor's capabilities beyond simple plain text. It provides a structured and hierarchical format for creating notes, to-do lists, project plans, and more. Org Mode offers features such as headings, lists, tables, tags, and timestamps, enabling users to manage complex information with ease. It supports exporting to various formats like HTML, PDF, and LaTeX, making it suitable for both personal organization and professional document preparation. With its extensive functionality and seamless integration with Emacs, Org Mode empowers users to efficiently manage tasks, maintain documentation, and stay organized in a clutter-free and efficient environment.

9.1. Org Bullet

Org Bullet is an Emacs package that enhances the visual appearance of Org Mode outlines by replacing plain text bullet points with custom symbols. It offers a variety of stylish bullets to represent different outline levels, making the organization of tasks and information more visually appealing and easier to comprehend. Org Bullet is highly configurable, allowing users to customize the bullet symbols to their preference and create a more visually pleasing and organized presentation of hierarchical data within Org Mode documents.

(use-package org-bullets
  :ensure t
  :defer t
  :config
  (add-hook 'org-mode-hook (lambda () (org-bullets-mode 1))))

9.2. Org Agenda

Org Agenda in Emacs is a powerful and flexible tool for managing tasks, appointments, and notes. It provides a dynamic view of scheduled events, deadlines, and TODO items from various Org Mode files, enabling users to organize and prioritize their work effectively. With its customizable views, filters, and sorting options, Org Agenda offers a comprehensive overview of upcoming events and pending tasks, making it an essential feature for staying organized and productive in Emacs.

(setq org-agenda-files (append
			(file-expand-wildcards "~/dox/org/*.org")))

10. Misc

Some extra setting, which doesn't fall in any category above.

10.1. Locales

(setq locale-coding-system 'utf-8)
(set-terminal-coding-system 'utf-8)
(set-keyboard-coding-system 'utf-8)
(set-selection-coding-system 'utf-8)
(prefer-coding-system 'utf-8)

Author: Biswakalyan Bhuyan

Created: 2023-07-20 Thu 06:39

Validate