Skip to content

Animeshz/.emacs.d

Repository files navigation

My Literate Emacs Configuration

Preliminaries

Preface

I was first introduced to Emacs by a friend at my college. I had been resistant to a lot of things in my life, like the 4-finger claw for playing mobile games, 10-finger touch typing on laptops, learning vim keybindings, and this time, Emacs. I can only count how many times these things have saved me from a time-bubble burst. These seemingly obscure and optional(-looking) things have indeed proven to be a few of the most influential aspects of my life.

Emacs holds a special place at the nucleus of my technological toolkit. All my workflows simplify down, because of its indcredible ingrained & integrable plugin ecosystem. You can’t imagine any other software working so well for a variety of use cases, sometimes even better than their recommended options. It has elevated my workflow as a programmer to a whole new level.

./ss.jpg

Introduction

This file, even though looking like a documentation or a book is indeed my emacs configuration! (And also my ever updating notes while I’m learning emacs).

This is possible because of the org-babel plugin (inbuilt in Emacs as of now) that allows Emacs to contain code-blocks within the org-mode documents. And this style of writing code within natural language is known as Literate Programming.

You can view my configuration at:

Getting Started

Installation

Install as you wish, I prefer using nix + home-manager for installation.

{ pkgs }:
{
  programs.emacs = {
    enable = true;
    package = pkgs.emacs29;

    extraPackages = epkgs: with epkgs; with pkgs; [
      custom.emacs-pcre
      custom.emacs-chdir
    ];
  };
}

I export emacs-pcre and emacs-chdir as custom packages on my nix config.

Basic Keybinds

I like to remember a few keybinds so in-case my config had any error, I could still use emacs with these fallback keybinds. And these keybinds are in general good enough for my hands as well hence I mostly don’t change them.

  • C = Ctrl
  • M = Alt
  • S = Shift
ScopeKeybindAction
globalM-xView Available Commands
C-x C-fFind File
C-h [f / v / k]Help on [functions / variables / key-chords]
C-x [2 / 3 / 0 / 1]Window Split [Down / Right / Close / Close All Except This]
C-x o / C-w C-w (Evil)Switch Window Split
org-modeC-c C-cRun CodeBlock or Format Table
C-c C-lInsert Link
C-c C-,Insert Snippets
minibufferC-yPaste

M-<number> is a shorthand for C-u <number>, and is used to pass first argument number in interactive commands via M-x or keybind.

Tutorials

I like to recommend this video if you want to get familiarized with emacs! This packs a lot of information with effective presentations instead of most videos which talk way too much and delivers barely anything useful.

This playlist is good for getting quick short videos for further learning emacs on your own pace.

Emacs Configuration

Early-Init and Init

The early-init.el and init.el files are the first two files emacs read when starting up.

I kept them separated from this main configuration because the former do very naive stuffs (such as basic ui changes and performance optimization), and the latter contains bootstrap code for Elpaca the package manager which is a prerequisite for most of this config and also it loads this config in the end.

Better Defaults (Almost Mandatory)

Emacs requires some essential tweaks to become somewhat usable.

;;; This file is generated from config.org | -*- lexical-binding: t; -*-

;; Enable minibuffer history, prioritizes M-x & vim commands with most recent commands issued
(setq history-length 100)
(savehist-mode 1)

;; Enable recording recent files & window configuration for going back and forth
(recentf-mode 1)  ; SPC-f-r
(winner-mode 1)   ; C-c [left / right]

;; Set relative lines
(setq display-line-numbers-type 'relative)
(global-display-line-numbers-mode t)

;; Configure automatic line breaks and word-wrap (just in case)
(setq-default fill-column 120  ; SPC-c
              auto-fill-function 'do-auto-fill)
(global-visual-line-mode t)  ; SPC-w

;; I prefer indentation with spaces
(setq-default tab-width 4
              indent-tabs-mode nil)

;; Make scratch buffer text-mode
(setq-default initial-scratch-message nil
              initial-major-mode 'text-mode)

;; Replace yes/no with y/n
(setq use-short-answers t)

;; Don't break hardlinks
(setq backup-by-copying t)

;; Count current and total count of isearch
(setq isearch-lazy-count t)

;; Modeline, if the custom one didn't work
(column-number-mode 1)

Better Org-Mode Defaults

Same goes for org-mode.

;; Allow these languages for code evaluation in org-mode documents
(org-babel-do-load-languages 'org-babel-load-languages
                             '((emacs-lisp . t) (shell . t) (python . t) (ruby . t) (C . t) (js . t)))  ; C-c C-c
(setq org-confirm-babel-evaluate nil)

;; Give org html export a deterministic id so it doesn't pollute git history
(defun my/org-deterministic-reference (references)
  (cl-loop for new from (length references) until (not (rassq new references))
           finally return new))
(advice-add #'org-export-new-reference :override #'my/org-deterministic-reference)

Base Packages

These core packages are the scaffold upon which the entire configuration below is assembled.

;; Used to set keybinds
(use-package general
  :config
  (general-override-mode)
  (general-auto-unbind-keys))

;; Emulates vim keybinds & modal editing
(use-package evil
  :init
  (setq evil-v$-excludes-newline t       ; $ in visual doesn't include \n
        evil-kill-on-visual-paste nil    ; pasting in visual mode won't copy replaced text to clipboard
        evil-auto-indent nil             ; o and O doesn't add indents
        evil-cross-lines t               ; h and l to move to newline
        ;; evil-respect-visual-line-mode t  ; physical line as $ anchor instead of \n, caveat: dj dk doesn't work as intended
        evil-shift-width tab-width       ; << and >>
        evil-want-keybinding nil         ; required by =evil-collection=
        evil-split-window-below t
        evil-vsplit-window-right t)
  :config
  (evil-mode 1))

;; Extend support of vim keybindings on to various other packages
(use-package evil-collection
  :after evil
  :config
  (evil-collection-init))

(elpaca-wait)

The evil package provides Vim’s Modal Editing in Emacs. I have notes on the only Vim keybind you need to know on my site.

Set Fonts

Set global font, whichever is available in the preferred-fonts.

(defvar preferred-fonts
  (list "CaskaydiaCove Nerd Font Mono" "Fira Code Mono" "Jetbrains Mono"))

(custom-set-faces
 '(default ((t (:family (cl-find-if font-info preferred-fonts) :height 120)))))

I didn’t set variable-pitch and fixed-pitch faces separately and forced Mono font everywhere, although that’s also an option.

Set Keybinds

General keybinds which are not specific to any package.

With evil we have 2 things, evil states (namely normal, motion, visutal, etc) and mode-map. In emacs, everything we edit (the buffer) has a major mode (e.g. prog-mode) and multiple minor modes (e.g. winner-mode, rust-mode) enabled through file extension or hooks, each of these modes have a mode-map associated in order to set keybinds in buffers with those modes enabled. Read more about them here.

Normal Keybinds

Keybinds without prefix.

(general-def '(normal motion visual operator)
  ;; Adjust font size
  "C-+" #'text-scale-increase
  "C-_" #'text-scale-decrease

  ;; Move lines without moving cursor
  "," #'evil-scroll-line-down
  "." #'evil-scroll-line-up

  ;; Indent region (same keybind as vscode lol)
  "C-S-i" (lambda () (interactive) (indent-region (point-min) (point-max)))

  "<escape>" #'keyboard-escape-quit)

Leader Keybinds

Keybinds with SPC prefix.

(general-create-definer leader-key
  :states '(normal motion visual operator emacs)
  :keymaps 'override
  :prefix "SPC")

(leader-key
  "ff" #'find-file
  "fr" #'recentf-open
  "tw" #'delete-trailing-whitespace
  "ev" #'eval-region
  "x" #'kill-this-buffer
  "r" #'revert-buffer
  "c" #'display-fill-column-indicator-mode
  "s" #'switch-to-buffer
  "d" #'bookmark-jump
  "w" #'visual-line-mode  ; toggle word-wrap
  "/" #'comment-dwim)

Miscellaneous

Ergonomic UX on insert-like modes,

(general-unbind "C-<backspace>")

(general-def 'insert
  "<tab>" #'tab-to-tab-stop
  "C-<backspace>" #'evil-delete-backward-word
  "C-S-v" #'evil-paste-before-cursor-after)

(general-def '(isearch-mode-map)
  "<down>" #'isearch-ring-advance
  "<up>" #'isearch-ring-retreat
  "C-S-v" #'isearch-yank-kill)

(general-def '(minibuffer-mode-map)
  "C-<backspace>" #'evil-delete-backward-word
  "C-S-v" #'yank)

Some org mode enhancements

;; Toggle folding org headings with tab/ret
(general-def 'normal org-mode-map
  "<tab>" #'evil-toggle-fold
  "<RET>" (lambda ()
            (interactive)
            (cond
             ((org-at-heading-p) (evil-toggle-fold))
             ((org-in-regexp org-link-any-re) (org-open-at-point))
             (t (evil-ret)))))

Productivity Enhancers

Undo History

Preserving undo history is probably the first productivity enhancer I can think of.

;; keep undo history
(use-package undo-fu
  :config
  (general-setq evil-undo-system 'undo-fu))

;; keep file's undo history between emacs sessions
(use-package undo-fu-session
  :config
  (undo-fu-session-global-mode))

;; make undo history a tree on-the-fly
(use-package vundo
  :ensure (vundo :host github :repo "casouri/vundo")
  :config
  (general-def 'normal vundo-mode-map "<escape>" #'vundo-quit))

Key & Minibuffer completions

This is really important as my memory is dum dum.

;; Shows valid key combinations after a key-press
(use-package which-key
  :config
  (setq which-key-idle-delay 0.4)
  (which-key-mode))

Completion over M-x and other help panels.

;; Transforms prompts into selectable panels
(use-package vertico
  :config
  (setq vertico-count 20
        vertico-resize nil
        vertico-cycle t)
  (vertico-mode))

;; Allows partial, unordered and regex search on those panels
(use-package orderless
  :config
  (setq completion-styles '(orderless basic)))

Hop (Jump Anywhere on Buffer)

This was my most missing feature from nvim, so much so I wrote this package myself. Read more on hop.el.

(require 'pcre)

(use-package hop
  :ensure (hop :host github :repo "Animeshz/hop.el")
  :config
  (general-def '(normal motion visual operator)
    "go" #'hop-word
    "gl" #'hop-char
    "gp" #'hop-regex-pattern
    "gk" #'hop-line))

AutoCompletion & Snippets

Woah, now we want to speed up!

;; Inline completions frontend
(use-package company
  :config
  (setq company-idle-delay 0
        company-show-numbers t)
  (global-company-mode 1))

Now let’s add a few completion backends.

;; Tabnine is my choice!
(use-package company-tabnine)

;; Add snippets to the stack!
(use-package yasnippet
  :config
  (setq yas-snippet-dirs '("~/.emacs.d/snippets"))
  (leader-key "ns" #'yas-new-snippet)  ; SPC-n-s
  (yas-global-mode 1))

Setup company at the end of everything, so multiple backends can be grouped and prioritized.

(defun my/setup-company ()
  (setq company-backends '((company-yasnippet))))
(add-hook 'elpaca-after-init-hook #'my/setup-company)

;; Tabnine may not sometimes keep up with my typing speed, so I may wanna toggle it often with SPC-t-n
(defun my/toggle-tabnine ()
  (interactive)
  (setq company-backends
        (cond ((equal company-backends '((company-yasnippet))) '((company-tabnine :with company-yasnippet)))
              (t '((company-yasnippet))))))
(leader-key
  "tn" #'my/toggle-tabnine)  ; SPC-t-n

Programming

Highlighting

(use-package markdown-mode)
(use-package nix-mode)

Project Management

Consider git repositories as projects, and provide useful commands for project-scoped files.

(use-package projectile
  :config
  (projectile-mode +1)
  (leader-key
    "p" #'projectile-command-map))

Some importantkeybinds to remember,

KeybindAction
SPC-p-fFind file within project
SPC-p-x-sOpen shell on project
SPC-p-s-gGrep on project
SPC-p-DDired on project

Add-ons

Remote Execution

Tramp (Transparent Remote Access Multiple Protocol) automatically kicks in when working in /[protocol:]user@x.x.x.x:/path/to/file directory. Can be opened via normal find-file or in the org code block with :dir property.

(use-package tramp
  :ensure nil
  :config
  (setq tramp-default-method "ssh"))

Embark

This is great article on uses of Embark.

It makes minibuffer as flexible as normal buffer is.

(use-package embark
  :config
  (setq embark-quit-after-action nil)
  (general-def '(normal motion visual global)
    "C-."  #'embark-act
    "C-;"  #'embark-export))

Most useful actions on embark-act

ScopeKeybindAction
globalC-hExpand all actions
iInsert minibuffer candidate
M-xgSet keybind to command for session

Marginalia

Add extra information on minibuffers.

(use-package marginalia
  :config
  (setq marginalia-align 'center)
  (marginalia-mode))

Better Help

;; Setup better help
(use-package helpful
  :config
  ;; Remap C-h to helpful package
  (general-define-key
   :prefix "C-h"
   "f" #'helpful-callable
   "v" #'helpful-variable
   "k" #'helpful-key
   "F" #'helpful-function
   "C" #'helpful-command))

Chdir Support

Syncing /proc/self/cwd with changes to (default-directory).

(require 'chdir)

Look & Feel

Theme

The main theme when opening emacs.

(use-package nimbus-theme
  :config
  (global-hl-line-mode 1)
  (load-theme 'nimbus t))

ModeLine

The beautiful bottom mode-line.

(use-package telephone-line
  :config
  ;; Set theme (color & separator)
  (setq telephone-line-primary-left-separator 'telephone-line-identity-left
        telephone-line-primary-right-separator 'telephone-line-identity-right
        telephone-line-secondary-left-separator 'telephone-line-nil
        telephone-line-secondary-right-separator 'telephone-line-nil)

  (custom-set-faces
   '(telephone-line-evil-normal ((t (:foreground "black" :background "lightgreen" :inherit telephone-line-evil))))
   '(telephone-line-evil-insert ((t (:foreground "black" :background "skyblue" :inherit telephone-line-evil))))
   '(telephone-line-evil-visual ((t (:foreground "black" :background "lightgoldenrod" :inherit telephone-line-evil))))
   '(telephone-line-evil-operator ((t (:foreground "black" :background "mediumpurple2" :inherit telephone-line-evil))))
   '(telephone-line-evil-motion ((t (:foreground "black" :background "burlywood2" :inherit telephone-line-evil))))
   '(telephone-line-evil-emacs ((t (:foreground "black" :background "cornflowerblue" :inherit telephone-line-evil)))))

  ;; Remove unwanted suffixes from major-mode
  (advice-add 'c-update-modeline :around #'ignore)  ; C++//l => C++
  (add-hook 'after-change-major-mode-hook
            (lambda () (if (listp mode-name) (setq mode-name (car mode-name)))))

  ;; Custom segments and mode-line configuration
  (telephone-line-defsegment telephone-line-dir ()
    (file-name-nondirectory (directory-file-name default-directory)))
  (telephone-line-defsegment telephone-line-visual-selected-char-count ()
    (if (evil-visual-state-p)
        (let ((beg (region-beginning))
              (end (region-end)))
          (format "%d chars  " (+ 1 (- end beg))))
      ""))
  (telephone-line-defsegment telephone-line-isearch-count ()
    ;; TODO: Seems like a bug, evil search forward always make count 0
    ;; (if (evil-normal-state-p)
    ;;     (format "[%s/%s] wow  " isearch-lazy-count-current isearch-lazy-count-total)
    "")

  (setq telephone-line-lhs
        '((evil   . (telephone-line-evil-tag-segment))
          (accent . (telephone-line-vc-segment))
          (nil    . (telephone-line-buffer-segment))))
  (setq telephone-line-rhs
        '((nil    . (telephone-line-dir telephone-line-misc-info-segment))
          (accent . (telephone-line-major-mode-segment))
          (evil   . (telephone-line-isearch-count telephone-line-visual-selected-char-count (telephone-line-airline-position-segment :args (3 2))))))

  (telephone-line-mode 1))

Org Export

Theme of the exported website when running org-html-export-to-html, this copies theme that is applied above.

(use-package hexrgb
  :ensure
  (hexrgb :host github :repo "emacsmirror/hexrgb" :main "hexrgb.el"))

(use-package org-html-themify
  :after hexrgb
  :ensure
  (org-html-themify
   :host github
   :repo "DogLooksGood/org-html-themify"
   :files ("*.el" "*.js" "*.css"))
  :hook (org-mode . org-html-themify-mode)
  :config
  (setq org-src-preserve-indentation nil
        org-edit-src-content-indentation 0))

Highlight Todo

(use-package hl-todo
  :hook ((prog-mode org-mode) . hl-todo-mode)
  :init
  (setq hl-todo-keyword-faces '(("HOLD" . "#cfdf30")
                                ("TODO" . "#ff9977")
                                ("NEXT" . "#b6a0ff")
                                ("PROG" . "#00d3d0")
                                ("FIXME" . "#ff9977")
                                ("DONE" . "#44bc44")
                                ("REVIEW" . "#6ae4b9")
                                ("DEPRECATED" . "#bfd9ff"))))

Miscellaneous

Notes

  • emoji-list is my emoji picker replacement 🙂

Below are the things that I like it this way! You may opt in or out to each on your own preferences.

Don’t reset the cursor to the middle when scrolling

(custom-set-variables
 '(scroll-conservatively 200)
 '(scroll-margin 3))

Highlight Trailing Whitespace

(setq-default show-trailing-whitespace t)
(add-hook 'prog-mode-hook
          (lambda () (font-lock-add-keywords nil '(("\\s-+$" 0 'trailing-whitespace)))))

Window Split Vertical-Horizontal Toggle

(defun my/window-split-toggle ()
  "Toggle between horizontal and vertical split with two windows."
  (interactive)
  (if (> (length (window-list)) 2)
      (error "Can't toggle with more than 2 windows!")
    (let ((func (if (window-full-height-p)
                    #'split-window-vertically
                  #'split-window-horizontally)))
      (delete-other-windows)
      (funcall func)
      (save-selected-window
        (other-window 1)
        (switch-to-buffer (other-buffer))))))
(leader-key
  "ts" #'my/window-split-toggle)  ; SPC-t-s

Change backup and lock file dump path

(defvar backupdir (concat user-emacs-directory "file-backups/"))
(defvar lockdir (concat user-emacs-directory "file-locks/"))
(make-directory backupdir t)
(make-directory lockdir t)

(setq auto-save-list-file-prefix (concat backupdir ".auto-saves-")
      auto-save-file-name-transforms `((".*" ,backupdir t))
      lock-file-name-transforms `((".*" ,lockdir t))
      backup-directory-alist `(("." . ,backupdir))
      tramp-auto-save-directory backupdir
      tramp-backup-directory-alist `((".*" . ,backupdir)))

open-at-point that opens respecting OS’s default app for the link

(defun open-at-point ()
  "Open URL at point."
  (interactive)
  (let* ((link-regexp "\\[\\[\\(.*?\\)\\]\\[.*?\\]\\]")
         (link (save-excursion
                 (when (re-search-backward link-regexp nil t)
                   (match-string 1)))))
    (message "%s" link)
    (cond
     ((string-equal system-type "windows-nt")
      (w32-shell-execute "open" (replace-regexp-in-string "/" "\\" link t t)))
     ((string-equal system-type "darwin")
      (shell-command (format "open \"%s\"" link)))
     ((string-equal system-type "gnu/linux")
      (let ((process-connection-type nil)) (start-process "" nil "xdg-open" link))))))

File closing prompt with evil-quit without saving won’t show “Type C-h for help.” in case wrong key is pressed.

Redefining the funcion at emacs/lisp/emacs-lisp/map-ynp.el, with some lines commented out.

(defun map-y-or-n-p (prompter actor list &optional help action-alist
                              no-cursor-in-echo-area)
  "Ask a boolean question per PROMPTER for each object in LIST, then call ACTOR.

      LIST is a list of objects, or a function of no arguments to return the next
      object; when it returns nil, the list of objects is considered exhausted.

      If PROMPTER is a string, it should be a format string to be used to format
      the question as \(format PROMPTER OBJECT).
      If PROMPTER is not a string, it should be a function of one argument, an
      object from LIST, which returns a string to be used as the question for
      that object.  If the function's return value is not a string, it may be
      nil to ignore the object, or non-nil to act on the object with ACTOR
      without asking the user.

      ACTOR is a function of one argument, an object from LIST,
      which gets called with each object for which the user answers `yes'
      to the question presented by PROMPTER.

      The user's answers to the questions may be one of the following:

       - y, Y, or SPC to act on that object;
       - n, N, or DEL to skip that object;
       - ! to act on all following objects;
       - ESC or q to exit (skip all following objects);
       - . (period) to act on the current object and then exit; or
       - \\[help-command] to get help.

      HELP provides information for displaying help when the user
      types \\[help-command].  If HELP is given, it should be a list of
      the form (OBJECT OBJECTS ACTION), where OBJECT is a string giving
      the singular noun describing an element of LIST; OBJECTS is the
      plural noun describing several elements of LIST, and ACTION is a
      transitive verb describing action by ACTOR on one or more elements
      of LIST.  If HELP is omitted or nil, it defaults
      to \(\"object\" \"objects\" \"act on\").

      If ACTION-ALIST is given, it is an alist specifying additional keys
      that will be accepted as an answer to the questions.  Each element
      of the alist has the form (KEY FUNCTION HELP), where KEY is a character;
      FUNCTION is a function of one argument (an object from LIST); and HELP
      is a string.  When the user presses KEY, FUNCTION is called; if it
      returns non-nil, the object is considered to have been \"acted upon\",
      and `map-y-or-n-p' proceeds to the next object from LIST.  If
      FUNCTION returns nil, the prompt is re-issued for the same object: this
      comes in handy if FUNCTION produces some display that will allow the
      user to make an intelligent decision whether the object in question
      should be acted upon.  If the user types \\[help-command], the string
      given by HELP is used to describe the effect of KEY.

      Optional argument NO-CURSOR-IN-ECHO-AREA, if non-nil, means not to set
      `cursor-in-echo-area' while prompting with the questions.

      This function uses `query-replace-map' to define the standard responses,
      but only some of the responses which `query-replace' understands
      are meaningful here, as described above.

      The function's value is the number of actions taken."
  (let* ((actions 0)
         (msg (current-message))
         user-keys mouse-event map prompt char elt def
         ;; Non-nil means we should use mouse menus to ask.
         use-menus
         delayed-switch-frame
         ;; Rebind other-window-scroll-buffer so that subfunctions can set
         ;; it temporarily, without risking affecting the caller.
         (other-window-scroll-buffer other-window-scroll-buffer)
         (next (if (functionp list)
                   (lambda () (setq elt (funcall list)))
                 (lambda () (when list
                              (setq elt (pop list))
                              t))))
         (try-again (lambda ()
                      (let ((x next))
                        (setq next (lambda () (setq next x) elt))))))
    (if (and (listp last-nonmenu-event)
             use-dialog-box)
        ;; Make a list describing a dialog box.
        (let ((objects (if help (capitalize (nth 1 help))))
              (action (if help (capitalize (nth 2 help)))))
          (setq map `(("Yes" . act) ("No" . skip)
                      ,@(mapcar (lambda (elt)
                                  (cons (with-syntax-table
                                            text-mode-syntax-table
                                          (capitalize (nth 2 elt)))
                                        (vector (nth 1 elt))))
                                action-alist)
                      (,(if help (concat action " This But No More")
                          "Do This But No More") . act-and-exit)
                      (,(if help (concat action " All " objects)
                          "Do All") . automatic)
                      ("No For All" . exit))
                use-menus t
                mouse-event last-nonmenu-event))
      (setq user-keys (if action-alist
                          (concat (mapconcat (lambda (elt)
                                               (key-description
                                                (vector (car elt))))
                                             action-alist ", ")
                                  " ")
                        "")
            ;; Make a map that defines each user key as a vector containing
            ;; its definition.
            map
            (let ((map (make-sparse-keymap)))
              (set-keymap-parent map query-replace-map)
              (dolist (elt action-alist)
                (define-key map (vector (car elt)) (vector (nth 1 elt))))
              map)))
    (unwind-protect
        (progn
          (if (stringp prompter)
              (setq prompter (let ((prompter prompter))
                               (lambda (object)
                                 (format prompter object)))))
          (while (funcall next)
            (setq prompt (funcall prompter elt))
            (cond ((stringp prompt)
                   ;; Prompt the user about this object.
                   (setq quit-flag nil)
                   (if use-menus
                       (setq def (or (x-popup-dialog (or mouse-event use-menus)
                                                     (cons prompt map))
                                     'quit))
                     ;; Prompt in the echo area.
                     (let ((cursor-in-echo-area (not no-cursor-in-echo-area)))
                       (message (apply 'propertize "%s(y, n, !, ., q, %sor %s) "
                                       minibuffer-prompt-properties)
                                prompt user-keys
                                (key-description (vector help-char)))
                       (if minibuffer-auto-raise
                           (raise-frame (window-frame (minibuffer-window))))
                       (while (progn
                                (setq char (read-event))
                                ;; If we get -1, from end of keyboard
                                ;; macro, try again.
                                (equal char -1)))
                       ;; Show the answer to the question.
                       (message "%s(y, n, !, ., q, %sor %s) %s"
                                prompt user-keys
                                (key-description (vector help-char))
                                (single-key-description char)))
                     (setq def (lookup-key map (vector char))))
                   (cond ((eq def 'exit)
                          (setq next (lambda () nil)))
                         ((eq def 'act)
                          ;; Act on the object.
                          (funcall actor elt)
                          (setq actions (1+ actions)))
                         ((eq def 'skip))
                         ;; Skip the object.

                         ((eq def 'act-and-exit)
                          ;; Act on the object and then exit.
                          (funcall actor elt)
                          (setq actions (1+ actions)
                                next (lambda () nil)))
                         ((eq def 'quit)
                          (setq quit-flag t)
                          (funcall try-again))
                         ((eq def 'automatic)
                          ;; Act on this and all following objects.
                          (if (funcall prompter elt)
                              (progn
                                (funcall actor elt)
                                (setq actions (1+ actions))))
                          (while (funcall next)
                            (if (funcall prompter elt)
                                (progn
                                  (funcall actor elt)
                                  (setq actions (1+ actions))))))
                         ((eq def 'help)
                          (with-help-window (help-buffer)
                            (princ
                             (let ((object  (or (nth 0 help) "object"))
                                   (objects (or (nth 1 help) "objects"))
                                   (action  (or (nth 2 help) "act on")))
                               (concat
                                (format-message
                                 (substitute-command-keys "\
      Type \\`SPC' or \\`y' to %s the current %s;
      \\`DEL' or \\`n' to skip the current %s;
      \\`RET' or \\`q' to skip the current and all remaining %s;
      \\`C-g' to quit (cancel the whole command);
      \\`!' to %s all remaining %s;\n")
                                 action object object objects action objects)
                                (mapconcat (lambda (elt)
                                             (format "%s to %s;\n"
                                                     (single-key-description
                                                      (nth 0 elt))
                                                     (nth 2 elt)))
                                           action-alist
                                           "")
                                (format
                                 "or . (period) to %s the current %s and exit."
                                 action object)))))

                          (funcall try-again))
                         ((and (symbolp def) (commandp def))
                          (call-interactively def)
                          ;; Regurgitated; try again.
                          (funcall try-again))
                         ((vectorp def)
                          ;; A user-defined key.
                          (if (funcall (aref def 0) elt) ;Call its function.
                              ;; The function has eaten this object.
                              (setq actions (1+ actions))
                            ;; Regurgitated; try again.
                            (funcall try-again)))
                         ((and (consp char)
                               (eq (car char) 'switch-frame))
                          ;; switch-frame event.  Put it off until we're done.
                          (setq delayed-switch-frame char)
                          (funcall try-again))))
                  ;; (t
                  ;; Random char.
                  ;; (message "Type %s for help."
                  ;;      (key-description (vector help-char)))
                  ;; (beep)
                  ;; (sit-for 1)
                  ;; (funcall try-again))))
                  (prompt
                   (funcall actor elt)
                   (setq actions (1+ actions))))))
      (if delayed-switch-frame
          (setq unread-command-events
                (cons delayed-switch-frame unread-command-events))))
    ;; Clear the last prompt from the minibuffer, and restore the
    ;; previous echo-area message, if any.
    (let ((message-log-max nil))
      (if msg
          (message "%s" msg)
        (message "")))
    ;; Return the number of actions that were taken.
    actions))

Resources References

These resources were very helpful in formation of my config. So a huge phrase of appreciation to all those people who were part of this.