Skip to content

Latest commit

 

History

History
6685 lines (5627 loc) · 198 KB

myinit.org

File metadata and controls

6685 lines (5627 loc) · 198 KB

My Emacs Mac set-up

repos

(setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3")

;; Byte compile directory everytime I start emacs
;;(byte-recompile-directory (expand-file-name "~/.emacs.d") 0)

;; it can also be done with `C-u 0 M-x byte-recompile-directory`
;; you can also use this from command line
;; emacs --batch --eval '(byte-recompile-directory "~/.emacs.d")'
;; emacs --batch --eval '(byte-compile-file "your-elisp-file.el")'

;; for latest org-mode and org-plus-contrib
(add-to-list 'package-archives '("org" . "https://orgmode.org/elpa/") t)

(setq load-prefer-newer t)
;; https://github.com/purcell/emacs.d/blob/master/lisp/init-elpa.el#L64
;; (setq package-enable-at-startup nil)
;;(package-initialize)
;;
;;(when (not package-archive-contents)
;;  (package-refresh-contents))
;;
;;(unless (package-installed-p 'use-package)
;;  (package-install 'use-package))
;;
;;;; Enable defer and ensure by default for use-package
;;(setq use-package-always-defer t
;;      use-package-always-ensure t)

Garbage collection

;; (let ((normal-gc-cons-threshold (* 128 1024 1024))
;;       (init-gc-cons-threshold (* 256 1024 1024)))
;;   (setq gc-cons-threshold init-gc-cons-threshold)
;;   (add-hook #'emacs-startup-hook
;;             (lambda () (setq gc-cons-threshold normal-gc-cons-threshold))))

;; (add-hook 'focus-out-hook #'garbage-collect)

;;; http://bling.github.io/blog/2016/01/18/why-are-you-changing-gc-cons-threshold/

(defun my-minibuffer-setup-hook ()
  (setq gc-cons-threshold most-positive-fixnum))

(defun my-minibuffer-exit-hook ()
  (setq gc-cons-threshold 800000))

(add-hook 'minibuffer-setup-hook #'my-minibuffer-setup-hook)
(add-hook 'minibuffer-exit-hook #'my-minibuffer-exit-hook)

;;(let ((gc-cons-threshold most-positive-fixnum))
;;  # existing init code
;;  )

;;https://github.com/seagle0128/.emacs.d/blob/24d17d3a36841c1c3c27c6ab26e4d3cb975095f3/init.el#L38
;; Speed up startup
(defvar default-file-name-handler-alist file-name-handler-alist)
(setq file-name-handler-alist nil)
(setq gc-cons-threshold 80000000)
(add-hook 'emacs-startup-hook
          (lambda ()
            "Restore defalut values after init."
            (setq file-name-handler-alist default-file-name-handler-alist)
            (setq gc-cons-threshold 4000000)
            (if (boundp 'after-focus-change-function)
                (add-function :after after-focus-change-function
                              (lambda ()
                                (unless (frame-focus-state)
                                  (garbage-collect))))
              (add-hook 'focus-out-hook 'garbage-collect))))


;;https://emacs.stackexchange.com/questions/34342/is-there-any-downside-to-setting-gc-cons-threshold-very-high-and-collecting-ga
;;(setq gc-cons-threshold (eval-when-compile (* 1024 1024 1024)))
;;(run-with-idle-timer 2 t (lambda () (garbage-collect)))

;;;;; Startup optimizations

;;;;;; Set garbage collection threshold

;; From https://www.reddit.com/r/emacs/comments/3kqt6e/2_easy_little_known_steps_to_speed_up_emacs_start/

(setq gc-cons-threshold-original gc-cons-threshold)
(setq gc-cons-threshold (eval-when-compile (* 1024 1024 1024)))
(run-with-idle-timer 2 t (lambda () (garbage-collect)))

;;;;;; Set file-name-handler-alist

;; Also from https://www.reddit.com/r/emacs/comments/3kqt6e/2_easy_little_known_steps_to_speed_up_emacs_start/

(setq file-name-handler-alist-original file-name-handler-alist)
(setq file-name-handler-alist nil)

;;;;;; Set deferred timer to reset them

(run-with-idle-timer
 5 nil
 (lambda ()
   (setq gc-cons-threshold gc-cons-threshold-original)
   (setq file-name-handler-alist file-name-handler-alist-original)
   (makunbound 'gc-cons-threshold-original)
   (makunbound 'file-name-handler-alist-original)
   (message "gc-cons-threshold and file-name-handler-alist restored")))

File-Exists Function

  (defun load-if-exists(f)
    "load the elip file only if it exits"
    (if (file-readable-p f)
        (load-file f)))
;; You can also use below
;;(when (file-readable-p f) (load-file p))

gnu-packagekeyring-update

(setq package-check-signature nil)
(use-package gnu-elpa-keyring-update
  :ensure t)

No-Littering

(use-package no-littering               ; Keep .emacs.d clean
  :ensure t
  :config (progn
            (require 'recentf)
            (add-to-list 'recentf-exclude no-littering-etc-directory)
            (add-to-list 'recentf-exclude no-littering-var-directory)
            (setq create-lockfiles nil
                  delete-old-versions t
                  kept-new-versions 6
                  kept-old-versions 2
                  version-control t)))

tuning start-up

(use-package term
  :ensure nil
  :defer t)

(use-package xterm-color
  :ensure nil
  :defer t)

(use-package ehelp
  :ensure nil
  :defer t)

interface tweaks

;; Core settings
;; UTF-8 please
(set-charset-priority 'unicode)
(setq locale-coding-system   'utf-8)   ; pretty
(set-terminal-coding-system  'utf-8)   ; pretty
(set-keyboard-coding-system  'utf-8)   ; pretty
(set-selection-coding-system 'utf-8)   ; please
(prefer-coding-system        'utf-8)   ; with sugar on top
(setq default-process-coding-system '(utf-8-unix . utf-8-unix))

(setq inhibit-startup-message t)
(add-to-list 'default-frame-alist '(fullscreen . maximized))
(fset 'yes-or-no-p 'y-or-n-p)

(global-set-key (kbd "<f5>") 'revert-buffer)
;;(global-set-key (kbd "C-a") 'move-beginning-of-line)
;;(global-set-key (kbd "C-e") 'move-end-of-line)

;; Commenting this due to excess battery usage
;;(global-auto-revert-mode 1) ;; you might not want this as it use huge amout of battery
;;(setq auto-revert-verbose nil) ;; or thiS
;; using swiper so ido no longer needed
(tool-bar-mode -1)
(winner-mode 1)
(superword-mode 1)

;;https://www.masteringemacs.org/article/improving-performance-emacs-display-engine
(setq redisplay-dont-pause t)
;;https://www.masteringemacs.org/article/making-deleted-files-trash-can
(setq delete-by-moving-to-trash t)
;;(require 'ox-odt (setq org-odt-preferred-output-format "docx"))
;;Added this to disable linum in pdf-tools
(add-hook 'pdf-view-mode-hook (lambda() (linum-relative-mode -1)))
;;to remember window config
;;(setq ido-enable-flex-matching t)
;;(setq ido-everywhere t)
;;(ido-mode 1)

(add-to-list 'load-path "~/.emacs.d/custom-el-scripts/font-lock+.el")
(add-to-list 'load-path "~/.emacs.d/custom-el-scripts/icons-in-terminal.el")

(add-to-list 'default-frame-alist '(font . "Fira Code-17"))
;;(windmove-default-keybindings) ;;uses shift + arrow keys to move around the windows.
;; For fira code - https://github.com/tonsky/FiraCode/wiki/Emacs-instructions#using-composition-mode-in-emacs-mac-port
;;(mac-auto-operator-composition-mode)
;;(defalias 'list-buffers 'ibuffer) ; make ibuffer default

(defun fira-code-mode--make-alist (list)
  "Generate prettify-symbols alist from LIST."
  (let ((idx -1))
    (mapcar
     (lambda (s)
       (setq idx (1+ idx))
       (let* ((code (+ #Xe100 idx))
              (width (string-width s))
              (prefix ())
              (suffix '(?\s (Br . Br)))
              (n 1))
         (while (< n width)
           (setq prefix (append prefix '(?\s (Br . Bl))))
           (setq n (1+ n)))
         (cons s (append prefix suffix (list (decode-char 'ucs code))))))
     list)))

(defconst fira-code-mode--ligatures
  '("www" "**" "***" "**/" "*>" "*/" "\\\\" "\\\\\\"
    "{-" "[]" "::" ":::" ":=" "!!" "!=" "!==" "-}"
    "--" "---" "-->" "->" "->>" "-<" "-<<" "-~"
    "#{" "#[" "##" "###" "####" "#(" "#?" "#_" "#_("
    ".-" ".=" ".." "..<" "..." "?=" "??" ";;" "/*"
    "/**" "/=" "/==" "/>" "//" "///" "&&" "||" "||="
    "|=" "|>" "^=" "$>" "++" "+++" "+>" "=:=" "=="
    "===" "==>" "=>" "=>>" "<=" "=<<" "=/=" ">-" ">="
    ">=>" ">>" ">>-" ">>=" ">>>" "<*" "<*>" "<|" "<|>"
    "<$" "<$>" "<!--" "<-" "<--" "<->" "<+" "<+>" "<="
    "<==" "<=>" "<=<" "<>" "<<" "<<-" "<<=" "<<<" "<~"
    "<~~" "</" "</>" "~@" "~-" "~=" "~>" "~~" "~~>" "%%"
    "x" ":" "+" "+" "*"))

(defvar fira-code-mode--old-prettify-alist)

(defun fira-code-mode--enable ()
  "Enable Fira Code ligatures in current buffer."
  (setq-local fira-code-mode--old-prettify-alist prettify-symbols-alist)
  (setq-local prettify-symbols-alist (append (fira-code-mode--make-alist fira-code-mode--ligatures) fira-code-mode--old-prettify-alist))
  (prettify-symbols-mode t))

(defun fira-code-mode--disable ()
  "Disable Fira Code ligatures in current buffer."
  (setq-local prettify-symbols-alist fira-code-mode--old-prettify-alist)
  (prettify-symbols-mode -1))

(define-minor-mode fira-code-mode
  "Fira Code ligatures minor mode"
  :lighter " Fira Code"
  (setq-local prettify-symbols-unprettify-at-point 'right-edge)
  (if fira-code-mode
      (fira-code-mode--enable)
    (fira-code-mode--disable)))

(defun fira-code-mode--setup ()
  "Setup Fira Code Symbols"
  (set-fontset-font t '(#Xe100 . #Xe16f) "Fira Code Symbol"))

(provide 'fira-code-mode)

(defalias 'list-buffers 'ibuffer-other-window) ; make ibuffer default

;; Save whatever’s in the current (system) clipboard before
;; replacing it with the Emacs’ text.
;; https://github.com/dakrone/eos/blob/master/eos.org
;; Kill ring
(setq kill-ring-max 200
      kill-do-not-save-duplicates t)
(setq save-interprogram-paste-before-kill t)
(column-number-mode t)
(size-indication-mode t)
(setq tramp-default-method "ssh")
;;(setq tramp-auto-save-directory temporary-file-directory) ;; handled by no-littering package

;; to speed up tramp
(setq remote-file-name-inhibit-cache nil)
(setq vc-ignore-dir-regexp
      (format "%s\\|%s"
              vc-ignore-dir-regexp
              tramp-file-name-regexp))
(setq tramp-verbose 1)

;;https://emacs.stackexchange.com/questions/17170/how-to-auto-copy-when-a-region-is-selected
;;When emacs 25.1 is released (supposedly the next stable version after 24.5),
;;the x-select-enable-primary variable name will be deprecated and
;;select-enable-primary must be used instead (removal of that x- prefix).
;;Similarly x-select-enable-clipboard will be deprecated in favor of select-enable-clipboard
(setq select-enable-primary nil
      select-enable-clipboard t
      select-active-regions t)

;;Keyboard tweaks
;;(setq mac-command-modifier 'meta) ; make cmd key do Meta
;;(setq mac-option-modifier 'super) ; make opt key do Super
;;(setq mac-control-modifier 'control) ; make Control key do Control
(setq ns-function-modifier 'hyper)  ; make Fn key do Hyper
(setq user-full-name "Chetan Koneru")

;; Default to 16MB for garbage collection
(defvar mu-gc-cons-threshold 16777216)

;; Temporary value for garbage collection is 512MB
(defvar mu-gc-cons-upper-limit 536870912)

;;Ediff mode is a UNIX patching tool and my version controlling package uses this to help resolve merge conflicts and having some better defaults will be useful for this.
(setq ediff-window-setup-function 'ediff-setup-windows-plain
      ediff-split-window-function 'split-window-horizontally)

;;`'subword-mode`' is a built-in mode that helps moving over camelCase words correctly.
(setq sentence-end-double-space nil)

;;Recneter screen
(setq recenter-positions '(top middle bottom))

;;Better wild cards in search
;;The built-in incremental search is pretty good but the most common regex I type is .* which stands for anything. This makes sure space between words acts the same way. It’s much better for me to use it now.
(setq search-whitespace-regexp ".*?")

;;Persistent history
;; commented due to exit errors
;;(savehist-mode)
;;(setq savehist-file "~/.emacs.d/var/savehist") ;; handled by no-littering package
(savehist-mode 1)
(setq savehist-autosave-interval (* 60 100))
(setq-default history-length 100)
(setq history-delete-duplicates t)
(setq savehist-save-minibuffer-history 1)
(setq savehist-additional-variables
      '(kill-ring
        search-ring
        regexp-search-ring))
(savehist-mode t)

;; Added this to build pdf tools
(setenv "PKG_CONFIG_PATH" "/usr/local/lib/pkgconfig:/usr/local/Cellar/libffi/3.2.1/lib/pkgconfig")

;;async, s, dash, and cl-lib are libraries for asynchronous processing, string manipulation, list manipulation and backward compatibility respectively.
(use-package async
  :ensure t
  :commands (async-start))

(use-package cl-lib
  :ensure t)

(use-package dash
  :ensure t)

(use-package s
  :ensure t)

;;Restart emacs from emacs
(use-package restart-emacs
  :ensure t
  :config (defalias 'emacs-restart #'restart-emacs)
  :bind* (("C-x M-c" . restart-emacs)))

;; Open Large file
(use-package vlf
  :ensure t
  :config
  (require 'vlf-setup))

;; Delete trailing-whitespace
(add-hook 'before-save-hook 'delete-trailing-whitespace)

;;saves the buffers whenever emacs loses the window focus.
(add-hook 'focus-out-hook (lambda () (save-some-buffers t)))

;;(setq desktop-path '("~/.emacs.d/var/desktop-mode-cache/"));; handled by no-littering package
(desktop-save-mode 1)

;;(setq org-ellipsis "↴") ;;▼, ↴, ⬎, ⤷,⤵
(setq org-ellipsis "") ;;▼, ↴, ⬎, ⤷,⤵

(setq desktop-restore-eager 10)

;;cursor color to white
(set-cursor-color "#ffffff")

;;Commented as not using ellocate
;; see -https://github.com/hlissner/doom-emacs/issues/1407#issuecomment-491931901
;;(setq max-specpdl-size 1300000)
;;(setq max-lisp-eval-depth 100000)

(setq-default save-place  t)
;;(setq save-place-file "~/.emacs.d/var/saveplace");; handled by no-littering package

;;Text selected with the mouse is automatically copied to clipboard.
(setq mouse-drag-copy-region t)

;; C-n, next line, inserts newlines when at the end of the buffer
(setq next-line-add-newlines t)

;; Adding indent hook
(add-hook 'org-mode-hook 'org-indent-mode)

(use-package server
  :no-require t
  :hook (after-init . server-start))

(setq require-final-newline t)

(global-visual-line-mode 1)

Theme

;;(load-theme 'misterioso t)
;;
;;(use-package spacemacs-theme
;;  :ensure t
;;  :defer
;;  ;;:init (load-theme 'spacemacs-dark t)
;;  )
;;
;;(use-package monokai-theme
;;  :ensure t
;;  ;;:init (load-theme 'monokai t)
;;  )
;;
;;(use-package zenburn-theme
;;  :ensure t
;;  ;;:init (load-theme 'zenburn t)
;;  )
;;
;;(use-package dracula-theme
;;  :ensure t
;;  ;;:init (load-theme 'dracula t)
;;  )
;;
;;(use-package color-theme-modern
;;  :ensure t)
;;
;;(use-package base16-theme
;;  :ensure t
;;  :init (load-theme 'base16-spacemacs t)
;;  )
;;
;;(use-package base16-theme
;;  :ensure t
;;  ;;:init (load-theme 'base16-monokai t)
;;  )
;;
(use-package moe-theme
  :ensure t
  :config
  ;; (Available colors: blue, orange, green ,magenta, yellow, purple, red, cyan, w/b.)
  ;; Choose a color for mode-line.(Default: blue)
  ;;(moe-theme-set-color 'cyan)
  (moe-theme-set-color 'w/b)
  ;; Resize titles (optional).
  (setq moe-theme-resize-markdown-title '(1.5 1.4 1.3 1.2 1.0 1.0))
  (setq moe-theme-resize-org-title '(1.5 1.4 1.3 1.2 1.1 1.0 1.0 1.0 1.0))
  (setq moe-theme-resize-rst-title '(1.5 1.4 1.3 1.2 1.1 1.0))


  ;; Show highlighted buffer-id as decoration. (Default: nil)
  (setq moe-theme-highlight-buffer-id t)
  :init (load-theme 'moe-dark t)
  )

;;(use-package alect-themes
;;  :ensure t)
;;
;;(use-package zerodark-theme
;;  :ensure t)
;;
;;(use-package faff-theme
;;:ensure t)
;;
;;(use-package poet-theme
;;  :ensure t)
;;
;;(use-package tao-theme
;;:ensure t)
;;
;;(use-package doom-themes
;;  :config
;;  ;; Global settings (defaults)
;;  (setq doom-themes-enable-bold t    ; if nil, bold is universally disabled
;;        doom-themes-enable-italic t) ; if nil, italics is universally disabled
;;  (load-theme 'doom-one)

;;  ;; Enable flashing mode-line on errors
;;  (doom-themes-visual-bell-config)

;;  ;; Enable custom neotree theme (all-the-icons must be installed!)
;;  ;;(doom-themes-neotree-config)
;;  ;; or for treemacs users
;;  (setq doom-themes-treemacs-theme "doom-colors") ; use the colorful treemacs theme
;;  (doom-themes-treemacs-config)

;;  ;; Corrects (and improves) org-mode's native fontification.
;;  (doom-themes-org-config))
;;
;;(use-package color-theme-sanityinc-tomorrow
;;  :ensure t
;;  ;;:init (load-theme 'sanityinc-tomorrow-blue)
;;  )
;;
;;(use-package apropospriate-theme
;;:ensure t
    ;;;; :init
    ;;;; (load-theme 'apropospriate-dark t)
    ;;;; ;; or
    ;;;; (load-theme 'apropospriate-light t)
;;)

;;(use-package chocolate-theme
;;  :ensure t
;;  :config
;;  (load-theme 'chocolate t)
;;  )

;;(use-package sublime-themes
;;  :ensure t)
;;(load-theme 'junio t)

Straight

 (setq straight-recipes-gnu-elpa-use-mirror t
	straight-repository-branch           "develop"
	straight-check-for-modifications     'live
	straight-vc-git-default-clone-depth  1)

 (defvar bootstrap-version)

 (let ((bootstrap-file
	 (expand-file-name "straight/repos/straight.el/bootstrap.el" user-emacs-directory))
	(bootstrap-version 5))
   (unless (file-exists-p bootstrap-file)
     (with-current-buffer
	  (url-retrieve-synchronously
	   "https://raw.githubusercontent.com/raxod502/straight.el/develop/install.el"
	   'silent 'inhibit-cookies)
	(goto-char (point-max))
	(eval-print-last-sexp)))
   (load bootstrap-file nil 'nomessage))

 ;;;;  Effectively replace use-package with straight-use-package
 ;;; https://github.com/raxod502/straight.el/blob/develop/README.md#integration-with-use-package
 (straight-use-package 'use-package)
 ;;(setq straight-use-package-by-default t)

Org

;; Enable Org mode
(use-package org
  :ensure org-plus-contrib
  )

(require 'org-tempo)

(setq org-startup-with-inline-images t)

(define-key org-mode-map (kbd "C-x n w") 'widen)

(add-hook 'org-mode-hook (lambda ()
                           "Beautify Org Checkbox Symbol"
                           (push '("[ ]" .  "") prettify-symbols-alist)
                           (push '("[X]" . "" ) prettify-symbols-alist)
                           (push '("[-]" . "" ) prettify-symbols-alist)
                           (push '("#+BEGIN_SRC" . "" ) prettify-symbols-alist)
                           (push '("#+END_SRC" . "" ) prettify-symbols-alist)
                           (push '("#+BEGIN_EXAMPLE" . "" ) prettify-symbols-alist)
                           (push '("#+END_EXAMPLE" . "" ) prettify-symbols-alist)
                           (push '("#+BEGIN_QUOTE" . "" ) prettify-symbols-alist)
                           (push '("#+END_QUOTE" . "" ) prettify-symbols-alist)
                           (push '("#+begin_quote" . "" ) prettify-symbols-alist)
                           (push '("#+end_quote" . "" ) prettify-symbols-alist)
                           (push '("#+begin_example" . "" ) prettify-symbols-alist)
                           (push '("#+end_example" . "" ) prettify-symbols-alist)
                           (push '("#+begin_src" . "" ) prettify-symbols-alist)
                           (push '("#+end_src" . "" ) prettify-symbols-alist)
                           (prettify-symbols-mode)))

Genearl

(use-package general
  :ensure t
  ;;:straight t
  :init
  (defalias 'gsetq #'general-setq)
  (defalias 'gsetq-local #'general-setq-local)
  (defalias 'gsetq-default #'general-setq-default))

(require 'general)
(general-evil-setup t)

;; use `SPC' as leader key
(general-create-definer my-spc-leader-def
  :prefix "SPC"
  :states '(normal visual))

(my-spc-leader-def
  "bl" 'ibuffer
  "bb" 'counsel-switch-buffer
  "bs" 'save-buffer
  "bk" 'my/kill-this-buffer
  "ff" 'counsel-find-file
  "fz" 'counsel-fzf
  "fp" 'counsel-projectile
  "fd" 'counsel-fd
  "dd" 'dired
  "uu" 'undo-tree
  "wo" 'other-window
  "w0" 'delete-window
  "w1" 'delete-other-windows
  "w2" 'my/split-below-and-move
  "w3" 'my/split-right-and-move
  "ww1" 'eyebrowse-switch-to-window-config-0
  "ww1" 'eyebrowse-switch-to-window-config-1
  "ww2" 'eyebrowse-switch-to-window-config-2
  "ww3" 'eyebrowse-switch-to-window-config-3
  "ww4" 'eyebrowse-switch-to-window-config-4
  "ww5" 'eyebrowse-switch-to-window-config-5
  "ww6" 'eyebrowse-switch-to-window-config-6
  "ww7" 'eyebrowse-switch-to-window-config-7
  "ww8" 'eyebrowse-switch-to-window-config-8
  "ww9" 'eyebrowse-switch-to-window-config-9
  "5o" 'other-frame
  "5f" 'find-file-other-frame
  "5b" 'switch-to-buffer-other-frame
  "50" 'delete-frame
  "51" 'delete-other-frame
  "5d" 'dired-other-frame
  "gg" 'magit-status
  "zz" 'zop-to-char
  "za" 'zop-up-to-char
  "mc" 'my/open-config
  "tt" 'treemacs
  "rr" 'quickrun
  "rc" 'quickrun-compile-only
  "SPC" 'counsel-M-x)

Hydra

(use-package hydra
  :defer t
  :ensure hydra
  :init
  (global-set-key
   (kbd "C-c h h t")
   (defhydra toggle (:color blue)
     "toggle"
     ("a" abbrev-mode "abbrev")
     ("s" flyspell-mode "flyspell")
     ("d" toggle-debug-on-error "debug")
     ("c" fci-mode "fCi")
     ("f" auto-fill-mode "fill")
     ("t" toggle-truncate-lines "truncate")
     ("w" whitespace-mode "whitespace")
     ("q" nil "cancel")))
  (global-set-key
   (kbd "C-c h h g")
   (defhydra gotoline
     ( :pre (linum-mode 1)
            :post (linum-mode -1))
     "goto"
     ("t" (lambda () (interactive)(move-to-window-line-top-bottom 0)) "top")
     ("b" (lambda () (interactive)(move-to-window-line-top-bottom -1)) "bottom")
     ("m" (lambda () (interactive)(move-to-window-line-top-bottom)) "middle")
     ("e" (lambda () (interactive)(end-of-buffer)) "end")
     ("c" recenter-top-bottom "recenter")
     ("n" next-line "down")
     ("p" (lambda () (interactive) (forward-line -1))  "up")
     ("g" goto-line "goto-line")
     ))
  (global-set-key
   (kbd "C-c h o t")
   (defhydra hydra-global-org (:color blue)
     "Org"
     ("t" org-timer-start "Start Timer")
     ("s" org-timer-stop "Stop Timer")
     ("r" org-timer-set-timer "Set Timer") ; This one requires you be in an orgmode doc, as it sets the timer for the header
     ("p" org-timer "Print Timer") ; output timer value to buffer
     ("w" (org-clock-in '(4)) "Clock-In") ; used with (org-clock-persistence-insinuate) (setq org-clock-persist t)
     ("o" org-clock-out "Clock-Out") ; you might also want (setq org-log-note-clock-out t)
     ("j" org-clock-goto "Clock Goto") ; global visit the clocked task
     ("c" org-capture "Capture") ; Don't forget to define the captures you want http://orgmode.org/manual/Capture.html
     ("l" (or )rg-capture-goto-last-stored "Last Capture"))

   ))

(use-package major-mode-hydra
  :ensure t
  :bind
  ("M-SPC" . major-mode-hydra))
(require 'major-mode-hydra)

All the Icons

(use-package all-the-icons
  :ensure t
  :defer 0.5)

(use-package all-the-icons-ivy
  :ensure t
  :after (all-the-icons ivy)
  :custom (all-the-icons-ivy-buffer-commands '(ivy-switch-buffer-other-window ivy-switch-buffer))
  :config
  (add-to-list 'all-the-icons-ivy-file-commands 'counsel-dired-jump)
  (add-to-list 'all-the-icons-ivy-file-commands 'counsel-find-library)
  (all-the-icons-ivy-setup))


(use-package all-the-icons-dired
  :ensure t
  )

;; TODO - Still did not upstreamed to Melpa. Try again in few days
(use-package all-the-icons-ibuffer
  :ensure t
  :init (all-the-icons-ibuffer-mode 1))

(use-package all-the-icons-ivy-rich
  :ensure t
  :init (all-the-icons-ivy-rich-mode 1))

(add-hook 'dired-mode-hook 'all-the-icons-dired-mode)

PosFrame

(use-package posframe
  :ensure t)

Quelpa

(package-initialize)
(if (require 'quelpa nil t)
    (quelpa-self-upgrade)
  (with-temp-buffer
    (url-insert-file-contents "https://framagit.org/steckerhalter/quelpa/raw/master/bootstrap.el")
    (eval-buffer)))

;;(use-package quelpa-use-package
;;  :ensure t
;;  :init
;;  (setq quelpa-update-melpa-p nil))
;;(setq use-package-ensure-function 'quelpa)
(quelpa
 '(quelpa-use-package
   :fetcher git
   :url "https://github.com/quelpa/quelpa-use-package.git"))
(require 'quelpa-use-package)
;;(setq use-package-ensure-function 'quelpa)

Which key

(use-package which-key
  :ensure t
  :config
  (which-key-mode))

Evil Mode For Vi

(setq evil-disable-insert-state-bindings t) ;;full blown emacs in insert mode
(add-to-list 'load-path "~/.emacs.d/custom-el-scripts/evil")
(setq evil-want-integration t) ;; This is optional since it's already set to t by default.
(setq evil-want-keybinding nil)

;;(setq evil-disable-insert-state-bindings t) ;;full blown emacs in insert mode
(require 'evil)
(evil-mode 1)

(use-package evil-matchit             ; vi-% for more than {[""]}
  :ensure t
  :init
  (global-evil-matchit-mode 1))

(use-package evil-surround            ; Exactly like tpopes vim-surround
  :ensure t
  :init
  (global-evil-surround-mode))

;; Treat underscores '_' part of the words
(with-eval-after-load 'evil
  (defalias #'forward-evil-word #'forward-evil-symbol))

(evil-set-initial-state 'ibuffer-mode 'emacs)
(evil-set-initial-state 'bookmark-bmenu-mode 'emacs)
(evil-set-initial-state 'dired-mode 'emacs)
(evil-set-initial-state 'wgrep-change-to-wgrep-mode 'emacs)

Org-sticky-header

(use-package org-sticky-header
  :defer t
  :hook (org-mode . org-sticky-header-mode)
  :config
  (setq-default
   org-sticky-header-full-path 'full
   ;; Child and parent headings are seperated by a /.
   org-sticky-header-outline-path-separator " / "))

Org Bullets

(use-package org-bullets
  :ensure t
  :after org
  :hook (org-mode . org-bullets-mode)
  :config
  (setq org-bullets-bullet-list '("" "" "" "" "" "" "" "~"))
  (add-hook 'org-mode-hook (lambda () (org-bullets-mode 1)))
  )

;;(require 'org-bullets)
;;(setq org-bullets-bullet-list '("☯" "◉" "☢" "❀" "○" "✸" "✿" "~"))
;;(add-hook 'org-mode-hook (lambda () (org-bullets-mode 1)))

Org-Download

;;(use-package org-download
;;  :ensure t
;;  :after org
;;  :config
;;  (add-hook 'dired-mode-hook 'org-download-enable))

(use-package org-download
  :defer 3
  :ensure t
  :config
  (require 'org-download)
  ;; Drag and drop to Dired
  (add-hook 'dired-mode-hook 'org-download-enable)
  (setq org-download-method 'directory)
  (setq-default org-download-image-dir "./img")
  (setq org-download-screenshot-method "screencapture –I %s")
  (setq org-download-screenshot-file "./img/tmp.png")
  )

Relative Line number

;; Built in line numbers now, yay!
;;(global-display-line-numbers-mode 'relative)
;;(setq-default display-line-numbers 'relative)

(use-package linum-relative
  :ensure t
  :config
  (linum-relative-global-mode 1))

(linum-relative-global-mode 1)

;; Use `display-line-number-mode' as linum-mode's backend for smooth performance
(setq linum-relative-backend 'display-line-numbers-mode)

Format-all

(use-package format-all
  :ensure t)

Ace Window

Swap and delete window

You can swap windows by calling `ace-window` with a prefix argument <kbd>C-u</kbd>. You can delete the selected window by calling `ace-window` with a double prefix argument, i.e. <kbd>C-u C-u</kbd>.

Change the action midway

You can also start by calling `ace-window` and then decide to switch the action to `delete` or `swap` etc. By default the bindings are:

kbdcommand
xdelete window
mswap windows
Mmove window
ccopy window
jselect buffer
nselect the previous window
uselect buffer in the other window
csplit window fairly, either vertically or horizontally
vsplit window vertically
bsplit window horizontally
omaximize current window
?show these command bindings
(use-package ace-window
  :ensure t
  :custom
  (aw-keys '(?a ?s ?d ?f ?g ?h ?p ?k ?l))
  ;;(aw-dispatch-always t)
  (aw-dispatch-alist
   '((?s aw-swap-window "Swap Windows")
     (?2 aw-split-window-vert "Split Window Vertically")
     (?3 aw-split-window-horz "Split Window Horizontally")
     (?? aw-show-dispatch-help)))
  (aw-display-mode-overlay t)
  :init
  (progn
    (global-set-key [remap other-window] 'ace-window)
    (custom-set-faces
     '(aw-leading-char-face
       ((t (:inherit ace-jump-face-foreground :height 3.0)))))
    )
  :config
  (defun my-scroll-other-window()
    (interactive)
    (scroll-other-window 1))
  (defun my-scroll-other-window-down ()
    (interactive)
    (scroll-other-window-down 1))
  (when (package-installed-p 'hydra)
    (defhydra hydra-window-size (:color red)
      "Windows size"
      ("h" shrink-window-horizontally "shrink horizontal")
      ("j" shrink-window "shrink vertical")
      ("k" enlarge-window "enlarge vertical")
      ("l" enlarge-window-horizontally "enlarge horizontal"))
    (defhydra hydra-window-frame (:color red)
      "Frame"
      ("f" make-frame "new frame")
      ("x" delete-frame "delete frame"))
    (defhydra hydra-window-scroll (:color red)
      "Scroll other window"
      ("n" my-scroll-other-window "scroll")
      ("p" my-scroll-other-window-down "scroll down"))
    (add-to-list 'aw-dispatch-alist '(?w hydra-window-size/body) t)
    (add-to-list 'aw-dispatch-alist '(?S hydra-window-scroll/body) t)
    (add-to-list 'aw-dispatch-alist '(?\; hydra-window-frame/body) t))
  (ace-window-display-mode -1)
  )

Counsel/Ivy/Swiper

;; it looks like counsel is a requirement for swiper
(use-package counsel
  :ensure t
  :bind
  (("M-y" . counsel-yank-pop)
   :map ivy-minibuffer-map
   ("M-y" . ivy-next-line))
  )

(use-package smex
  :ensure t
  :init (smex-initialize))

(use-package historian
  :ensure t)
(use-package ivy-historian
  :ensure t)

(use-package ivy
  :ensure t
  :init
  (ivy-mode +1)
  (historian-mode +1)
  :diminish (ivy-mode)
  :bind (("C-x b" . ivy-switch-buffer))
  :custom
  (ivy-use-selectable-prompt t)
  :config
  ;;(ivy-mode 1)
  (ivy-historian-mode +1)
  (setq ivy-use-virtual-buffers t)
  (setq ivy-display-style 'fancy))

(use-package ivy-hydra
  :ensure t)

;;(load-if-exists "~/.emacs.d/custom-el-scripts/init-ivy-rich.el")
(load-if-exists "~/.emacs.d/custom-el-scripts/counsel-fd.el")

(use-package ivy-rich
  :ensure t
  :custom
  (ivy-rich-path-style 'abbreviate)
  :config
  (setcdr (assq t ivy-format-functions-alist)
          #'ivy-format-function-line)
  (ivy-rich-mode 1))

;; Enhance fuzzy matching
(use-package flx
  :ensure t)

;; Enhance M-x
(use-package amx
  :ensure t)

;; Ivy integration for Projectile
(use-package counsel-projectile
  :ensure t
  :config (counsel-projectile-mode 1))

;; Integration with `projectile'
(with-eval-after-load 'projectile
  (setq projectile-completion-system 'ivy))

;; Integration with `magit'
(with-eval-after-load 'magit
  (setq magit-completing-read-function 'ivy-completing-read))

(use-package swiper
  :ensure t
  :commands (ivy-dispatching-done)
  ;;This also can be used to bind keys
  ;;:bind (("C-s" . swiper)
  ;;	 ("C-r" . swiper)
  ;;	 ("C-c C-r" . ivy-resume)
  ;;	 ("M-x" . counsel-M-x)
  ;;	 ("C-x C-f" . counsel-find-file))
  :config
  (progn
    (ivy-mode 1)
    (setq ivy-use-virtual-buffers t)
    (global-set-key "\C-s" 'swiper)
    (global-set-key (kbd "C-c C-r") 'ivy-resume)
    ;;(global-set-key (kbd "<f6>") 'ivy-resume)
    (global-set-key (kbd "M-x") 'counsel-M-x)
    (global-set-key (kbd "C-x C-f") 'counsel-find-file)
    (global-set-key (kbd "<f1> f") 'counsel-describe-function)
    (global-set-key (kbd "<f1> v") 'counsel-describe-variable)
    (global-set-key (kbd "<f1> l") 'counsel-load-library)
    (global-set-key (kbd "<f2> i") 'counsel-info-lookup-symbol)
    (global-set-key (kbd "<f2> u") 'counsel-unicode-char)
    (global-set-key (kbd "C-c g") 'counsel-git)
    (global-set-key (kbd "C-c j") 'counsel-git-grep)
    (global-set-key (kbd "C-c k") 'counsel-ag)
    (global-set-key (kbd "C-x l") 'counsel-locate)
    (global-set-key (kbd "C-S-p") 'swiper-thing-at-point)
    (define-key read-expression-map (kbd "C-r") 'counsel-expression-history)
    ))

;; Define actions in the minibuffer keymap
;; Mimicking the behavior of "C-c i" in helm-mode, but with mode flexibility
;;(define-key ivy-minibuffer-map (kbd "C-c i") 'ivy-dispatching-done)
(define-key ivy-minibuffer-map (kbd "M-s-ø") 'ivy-dispatching-done)

(use-package prescient
  :ensure t
  :config (prescient-persist-mode))

(use-package ivy-prescient
  :ensure t
  :after (prescient ivy)
  :custom
  (ivy-prescient-sort-commands
   '(:not swiper ivy-switch-buffer counsel-switch-buffer))
  (ivy-prescient-retain-classic-highlighting t)
  (ivy-prescient-enable-filtering t)
  (ivy-prescient-enable-sorting t)
  :init (ivy-prescient-mode 1))

(setq counsel-grep-base-command
      "rg -i -M 120 --no-heading --line-number --color never '%s' %s")

(setq counsel-rg-base-command
      "rg -SHni -M 120 --no-heading --color never --no-follow --hidden %s")
;; https://oremacs.com/2016/01/06/ivy-flx/
;;(setq ivy-re-builders-alist
;;      '((ivy-switch-buffer . ivy--regex-plus)
;;        (t . ivy--regex-fuzzy)))

(setq counsel-fzf-cmd "fd -HLia -t f --color never --exclude .git | fzf -f \"%s\"")

(defun my/counsel-fzf-rg-files (&optional input dir)
  "Run `fzf' in tandem with `ripgrep' to find files in the
    present directory.  If invoked from inside a version-controlled
    repository, then the corresponding root is used instead."
  (interactive)
  (let* ((process-environment
          (cons (concat "FZF_DEFAULT_COMMAND=rg -Sn --color never --files --no-follow --hidden")
                process-environment))
         (vc (vc-root-dir)))
    (if dir
        (counsel-fzf input dir)
      (if (eq vc nil)
          (counsel-fzf input default-directory)
        (counsel-fzf input vc)))))

(defun my/counsel-fzf-dir (arg)
  "Specify root directory for `counsel-fzf'."
  (my/counsel-fzf-rg-files ivy-text
                           (read-directory-name
                            (concat (car (split-string counsel-fzf-cmd))
                                    " in directory: "))))

(defun my/counsel-rg-dir (arg)
  "Specify root directory for `counsel-rg'."
  (let ((current-prefix-arg '(4)))
    (counsel-rg ivy-text nil "")))

;; TODO generalise for all relevant file/buffer counsel-*?
(defun my/counsel-fzf-ace-window (arg)
  "Use `ace-window' on `my/counsel-fzf-rg-files' candidate."
  (ace-window t)
  (let ((default-directory (if (eq (vc-root-dir) nil)
                               counsel--fzf-dir
                             (vc-root-dir))))
    (if (> (length (aw-window-list)) 1)
        (progn
          (find-file arg))
      (find-file-other-window arg))
    (balance-windows (current-buffer))))

(defun my/counsel-ff-ace-window (arg)
  "Use `ace-window' on `my/counsel-find-files' candidate."
  (ace-window t)
  (if (> (length (aw-window-list)) 1)
      (progn
        (find-file arg))
    (find-file-other-window arg))
  (balance-windows (current-buffer)))

;; Pass functions as appropriate Ivy actions (accessed via M-o)
(ivy-add-actions
 'counsel-fzf
 '(("r" my/counsel-fzf-dir "change root directory")
   ("g" my/counsel-rg-dir "use ripgrep in root directory")
   ("a" my/counsel-fzf-ace-window "ace-window switch")))

(ivy-add-actions
 'counsel-rg
 '(("r" my/counsel-rg-dir "change root directory")
   ("z" my/counsel-fzf-dir "find file with fzf in root directory")))

(ivy-add-actions
 'counsel-find-file
 '(("g" my/counsel-rg-dir "use ripgrep in root directory")
   ("z" my/counsel-fzf-dir "find file with fzf in root directory")
   ;; ("i" ivy-copy-to-buffer-action "insert")
   ;; ("y" ivy-yank-action "yank")
   ))

;; to toggle case sesitivity in swiper
(define-key ivy-minibuffer-map (kbd "M-c") 'ivy-toggle-case-fold)

(defun ivy-yank-action (x)
  (kill-new x))

(defun ivy-copy-to-buffer-action (x)
  (with-ivy-window
    (insert x)))

(ivy-set-actions
 t
 '(("i" ivy-copy-to-buffer-action "insert")
   ("y" ivy-yank-action "yank")
   ("O" my/counsel-ff-ace-window "find file with ace-window integration")
   ))

(setq counsel-yank-pop-preselect-last t)

;;(ivy-set-actions t nil)

Avy

(use-package avy
  :ensure t
  :bind (("M-s s" . avy-goto-char)
         ("M-s w" . avy-goto-word-0)
         ("M-s a" . avy-goto-char-2)
         ("M-s l" . avy-goto-line)
         (:map evil-normal-state-map
               ("g s" . avy-goto-char)
               ("g S" . avy-goto-char-2)))
  :config
  (avy-setup-default))

(setq avy-background t)

Hippie-expand

(use-package dabbrev
  :commands (dabbrev-expand dabbrev-completion)
  :config
  (setq dabbrev-abbrev-char-regexp "\\sw\\|\\s_")
  (setq dabbrev-abbrev-skip-leading-regexp "\\$\\|\\*\\|/\\|=")
  (setq dabbrev-backward-only nil)
  (setq dabbrev-case-distinction nil)
  (setq dabbrev-case-fold-search t)
  (setq dabbrev-case-replace nil)
  (setq dabbrev-check-other-buffers t)
  (setq dabbrev-eliminate-newlines nil)
  (setq dabbrev-upcase-means-case-search t))

(use-package hippie-exp
  :after dabbrev
  :config
  (setq hippie-expand-try-functions-list
        '(try-expand-dabbrev-visible
          try-expand-dabbrev
          try-expand-dabbrev-all-buffers
          try-expand-dabbrev-from-kill
          try-expand-list-all-buffers
          try-expand-list
          try-expand-line-all-buffers
          try-expand-line
          try-complete-file-name-partially
          try-complete-file-name
          try-expand-all-abbrevs))
  (setq hippie-expand-verbose nil)
  :bind ("M-/" . hippie-expand))

Company

(use-package company
  :diminish company-mode
  :defines
  (company-dabbrev-ignore-case company-dabbrev-downcase)
  :bind
  (("M-s-÷" . company-complete)
   (:map company-active-map
         ("C-n" . company-select-next)
         ("C-p" . company-select-previous)
         ("<tab>" . company-complete-common-or-cycle)
         ("TAB" . company-complete-common-or-cycle)
         ("M-i" . company-complete-common-or-cycle)
         :map company-search-map
         ("C-p" . company-select-previous)
         ("C-n" . company-select-next)))
  :hook
  (after-init . global-company-mode)
  ;;(plantuml-mode . (lambda () (set (make-local-variable 'company-backends)
  ;;                                 '((company-yasnippet
  ;;                                    ;; company-dabbrev
  ;;                                    )))))
  ;;((go-mode
  ;;  c++-mode
  ;;  org-mode
  ;;  emacs-lisp-mode
  ;;  shell-mode
  ;;  groovy-mode
  ;;  java-mode
  ;;  python-mode
  ;;  ) . (lambda () (set (make-local-variable 'company-backends)
  ;;                      '((company-yasnippet
  ;;                         company-lsp
  ;;                         company-files
  ;;                         company-capf
  ;;                         company-dabbrev-code
  ;;                         company-dabbrev
  ;;                         )))))
  :config
  (setq
   company-auto-complete nil

   ;; start autocompletion only after typing
   company-begin-commands '(self-insert-command)

   company-echo-delay (if (display-graphic-p) nil 0)

   company-dabbrev-code-everywhere t

   company-dabbrev-code-modes t

   ;; Only 2 letters required for completion to activate.
   company-minimum-prefix-length 2

   ;; Search other buffers for compleition candidates

   company-dabbrev-other-buffers 'all

   company-dabbrev-code-other-buffers 'all

   company-transformers
   '(company-sort-by-backend-importance
     company-sort-prefer-same-case-prefix
     company-sort-by-occurrence)

   company-tooltip-align-annotations t

   company-tooltip-limit 20

   company-tooltip-margin 1

   company-tooltip-minimum 3

   company-tooltip-idle-delay 0

   company-tooltip-offset-display 'scrollbar

   company-frontends '(company-pseudo-tooltip-frontend
                       company-echo-metadata-frontend)

   company-require-match nil

   ;; Allow (lengthy) numbers to be eligible for completion.
   company-complete-number t

   ;; M-⟪num⟫ to select an option according to its number.
   company-show-numbers t

   ;; Edge of the completion list cycles around.
   company-selection-wrap-around t

   ;; Do not downcase completions by default.
   company-dabbrev-downcase nil

   ;; Even if I write something with the ‘wrong’ case,
   ;; provide the ‘correct’ casing.
   company-dabbrev-ignore-case t

   ;;copied from oremacs
   company-backends '(company-capf
                      (company-dabbrev-code company-gtags company-etags
                                            company-keywords)
                      company-files
                      company-dabbrev)

   ;; Immediately activate completion.
   company-idle-delay 0.3
   )

  ;; TOPIC: How add company-dabbrev to the Company completion popup?
  ;; URL: https://emacs.stackexchange.com/questions/15246/how-add-company-dabbrev-to-the-company-completion-popup
  ;; (add-to-list 'company-backends 'company-dabbrev-code)
  ;; (add-to-list 'company-backends 'company-gtags)
  ;; (add-to-list 'company-backends 'company-etags)
  ;; (add-to-list 'company-backends 'company-keywords)
  ;; (add-to-list 'company-backends 'company-files)
  ;; (add-to-list 'company-backends 'company-dabbrev)
  ;; (add-to-list 'company-backends 'company-capf)
  ;; using child frame
  (use-package company-posframe
    :ensure t
    :hook (company-mode . company-posframe-mode))

  (use-package company-fuzzy
    :ensure t
    :defer t
    :init
    (setq company-fuzzy-sorting-backend 'flx)
    (setq company-fuzzy-prefix-ontop nil)
    (with-eval-after-load 'company
      (global-company-fuzzy-mode t)))

  (use-package company-shell
    :ensure t
    :config
    (add-to-list 'company-backends '(company-shell
                                     company-shell-env
                                     company-fish-shell)))

  ;; Better sorting and filtering
  (use-package company-prescient
    :init (company-prescient-mode 1))

  ;; Show pretty icons
  (use-package company-box
    :ensure t
    :diminish
    :hook (company-mode . company-box-mode)
    ;;:init (setq company-box-doc-enable nil ; disable auto `company-box-doc' timer.
    ;;            company-box-show-single-candidate t ; for still can use doc popup keybinding.
    ;;            company-box-doc-delay 0.5
    ;;            )
    ;;:init (setq company-box-icons-alist 'company-box-icons-all-the-icons)
    :config
    ;; Overright this method to get candidate numbers in company box
    (defun company-box--render-buffer (string)
      (let ((selection company-selection))
        (with-current-buffer (company-box--get-buffer)
          (erase-buffer)
          (insert string "\n")
          (setq mode-line-format nil
                display-line-numbers t
                truncate-lines t
                cursor-in-non-selected-windows nil)
          (setq-local scroll-step 1)
          (setq-local scroll-conservatively 10000)
          (setq-local scroll-margin  0)
          (setq-local scroll-preserve-screen-position t)
          (add-hook 'window-configuration-change-hook 'company-box--prevent-changes t t)
          (company-box--update-line selection))))

    (setq company-box-backends-colors nil)
    (setq company-box-show-single-candidate t)
    (setq company-box-max-candidates 50)

    (setq company-box-icons-unknown 'fa_question_circle)

    (setq company-box-icons-elisp
          '((fa_tag :face font-lock-function-name-face) ;; Function
            (fa_cog :face font-lock-variable-name-face) ;; Variable
            (fa_cube :face font-lock-constant-face) ;; Feature
            (md_color_lens :face font-lock-doc-face))) ;; Face

    (setq company-box-icons-yasnippet 'fa_bookmark)

    (setq company-box-icons-lsp
          '((1 . fa_text_height) ;; Text
            (2 . (fa_tags :face font-lock-function-name-face)) ;; Method
            (3 . (fa_tag :face font-lock-function-name-face)) ;; Function
            (4 . (fa_tag :face font-lock-function-name-face)) ;; Constructor
            (5 . (fa_cog :foreground "#FF9800")) ;; Field
            (6 . (fa_cog :foreground "#FF9800")) ;; Variable
            (7 . (fa_cube :foreground "#7C4DFF")) ;; Class
            (8 . (fa_cube :foreground "#7C4DFF")) ;; Interface
            (9 . (fa_cube :foreground "#7C4DFF")) ;; Module
            (10 . (fa_cog :foreground "#FF9800")) ;; Property
            (11 . md_settings_system_daydream) ;; Unit
            (12 . (fa_cog :foreground "#FF9800")) ;; Value
            (13 . (md_storage :face font-lock-type-face)) ;; Enum
            (14 . (md_closed_caption :foreground "#009688")) ;; Keyword
            (15 . md_closed_caption) ;; Snippet
            (16 . (md_color_lens :face font-lock-doc-face)) ;; Color
            (17 . fa_file_text_o) ;; File
            (18 . md_refresh) ;; Reference
            (19 . fa_folder_open) ;; Folder
            (20 . (md_closed_caption :foreground "#009688")) ;; EnumMember
            (21 . (fa_square :face font-lock-constant-face)) ;; Constant
            (22 . (fa_cube :face font-lock-type-face)) ;; Struct
            (23 . fa_calendar) ;; Event
            (24 . fa_square_o) ;; Operator
            (25 . fa_arrows)) ;; TypeParameter
          )
    )
  ;;Show quick tooltip
                                        ;(use-package company-quickhelp
  ;;  :ensure t
  ;;  :defines company-quickhelp-delay
  ;;  :bind (:map company-active-map
  ;;              ("M-h" . company-quickhelp-manual-begin))
  ;;  :hook (global-company-mode . company-quickhelp-mode)
  ;;  :custom (company-quickhelp-delay 0.15))
  )

;;(use-package company-jedi
;;  :ensure t
;;  :config
;;  (add-hook 'python-mode-hook 'jedi:setup)
;;  )

;;(defun my/python-mode-hook ()
;;  (add-to-list 'company-backends 'company-jedi))

;;(add-hook 'python-mode-hook 'my/python-mode-hook)

;; Had to comment this to get company mode working in org mode
;;(setq company-global-modes '(not org-mode))

(require 'company)
;; http://oremacs.com/2017/12/27/company-numbers/
(setq company-show-numbers t)
(let ((map company-active-map))
  (mapc
   (lambda (x)
     (define-key map (format "%d" x) 'ora-company-number))
   (number-sequence 0 9))
  (define-key map " " (lambda ()
                        (interactive)
                        (company-abort)
                        (self-insert-command 1)))
  (define-key map (kbd "<return>") nil))

(defun ora-company-number ()
  "Forward to `company-complete-number'.

  Unless the number is potentially part of the candidate.
  In that case, insert the number."
  (interactive)
  (let* ((k (this-command-keys))
         (re (concat "^" company-prefix k)))
    (if (cl-find-if (lambda (s) (string-match re s))
                    company-candidates)
        (self-insert-command 1)
      (company-complete-number (string-to-number k)))))

;;(add-to-list 'company-backends '(company-capf company-dabbrev company-dabbrev-code company-files))
(define-key global-map (kbd "C-c c f") 'company-files)

Reveal.js

(use-package ox-reveal
  :defer 1
  :ensure ox-reveal)

(setq org-reveal-root "http://cdn.jsdelivr.net/reveal.js/3.0.0/")
(setq org-reveal-mathjax t)

(use-package htmlize
  :defer 1
  :ensure t)

Org-Config-Easy-Template

;; add <el for emacs-lisp expansion

;; Setup code block templates.
;; For Org-mode < 9.2
(setq old-structure-template-alist
      '(("py" "#+BEGIN_SRC python :results output\n?\n#+END_SRC" "")
        ("ipy" "#+BEGIN_SRC ipython :results output\n?\n#+END_SRC" "")
        ("el" "#+BEGIN_SRC emacs-lisp\n?\n#+END_SRC" "")
        ("hs" "#+BEGIN_SRC haskell\n?\n#+END_SRC" "")
        ("laeq" "#+BEGIN_LaTeX\n\\begin{equation} \\label{eq-sinh}\ny=\\sinh x\n\\end{equation}\n#+END_LaTeX" "")
        ("sh" "#+BEGIN_SRC sh\n?\n#+END_SRC" "")
        ("r" "#+BEGIN_SRC R\n?\n#+END_SRC" "")
        ("js" "#+BEGIN_SRC js\n?\n#+END_SRC" "")
        ("http" "#+BEGIN_SRC http\n?\n#+END_SRC" "")
        ("ditaa" "#+BEGIN_SRC ditaa :file\n?\n#+END_SRC" "")
        ("dot" "#+BEGIN_SRC dot :file\n?\n#+END_SRC" "")
        ("rp" "#+BEGIN_SRC R :results output graphics :file \n?\n#+END_SRC" "")
        ("plantuml" "#+BEGIN_SRC plantuml :file\n?\n#+END_SRC" "")
        ("n" "#+NAME: ?")
        ("cap" "#+CAPTION: ?")))
;; For Org-mode >= 9.2
(setq new-structure-template-alist
      '(("py" . "src python :results output")
        ("ipy" . "src ipython :results output")
        ("el" . "src emacs-lisp")
        ("hs" . "src haskell")
        ("laeq" . "latex \n\\begin{equation} \\label{eq-sinh}\ny=\\sinh x\n\\end{equation}")
        ("sh" . "src sh")
        ("r" . "src R")
        ("js" . "src js")
        ("http" . "src http")
        ("ditaa" . "src ditaa :file")
        ("dot" . "src dot :file")
        ("rp" . "src R :results output graphics :file ")
        ("plantuml" . "src plantuml :file")
        ))
;; Keyword expansion also changed in 9.2
(setq my-tempo-keywords-alist
      '(("n" . "NAME")
        ("cap" . "CAPTION")))

(when (version< (org-version) "9.2")
  (add-to-list 'org-modules 'org-tempo))
(require 'org-tempo)
(if (version<  (org-version) "9.2")
    (dolist (ele old-structure-template-alist)
      (add-to-list 'org-structure-template-alist ele))
  (dolist (ele new-structure-template-alist)
    (add-to-list 'org-structure-template-alist ele))
  (dolist (ele my-tempo-keywords-alist)
    (add-to-list 'org-tempo-keywords-alist ele))
  )

;;;; add <cl for emacs-lisp expansion
;;(add-to-list 'org-structure-template-alist
;;             '("cl" "#+BEGIN_SRC clojure\n?\n#+END_SRC"
;;               "<src lang=\"clojure\">\n?\n</src>"))
;;
;;;; add <p for python expansion
;;(add-to-list 'org-structure-template-alist
;;             '("p" "#+BEGIN_SRC python :results output org drawer\n?\n#+END_SRC"
;;               "<src lang=\"python\">\n?\n</src>"))
;;
;;;; add <r for R expansion
;;(add-to-list 'org-structure-template-alist
;;             '("r" "#+BEGIN_SRC r :results output org drawer\n?\n#+END_SRC"
;;               "<src lang=\"r\">\n?\n</src>"))
;;
;;(add-to-list 'org-structure-template-alist
;;             '("ao" "#+attr_org: " ""))
;;
;;(add-to-list 'org-structure-template-alist
;;             '("al" "#+attr_latex: " ""))
;;
;;(add-to-list 'org-structure-template-alist
;;             '("ca" "#+caption: " ""))
;;
;;(add-to-list 'org-structure-template-alist
;;             '("tn" "#+tblname: " ""))
;;
;;(add-to-list 'org-structure-template-alist
;;             '("n" "#+name: " ""))
;;
;;(add-to-list 'org-structure-template-alist
;;             '("o" "#+options: " ""))
;;
;;(add-to-list 'org-structure-template-alist
;;             '("ti" "#+title: " ""))

FlyCheck

(use-package flycheck
  :defer 1
  :ensure t
  :init
  (global-flycheck-mode t)
  :config
  ;;(setq-default flycheck-highlighting-mode 'lines)
  ;;(setq flycheck-check-syntax-automatically '(mode-enabled save idle-change))
  (setq flycheck-check-syntax-automatically '(save))
  (setq flycheck-highlighting-mode 'lines)
  (setq flycheck-indication-mode 'left-fringe)
  )

Python

;;(setq py-python-command "python3")
;;(setq python-shell-interpreter "python3")
;;(use-package jedi
;;  :ensure t
;;  :init
;;  (add-hook 'python-mode-hook 'jedi:setup)
;; ;; (add-hook 'python-mode-hook 'jedi:ac-setup)
;; )
;;;;make sure to install jedi-server for effective pip lint
;;;;M-x jedi:install-server
;;;;Check Elpy if interested in Python Developement
;;(use-package jedi
;;  :ensure t
;;  :init
;;  (add-to-list 'company-backends 'company-jedi)
;;  :config
;;  (use-package company-jedi
;;    :ensure t
;;    :init
;;    (add-hook 'python-mode-hook (lambda () (add-to-list 'company-backends 'company-jedi)))
;;    (setq company-jedi-python-bin "python")))
;;
;;(use-package elpy
;;  :ensure t
;;  :commands (elpy-enable)
;;  :init
;;  (setq elpy-rpc-backend "jedi")
;;  :config
;;  (add-to-list 'auto-mode-alist '("\\.py$" . python-mode))
;;  ;; (add-hook 'python-mode-hook 'py-autopep8-enable-on-save)
;;  ;;flycheck-python-flake8-executable "/usr/local/bin/flake8"
;;  (setq elpy-rpc-python-command "python3"
;;        elpy-modules (dolist (elem '(elpy-module-highlight-indentation
;;                                     elpy-module-yasnippet))
;;                       (remove elem elpy-modules)))
;;
;;  :bind (:map elpy-mode-map
;;              ("M-." . elpy-goto-definition)
;;              ("M-," . pop-tag-mark)
;;              )
;;  )


(use-package lsp-python-ms
  :defer 1
  :ensure t
  :hook (python-mode . (lambda ()
                         (require 'lsp-python-ms)
                         (lsp))))

(setq lsp-python-ms-executable "~/GitRepos/python-language-server/output/bin/Release/osx-x64/publish/Microsoft.Python.LanguageServer")
(setq lsp-python-ms-python-executable-cmd "python3")

(use-package pyvenv
  :defer 1
  :custom
  (pyvenv-mode-line-indicator '(pyvenv-virtual-env-name ("[venv:" pyvenv-virtual-env-name "] ")))
  :config
  (add-hook 'pyvenv-post-activate-hooks
            #'(lambda ()
                (call-interactively #'lsp-workspace-restart)))
  (pyvenv-mode +1))

;;(use-package pyenv-mode
;;  :hook ((python-mode . pyenv-mode))
;;  :config
;;  ;; integrate pyenv with projectile
;;  (defun projectile-pyenv-mode-set ()
;;    "Set pyenv version matching project name."
;;    (let ((project (projectile-project-name)))
;;      (if (member project (pyenv-mode-versions))
;;          (pyenv-mode-set project)
;;        (pyenv-mode-unset))))
;;  (add-hook 'projectile-switch-project-hook 'projectile-pyenv-mode-set))

(use-package virtualenvwrapper
  :defer 1
  :ensure t
  ;; Automatically switch python venv
  :hook (projectile-after-switch-project . venv-projectile-auto-workon)
  :config
  (venv-initialize-interactive-shells)
  (venv-initialize-eshell)
  (setq venv-location "/Users/ckoneru/.virtualenvs/")
  )


;;(use-package auto-virtualenv
;;  :ensure t
;;  :config
;;  (add-hook 'python-mode-hook 'auto-virtualenv-set-virtualenv)
;;  )

;; lightweight auto activate python virtualenvs
;;(use-package auto-virtualenvwrapper
;;  :ensure t
;;  :after
;;  (:all python virtualenvwrapper)
;;  :init
;;  (add-hook 'python-mode-hook #'auto-virtualenvwrapper-activate))

(use-package pip-requirements
  :defer 1
  :ensure t
  :mode ("/requirements.txt$" . pip-requirements-mode))

(use-package blacken
  :defer 1
  :ensure t
  :config
  ;; (add-hook 'python-mode-hook 'blacken-mode)
  ;; Allow using Python 3.6-only syntax
  (setq blacken-allow-py36 t)
  ;; Skips temporary sanity checks
  (setq blacken-fast-unsafe t)
  ;; Use fill-column line-length
  (setq blacken-line-length 'fill)
  )

;; package-list-packages like interface for python packages
(use-package pippel
  :ensure t
  :defer t)

(use-package python-test
  :ensure t
  :defer t
  :config
  ;; Set default test backend to pytest
  (setq python-test-backend 'pytest))


;; Enable (restructured) syntax highlighting for python docstrings
(use-package python-docstring
  :defer t
  :ensure t
  :hook (python-mode . python-docstring-mode))

(use-package pydoc
  :defer t
  :ensure t
  :bind (:map python-mode-map
              ("M-?" . pydoc-at-point)))

(use-package counsel-pydoc
  :defer t
  :ensure t)

White Space and Blank Lines

;; whitespace cleanup
(use-package whitespace-cleanup-mode
  :defer 1
  :ensure t
  :diminish whitespace-cleanup-mode
  :init (global-whitespace-cleanup-mode))

MarkDown mode

(use-package markdown-mode
  ;;:defer t
  :ensure t
  :commands (markdown-mode gfm-mode)
  :mode (("README\\.md\\'" . gfm-mode)
         ("\\.md\\'" . markdown-mode)
         ("\\.markdown\\'" . markdown-mode))
  ;; :init (setq markdown-command "/usr/local/bin/multimarkdown")
  )

(use-package markdownfmt
  ;;:defer 2
  :ensure t)

(use-package markdown-mode+
  :ensure t
  :after markdown-mode
 ;;:defer t
 )

(setq markdown-command
      (concat
       "/usr/local/bin/pandoc"
       " -f markdown+smart -t html5-smart"
       " --self-contained --highlight-style=pygments"
       " -c ~/.emacs.d/custom-el-scripts/github-pandoc.css"
       " --standalone --mathjax --highlight-style=pygments"))

;;(setq markdown-command "/usr/local/bin/multimarkdown --smart --notes")

(use-package poly-markdown
  ;;:defer 2
  :ensure t)

(use-package polymode
  ;;:defer 2
  :ensure t
  )

(use-package markdown-preview-mode
  ;;:defer 2
  :ensure t)

(use-package markdown-toc
  ;;:defer 2
  :ensure t)

;; Automatic preview
;; Link: https://github.com/mola-T/flymd
(use-package flymd
  ;;:defer 2
  :ensure t)

(use-package ox-gfm
  ;;:defer 2
  :ensure t
  :after ox
  :config (require 'ox-gfm))

(use-package grip-mode
  ;;:defer 2
  :ensure t
  ;;:hook ((markdown-mode org-mode adoc-mode) . grip-mode)
  )

Undo-tree

(use-package undo-tree
  :ensure t
  :init
  (global-undo-tree-mode)
  :config
  (setq undo-tree-auto-save-history t)
  (setq undo-tree-enable-undo-in-region t) ;; undo-tree on a selected region
  (add-to-list 'undo-tree-incompatible-major-modes #'magit-modes)
  )

;;(use-package undo-tree
;;  :load-path "~/.emacs.d/custom-el-scripts/undo-tree/"
;;  :init
;;  (global-undo-tree-mode))

;; Keep region when undoing in region
(defadvice undo-tree-undo (around keep-region activate)
  (if (use-region-p)
      (let ((m (set-marker (make-marker) (mark)))
            (p (set-marker (make-marker) (point))))
        ad-do-it
        (goto-char p)
        (set-mark m)
        (set-marker p nil)
        (set-marker m nil))
    ad-do-it))

Highlight cursor line

(global-hl-line-mode t)

Beacon Mode

;; flashes the cursor's line when you scroll
(use-package beacon
  :ensure t
  :config
  (beacon-mode 1)
  ;; this color looks good for the zenburn theme but not for the one
  ;; I'm using for the videos
  (setq beacon-color "#666600")
  )

Hungy Delete Mode

;;  deletes all the whitespace when you hit backspace or delete
(use-package hungry-delete
  :defer 1
  :ensure t
  :config
  (global-hungry-delete-mode))

Smart-HUngry Delete

(use-package smart-hungry-delete
  :ensure t
  :bind (("C-M-<backspace>" . smart-hungry-delete-backward-char)
         ("C-d" . smart-hungry-delete-forward-char))
  :defer nil ;; dont defer so we can add our functions to hooks
  :config (smart-hungry-delete-add-default-hooks)
  )

Expand Region

;; expand the marked region in semantic increments (negative prefix to reduce region)
(use-package expand-region
  :ensure t
  :config
  (global-set-key (kbd "C-=") 'er/expand-region)
  (global-set-key (kbd "C-+") 'er/contract-region)
  )


(defhydra my/hydra-expand (:pre (er/mark-word)
                                :color red
                                :hint nil)
  "
 _a_: add    _r_: reduce   _q_: quit
 "
  ("a" er/expand-region)
  ("r" er/contract-region)
  ("q" nil :color blue))

(bind-keys*
 ("M-m a a" . my/hydra-expand/body))

Multiple Cursors

(use-package multiple-cursors
  :ensure t
  :config
  (global-set-key (kbd "C-c h m") 'my/hydra-multiple-cursors/body)
  (global-set-key (kbd "C->") 'mc/mark-next-like-this)
  (global-set-key (kbd "C-<") 'mc/mark-previous-like-this)
  (global-set-key (kbd "C-c C-<") 'mc/mark-all-like-this)
  (global-set-key (kbd "C-S-l C-n") 'mc/mark-next-lines)
  :preface
  ;; insert specific serial number
  (defvar my/mc/insert-numbers-hist nil)
  (defvar my/mc/insert-numbers-inc 1)
  (defvar my/mc/insert-numbers-pad "%01d")
  (defun my/mc/insert-numbers (start inc pad)
    "Insert increasing numbers for each cursor specifically."
    (interactive
     (list (read-number "Start from: " 0)
           (read-number "Increment by: " 1)
           (read-string "Padding (%01d): " nil my/mc/insert-numbers-hist "%01d")))
    (setq mc--insert-numbers-number start)
    (setq my/mc/insert-numbers-inc inc)
    (setq my/mc/insert-numbers-pad pad)
    (mc/for-each-cursor-ordered
     (mc/execute-command-for-fake-cursor
      'my/mc--insert-number-and-increase
      cursor)))

  (defun my/mc--insert-number-and-increase ()
    (interactive)
    (insert (format my/mc/insert-numbers-pad mc--insert-numbers-number))
    (setq mc--insert-numbers-number (+ mc--insert-numbers-number my/mc/insert-numbers-inc)))

  (defhydra my/hydra-multiple-cursors (:hint nil)
    "
 Up^^             Down^^           Miscellaneous           % 2(mc/num-cursors) cursor%s(if (> (mc/num-cursors) 1) \"s\" \"\")
------------------------------------------------------------------
 [_p_]   Next     [_n_]   Next     [_l_] Edit lines  [_0_] Insert numbers
 [_P_]   Skip     [_N_]   Skip     [_a_] Mark all    [_A_] Insert letters
 [_M-p_] Unmark   [_M-n_] Unmark   [_s_] Search
 [Click] Cursor at point       [_q_] Quit"
    ("l" mc/edit-lines :exit t)
    ("a" mc/mark-all-like-this :exit t)
    ("n" mc/mark-next-like-this)
    ("N" mc/skip-to-next-like-this)
    ("M-n" mc/unmark-next-like-this)
    ("p" mc/mark-previous-like-this)
    ("P" mc/skip-to-previous-like-this)
    ("M-p" mc/unmark-previous-like-this)
    ("s" mc/mark-all-in-region-regexp :exit t)
    ("0" mc/insert-numbers :exit t)
    ("A" mc/insert-letters :exit t)
    ("q" nil))
  )

(use-package evil-mc
  :ensure t
  :config
  (global-evil-mc-mode 1))


(use-package evil-mc-extras
  :ensure t
  :config
  (global-evil-mc-extras-mode 1))

smart-forward

(use-package smart-forward
  :defer 1
  :ensure t
  :config
  (global-set-key (kbd "M-<up>") 'smart-up)
  (global-set-key (kbd "M-<down>") 'smart-down)
  (global-set-key (kbd "M-<left>") 'smart-backward)
  (global-set-key (kbd "M-<right>") 'smart-forward))

Join Line

(global-set-key (kbd "M-j")
                (lambda ()
                  (interactive)
                  (join-line -1)))

Parantasis/brackets

Highlight matching pair

;; Complete pair
;; auto close bracket insertion. New in emacs 24
(electric-pair-mode 1)
(setq electric-pair-preserve-balance nil)

;; turn on highlight matching brackets when cursor is on one
(show-paren-mode 1)

;; highlight brackets
(setq show-paren-style 'parenthesis)

;; highlight entire expression
;;(setq show-paren-style 'expression)

;; highlight brackets if visible, else entire expression
;;(setq show-paren-style 'mixed)

;; disable <> auto pairing in electric-pair-mode for org-mode
(add-hook
 'org-mode-hook
 (lambda ()
   (setq-local electric-pair-inhibit-predicate
               `(lambda (c)
                  (if (char-equal c ?<) t (,electric-pair-inhibit-predicate c))))))

;; make electric-pair-mode work on more brackets
(setq electric-pair-pairs
      '(
        (?\" . ?\")
        (?\' . ?\')
        (?\{ . ?\})
        ))

string-inflection for string manipulation

(use-package string-inflection
  :defer 1
  :ensure t
  :bind (("C-c i" . string-inflection-all-cycle))
  )

;; for java
(add-hook 'java-mode-hook
          '(lambda ()
             (local-set-key (kbd "C-c i") 'string-inflection-java-style-cycle)))

;; for python
(add-hook 'python-mode-hook
          '(lambda ()
             (local-set-key (kbd "C-c i") 'string-inflection-python-style-cycle)))

iedit and narrow / widen dwim

; mark and edit all copies of the marked region simultaniously.

(use-package iedit
  :defer 1
  :ensure t)

Web-Mode

(use-package web-mode
  :defer 1
  :ensure t
  :config
  (add-to-list 'auto-mode-alist '("\\.html?\\'" . web-mode))
  (setq web-mode-engines-alist
        '(("django"    . "\\.html\\'")))
  (setq web-mode-ac-sources-alist
        '(("css" . (ac-source-css-property))
          ("html" . (ac-source-words-in-buffer ac-source-abbrev))))

  (setq web-mode-enable-auto-closing t)
  (setq web-mode-enable-auto-quoting t))

Mode Line

(setq display-time-24hr-format t)
(setq display-time-day-and-date t)
(display-time-mode +1)

(use-package doom-modeline
  :ensure t
  :config
  (set-cursor-color "cyan")
  (line-number-mode +1)
  (column-number-mode +1))
(require 'doom-modeline)
(doom-modeline-init)
(setq doom-modeline-env-version t)
;;(setq doom-modeline-enable-word-count t)
;; Please refer to https://github.com/bbatsov/projectile/issues/657.
(setq doom-modeline-buffer-file-name-style 'truncate-upto-project)

;; Whether display icons in mode-line or not.
(setq doom-modeline-icon t)

;; Whether display the icon for major mode. It respects `doom-modeline-icon'.
(setq doom-modeline-major-mode-icon t)

;; Whether display color icons for `major-mode'. It respects
;; `doom-modeline-icon' and `all-the-icons-color-icons'.
(setq doom-modeline-major-mode-color-icon t)

;; Whether display icons for buffer states. It respects `doom-modeline-icon'.
(setq doom-modeline-buffer-state-icon t)

;; Whether display buffer modification icon. It respects `doom-modeline-icon'
;; and `doom-modeline-buffer-state-icon'.
(setq doom-modeline-buffer-modification-icon t)
;; Whether display minor modes in mode-line or not.
;;(setq doom-modeline-minor-modes t)

;; Whether display the `lsp' state. Non-nil to display in mode-line.
(setq doom-modeline-lsp t)

;; Whether display the modal state icon.
;; Including `evil', `overwrite', `god', `ryo' and `xah-fly-keys', etc.
(setq doom-modeline-modal-icon nil)

;; The maximum displayed length of the branch name of version control.
(setq doom-modeline-vcs-max-length 12)

;; Whether display environment version or not
(setq doom-modeline-env-version t)
;; Or for individual languages
(setq doom-modeline-env-enable-python t)
;;(setq doom-modeline-env-enable-ruby t)
;;(setq doom-modeline-env-enable-perl t)
(setq doom-modeline-env-enable-go t)
;;(setq doom-modeline-env-enable-elixir t)
;;(setq doom-modeline-env-enable-rust t)

;; Change the executables to use for the language version string
(setq doom-modeline-env-python-executable "python3") ; or `python-shell-interpreter'
;;(setq doom-modeline-env-ruby-executable "ruby")
;;(setq doom-modeline-env-perl-executable "perl")
(setq doom-modeline-env-go-executable "go")
;;(setq doom-modeline-env-elixir-executable "iex")
;;(setq doom-modeline-env-rust-executable "rustc")

;; What to dispaly as the version while a new one is being loaded
;;(setq doom-modeline-env-load-string "...")

;; Hooks that run before/after the modeline version string is updated
(setq doom-modeline-before-update-env-hook nil)
(setq doom-modeline-after-update-env-hook nil)

(doom-modeline-def-modeline 'main
  '(bar workspace-name window-number modals matches buffer-info remote-host buffer-position parrot selection-info)
  '(objed-state misc-info persp-name debug lsp minor-modes input-method indent-info buffer-encoding major-mode process vcs checker))

(doom-modeline-def-modeline 'minimal
  '(bar matches buffer-info-simple)
  '(media-info major-mode))

(doom-modeline-def-modeline 'special
  '(bar window-number modals matches buffer-info buffer-position parrot selection-info)
  '(objed-state misc-info debug lsp minor-modes input-method indent-info buffer-encoding major-mode process checker))

(doom-modeline-def-modeline 'project
  '(bar window-number buffer-default-directory)
  '(misc-info debug major-mode process))

(doom-modeline-def-modeline 'package
  '(bar window-number package)
  '(misc-info major-mode process))

(doom-modeline-def-modeline 'info
  '(bar window-number buffer-info info-nodes buffer-position parrot selection-info)
  '(misc-info buffer-encoding major-mode))

(doom-modeline-def-modeline 'media
  '(bar window-number buffer-size buffer-info)
  '(misc-info media-info major-mode process vcs))

(doom-modeline-def-modeline 'pdf
  '(bar window-number buffer-size buffer-info pdf-pages)
  '(misc-info major-mode process vcs))

;;(doom-modeline-def-modeline 'helm
;;  '(bar helm-buffer-id helm-number helm-follow helm-prefix-argument)
;;  '(helm-help))

;;(doom-modeline-def-modeline 'timemachine
;;  '(bar window-number matches git-timemachine buffer-position parrot selection-info)
;;  '(misc-info fancy-battery mu4e github debug minor-modes indent-info buffer-encoding major-mode))

;;(doom-modeline-def-modeline 'my-simple-line
;;  '(bar window-number matches buffer-info remote-host buffer-position parrot selection-info)
;;  '(misc-info minor-modes input-method buffer-encoding major-mode process vcs checker))

;;(defun setup-custom-doom-modeline ()
;;  (doom-modeline-set-modeline 'my-simple-line 'default))

;;(add-hook 'doom-modeline-mode-hook 'setup-custom-doom-modeline)

(defmacro rename-modeline (package-name mode new-name)
  `(eval-after-load ,package-name
     '(defadvice ,mode (after rename-modeline activate)
        (setq mode-name ,new-name))))

(rename-modeline "js2-mode" js2-mode "JS2")
(rename-modeline "clojure-mode" clojure-mode "Clj")

mode-icons

(use-package mode-icons
  :ensure t
  :config
  (mode-icons-mode))

Volatile-Highlights

(use-package volatile-highlights
  :ensure t
  :config
  (volatile-highlights-mode t))

Uniquify For buffer names

;;(use-package uniquify
;;  :ensure nil
;;  :config
  (setq uniquify-buffer-name-style 'post-forward-angle-brackets) ;; or "forward"
  ;;(setq uniquify-min-dir-content 3)
;;  )

Formatting and white-space

(setq-default indent-tabs-mode nil)

Posframe

(use-package posframe :ensure t)

Yasnippet

(use-package yasnippet
  :ensure t
  :init
  (yas-global-mode 1))

(use-package auto-yasnippet
  :ensure t)


(use-package yasnippet-snippets
  :ensure t
  :defer    t
  )

(use-package ivy-yasnippet
  :ensure t)

Dired

(setq dired-dwim-target t)

 (when (string= system-type "darwin")
   (setq dired-use-ls-dired t
         insert-directory-program "/usr/local/bin/gls"))
(setq dired-listing-switches "-aBhl --group-directories-first")

(add-hook 'dired-mode-hook 'dired-hide-details-mode)

(use-package diredfl
  :ensure t
  :config
  (add-hook 'dired-mode-hook 'diredfl-mode))

(use-package dired-git-info
  ;;:quelpa (dired-git-info :fetcher github :repo "clemera/dired-git-info")
  :straight (dired-git-info :type git :host github :repo "clemera/dired-git-info")
  ;;:ensure t
  :bind (:map dired-mode-map
              ("I" . dired-git-info-mode)))

(use-package dired-narrow
  :ensure t
  :config
  (bind-key "C-c C-n" #'dired-narrow)
  (bind-key "C-c C-f" #'dired-narrow-fuzzy)
  (bind-key "C-x C-N" #'dired-narrow-regexp)
  )

;;(use-package dired-subtree
;;  :ensure t
;;  :after dired
;;  :config
;;  (bind-key "t" #'dired-subtree-toggle dired-mode-map)
;;  (bind-key "T" #'dired-subtree-cycle dired-mode-map))


(use-package peep-dired
  :ensure t
  :config
  (setq peep-dired-cleanup-on-disable t)
  (define-key dired-mode-map (kbd "P") 'peep-dired)
  )

(use-package dired-single
  :ensure t
  :config
  (define-key dired-mode-map [return] 'dired-single-buffer)
  (define-key dired-mode-map [mouse-1] 'dired-single-buffer-mouse)
  )

(use-package dired-collapse
  :ensure t
  :defer
  :init
  (add-hook 'dired-mode-hook 'dired-collapse-mode))

(use-package image-dired+
  :ensure t
  :config
  (setq auto-image-file-mode t)
  (eval-after-load 'image-dired+ '(image-diredx-async-mode 1)))

(use-package dired-filter
  :ensure t
  :init
  (add-hook 'dired-mode-hook 'dired-filter-group-mode)

  :config
  (setq dired-filter-group-saved-groups
        '(("default"
           ("Directories" (directory))
           ("PDF"
            (extension . "pdf"))
           ("LaTeX"
            (extension "tex" "bib"))
           ("Org"
            (extension . "org"))
           ("Archives"
            (extension "zip" "rar" "gz" "bz2" "tar"))
           ("Multimedia"
            (extension "ogg" "flv" "mpg" "avi" "mp4" "mp3"))
           )))
  )

(use-package dired-rsync
  :defer t
  :ensure t
  :config
  (bind-key "C-c C-r" 'dired-rsync dired-mode-map))

;; Display the recursive size of directories in Dired
(use-package dired-du
  :ensure t
  :after dired
  :config
  ;; human readable size format
  (setq dired-du-size-format t))

(use-package wdired
  :ensure t
  :after dired
  :config
  (setq wdired-create-parent-directories t)
  ;; Make permission bits editable
  (setq wdired-allow-to-change-permissions t))

(use-package dired-hacks-utils
  :ensure t
  :hook (dired-mode . dired-utils-format-information-line-mode))

(use-package dired-open
  :ensure t
  :after dired
  :bind (:map dired-mode-map
              ("RET" . dired-open-file)
              ([return] . dired-open-file)
              ("f" . dired-open-file))
  :config
  ;; Reuse existing dired buffer
  (setq dired-open-find-file-function 'diredp-find-file-reuse-dir-buffer)
  (setq dired-open-functions '(dired-open-by-extension dired-open-guess-shell-alist dired-open-subdir)))

(use-package dired-ranger
  :ensure t
  :after dired
  :init
  (bind-keys :map dired-mode-map
             :prefix "c"
             :prefix-map dired-ranger-map
             :prefix-docstring "Map for ranger operations."
             ("c" . dired-ranger-copy)
             ("p" . dired-ranger-paste)
             ("m" . dired-ranger-move))

  (bind-keys :map dired-mode-map
             ("'" . dired-ranger-bookmark)
             ("`" . dired-ranger-bookmark-visit)))

(use-package dired-rainbow
  :ensure t
  :config
  (progn
    (dired-rainbow-define-chmod directory "#6cb2eb" "d.*")
    (dired-rainbow-define html "#eb5286" ("css" "less" "sass" "scss" "htm" "html" "jhtm" "mht" "eml" "mustache" "xhtml"))
    (dired-rainbow-define xml "#f2d024" ("xml" "xsd" "xsl" "xslt" "wsdl" "bib" "json" "msg" "pgn" "rss" "yaml" "yml" "rdata"))
    (dired-rainbow-define document "#9561e2" ("docm" "doc" "docx" "odb" "odt" "pdb" "pdf" "ps" "rtf" "djvu" "epub" "odp" "ppt" "pptx"))
    (dired-rainbow-define markdown "#ffed4a" ("org" "etx" "info" "markdown" "md" "mkd" "nfo" "pod" "rst" "tex" "textfile" "txt"))
    (dired-rainbow-define database "#6574cd" ("xlsx" "xls" "csv" "accdb" "db" "mdb" "sqlite" "nc"))
    (dired-rainbow-define media "#de751f" ("mp3" "mp4" "MP3" "MP4" "avi" "mpeg" "mpg" "flv" "ogg" "mov" "mid" "midi" "wav" "aiff" "flac"))
    (dired-rainbow-define image "#f66d9b" ("tiff" "tif" "cdr" "gif" "ico" "jpeg" "jpg" "png" "psd" "eps" "svg"))
    (dired-rainbow-define log "#c17d11" ("log"))
    (dired-rainbow-define shell "#f6993f" ("awk" "bash" "bat" "sed" "sh" "zsh" "vim"))
    (dired-rainbow-define interpreted "#38c172" ("py" "ipynb" "rb" "pl" "t" "msql" "mysql" "pgsql" "sql" "r" "clj" "cljs" "scala" "js"))
    (dired-rainbow-define compiled "#4dc0b5" ("asm" "cl" "lisp" "el" "c" "h" "c++" "h++" "hpp" "hxx" "m" "cc" "cs" "cp" "cpp" "go" "f" "for" "ftn" "f90" "f95" "f03" "f08" "s" "rs" "hi" "hs" "pyc" ".java"))
    (dired-rainbow-define executable "#8cc4ff" ("exe" "msi"))
    (dired-rainbow-define compressed "#51d88a" ("7z" "zip" "bz2" "tgz" "txz" "gz" "xz" "z" "Z" "jar" "war" "ear" "rar" "sar" "xpi" "apk" "xz" "tar"))
    (dired-rainbow-define packaged "#faad63" ("deb" "rpm" "apk" "jad" "jar" "cab" "pak" "pk3" "vdf" "vpk" "bsp"))
    (dired-rainbow-define encrypted "#ffed4a" ("gpg" "pgp" "asc" "bfe" "enc" "signature" "sig" "p12" "pem"))
    (dired-rainbow-define fonts "#6cb2eb" ("afm" "fon" "fnt" "pfb" "pfm" "ttf" "otf"))
    (dired-rainbow-define partition "#e3342f" ("dmg" "iso" "bin" "nrg" "qcow" "toast" "vcd" "vmdk" "bak"))
    (dired-rainbow-define vc "#0074d9" ("git" "gitignore" "gitattributes" "gitmodules"))
    (dired-rainbow-define-chmod executable-unix "#38c172" "-.*x.*")
    ))

;;;###autoload - http://oremacs.com/2016/02/24/dired-rsync/
(defun ora-dired-rsync (dest)
  (interactive
   (list
    (expand-file-name
     (read-file-name
      "Rsync to:"
      (dired-dwim-target-directory)))))
  ;; store all selected files into "files" list
  (let ((files (dired-get-marked-files
                nil current-prefix-arg))
        ;; the rsync command
        (tmtxt/rsync-command
         "rsync -arvz --progress "))
    ;; add all selected file names as arguments
    ;; to the rsync command
    (dolist (file files)
      (setq tmtxt/rsync-command
            (concat tmtxt/rsync-command
                    (shell-quote-argument file)
                    " ")))
    ;; append the destination
    (setq tmtxt/rsync-command
          (concat tmtxt/rsync-command
                  (shell-quote-argument dest)))
    ;; run the async shell command
    (async-shell-command tmtxt/rsync-command "*rsync*")
    ;; finally, switch to that window
    (other-window 1)))

(define-key dired-mode-map "Y" 'ora-dired-rsync)

;;http://xenodium.com/drill-down-emacs-dired-with-dired-subtree/
(use-package dired-subtree :ensure t
             :after dired
             :config
             (bind-key ">" #'dired-subtree-toggle dired-mode-map)
             (bind-key "<" #'dired-subtree-cycle dired-mode-map))

Projectile

;; projectile
(use-package projectile
  :defer 1
  :ensure t
  :bind ("C-c p" . projectile-command-map)
  :custom
  (projectile-project-search-path '("~/GitRepos/"))
  (projectile-indexing-method 'alien)
  (setq projectile-sort-order 'recently-active)
  (projectile-enable-caching t)
  :config
  (projectile-global-mode)
  (setq projectile-completion-system 'ivy))

;; (use-package counsel-projectile
;;   :ensure t
;;   :config
;;   (counsel-projectile-on))
;;(setq projectile-git-submodule-command "git submodule --quiet foreach 'echo $(git rev-parse --show-toplevel)' | xargs realpath --relative-to=$PWD 2> /dev/null")
;;https://github.com/bbatsov/projectile/issues/1302#issuecomment-433894379
(setq projectile-git-submodule-command nil)

Smart-Parens

(use-package smartparens
  :ensure t
  :demand t
  :bind* (("M-m m j" . sp-down-sexp)
          ("M-m m k" . sp-backward-up-sexp)
          ("M-m m h" . sp-backward-down-sexp)
          ("M-m m l" . sp-up-sexp)
          ("M-m m f" . sp-forward-sexp)
          ("M-m m b" . sp-backward-sexp)
          ("M-m m a" . sp-beginning-of-sexp)
          ("M-m m e" . sp-end-of-sexp)
          ("M-m m n" . sp-next-sexp)
          ("M-m m p" . sp-previous-sexp)
          ("M-m m >" . sp-forward-barf-sexp)
          ("M-m m <" . sp-backward-barf-sexp)
          ("M-m m )" . sp-forward-slurp-sexp)
          ("M-m m (" . sp-backward-slurp-sexp)
          ("M-m m x" . sp-transpose-sexp)
          ("M-m m d" . sp-kill-sexp)
          ("M-m m y" . sp-copy-sexp)
          ("M-m m u" . sp-unwrap-sexp)
          ("M-m m U" . sp-backward-unwrap-sexp)
          ("M-m m C" . sp-convolute-sexp)
          ("M-m m r" . sp-raise-sexp)
          ("M-m m s" . sp-split-sexp)
          ("M-m m S" . sp-splice-sexp)
          ("M-m m F" . sp-splice-sexp-killing-forward)
          ("M-m m B" . sp-splice-sexp-killing-backward)
          ("M-m m A" . sp-splice-sexp-killing-around))
  :diminish smartparens-mode
  :diminish smartparens-strict-mode
  :config

  ;; Diasble in org- mode as `smartparens' is heavy in `org-self-insert-command'.
  (add-to-list 'sp-ignore-modes-list 'org-mode)

  ;;(require 'smartparens-config)
  (smartparens-global-mode)
  ;;(smartparens-global-strict-mode)
  (show-smartparens-global-mode)
  (which-key-add-key-based-replacements
    "M-m m" "move prefix"))

;;(use-package smartparens-config
  ;;:ensure t
  ;;:ensure smartparens
  ;;:hook ((after-init . show-smartparens-global-mode)
	   ;;(after-init . smartparens-global-mode))
  ;;:init (gsetq sp-hybrid-kill-entire-symbol nil))

Font Scaling

;; font scaling
(use-package default-text-scale
  :ensure t
  :config
  (global-set-key (kbd "C-M-=") 'default-text-scale-increase)
  (global-set-key (kbd "C-M--") 'default-text-scale-decrease))

(use-package fontify-face
  :defer t)

Git

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

(use-package magit
  :ensure t
  :init
  (progn
    (bind-key "C-x g" 'magit-status)
    ))

(setq magit-status-margin
      '(t "%Y-%m-%d %H:%M " magit-log-margin-width t 18))
(use-package git-gutter
  :ensure t
  :init
  (global-git-gutter-mode +1))

(global-set-key (kbd "M-g M-g") 'hydra-git-gutter/body)


(use-package git-timemachine
  :defer t
  :ensure t
  )
(defhydra hydra-git-gutter (:body-pre (git-gutter-mode 1)
                                      :hint nil)
  "
    Git gutter:
      _j_: next hunk        _s_tage hunk     _q_uit
      _k_: previous hunk    _r_evert hunk    _Q_uit and deactivate git-gutter
      ^ ^                   _p_opup hunk
      _h_: first hunk
      _l_: last hunk        set start _R_evision
    "
  ("j" git-gutter:next-hunk)
  ("k" git-gutter:previous-hunk)
  ("h" (progn (goto-char (point-min))
              (git-gutter:next-hunk 1)))
  ("l" (progn (goto-char (point-min))
              (git-gutter:previous-hunk 1)))
  ("s" git-gutter:stage-hunk)
  ("r" git-gutter:revert-hunk)
  ("p" git-gutter:popup-hunk)
  ("R" git-gutter:set-start-revision)
  ("q" nil :color blue)
  ("Q" (progn (git-gutter-mode -1)
              ;; git-gutter-fringe doesn't seem to
              ;; clear the markup right away
              (sit-for 0.1)
              (git-gutter:clear))
   :color blue))

(use-package gitconfig-mode
  :defer t
  :ensure t
  :mode "\\.gitconfig\\'"
  :mode "\\.git/config\\'"
  :mode "\\.gitmodules\\'")

(use-package gitignore-mode
  :defer t
  :ensure t
  :mode "\\.gitignore\\'"
  :mode "\\.dockerignore\\'"
  :mode "\\..elpaignore\\'")

(use-package gitignore-templates
  :defer t
  :ensure t)

(use-package diffview
  :defer t
  :ensure t
  :commands (diffview-region diffview-current)
  :preface
  (defun my/diffview-dwim ()
    (interactive)
    (if (region-active-p)
        (diffview-region)
      (diffview-current)))
  :bind ("M-g v" . my/diffview-dwim))

(use-package smerge-mode
  :ensure t
  :diminish
  :preface
  (with-eval-after-load 'hydra
    (defhydra hydra-smerge
      (:color pink :hint nil :post (smerge-auto-leave))
      "
  ^Move^       ^Keep^               ^Diff^                 ^Other^
  ^^-----------^^-------------------^^---------------------^^-------
  _n_ext       _b_ase               _<_: upper/base        _C_ombine
  _p_rev       _u_pper              _=_: upper/lower       _r_esolve
  ^^           _l_ower              _>_: base/lower        _k_ill current
  ^^           _a_ll                _R_efine
  ^^           _RET_: current       _E_diff
  "
      ("n" smerge-next)
      ("p" smerge-prev)
      ("b" smerge-keep-base)
      ("u" smerge-keep-upper)
      ("l" smerge-keep-lower)
      ("a" smerge-keep-all)
      ("RET" smerge-keep-current)
      ("\C-m" smerge-keep-current)
      ("<" smerge-diff-base-upper)
      ("=" smerge-diff-upper-lower)
      (">" smerge-diff-base-lower)
      ("R" smerge-refine)
      ("E" smerge-ediff)
      ("C" smerge-combine-with-next)
      ("r" smerge-resolve)
      ("k" smerge-kill-current)
      ("ZZ" (lambda ()
              (interactive)
              (save-buffer)
              (bury-buffer))
       "Save and bury buffer" :color blue)
      ("q" nil "cancel" :color blue)))
  :hook ((find-file . (lambda ()
                        (save-excursion
                          (goto-char (point-min))
                          (when (re-search-forward "^<<<<<<< " nil t)
                            (smerge-mode 1)))))
         (magit-diff-visit-file . (lambda ()
                                    (when smerge-mode
                                      (smerge-hydra/body))))))


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

(use-package magit-todos
  :defer t
  :ensure t
  :commands (magit-todos-mode)
  :hook (magit-mode . magit-todos-mode)
  :config
  (setq magit-todos-recursive t
        magit-todos-depth 100)
  :custom (magit-todos-keywords (list "TODO" "FIXME")))

(use-package git-commit
  :ensure t
;;  :defer t
  )

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

(use-package git-msg-prefix
  :ensure t
  :defer t
  :config
  (setq git-msg-prefix-log-flags " --since='1 week ago' "
        git-msg-prefix-regex "^\\([^:]*: \\)"
        git-msg-prefix-input-method 'ivy-read)
  ;; (add-hook 'git-commit-mode-hook 'git-msg-prefix)
  )

;; Github api
(use-package gh
  :defer t
  :ensure t)
(use-package gh-md
  :defer t
  :ensure t)

;; Search on github
(use-package github-search
  :defer t
  :ensure t)

;; Mapping github with magit
(use-package ghub
  :defer t
  :ensure t)
(use-package ghub+
  :defer t
  :ensure t)

;;(use-package magithub
;;  :ensure t
;;  :after (:all magit ghub ghub+)
;;  :config (magithub-feature-autoinject t)
;;  (setq magithub-clone-default-directory "~/github"))

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

;; Display commit number that is associated with current line of code
(use-package vc-msg
  :defer t
  :after (vc popup)
  :commands (vc-msg-show
             my/vc-msg-init)
  :bind
  ("C-x v c" . vc-msg-show)
  :hook (vc-msg . my/vc-msg-init)
  :config (defun my/vc-msg-init (vcs-type commit-info)
            ;; copy commit id to clipboard
            (message (format "%s\n%s\n%s\n%s"
                             (plist-get commit-info :id)
                             (plist-get commit-info :author)
                             (plist-get commit-info :author-time)
                             (plist-get commit-info :author-summary)))))

(defun my/git-commit-search-message-history ()
  "Search and insert commit message from history.
     http://xenodium.com/m-r-history-search-in-git-commit-mode/"
  (interactive)
  (insert (completing-read "History: "
                           ;; Remove unnecessary newlines from beginning and end.
                           (mapcar (lambda (text)
                                     (string-trim text))
                                   (ring-elements log-edit-comment-ring)))))

(bind-key "M-r" #'my/git-commit-search-message-history git-commit-mode-map)
;;(add-to-list 'savehist-additional-variables log-edit-comment-ring)
;;(savehist-mode +1)

(setq magit-repository-directories
      `(("~/.emacs.d/" . 0)
        ("~/GitRepos/" . 1)
        ("~/IdeaProjects/" . 1)))

;; full screen magit-status

(defadvice magit-status (around magit-fullscreen activate)
  (window-configuration-to-register :magit-fullscreen)
  ad-do-it
  (delete-other-windows))

(defun magit-quit-session ()
  "Restores the previous window configuration and kills the magit buffer"
  (interactive)
  (kill-buffer)
  (jump-to-register :magit-fullscreen))

(define-key magit-status-mode-map (kbd "q") 'magit-quit-session)

;; C-c C-a to amend without any prompt
;; This code is inbuild by magit so Instead you should be using the built in Extend Commit command: `c e'
;;(defun magit-just-amend ()
;;  (interactive)
;;  (save-window-excursion
;;    (magit-refresh
;;     (shell-command "git --no-pager commit --amend --reuse-message=HEAD"))))
;;
;;(eval-after-load "magit"
;;  '(define-key magit-status-mode-map (kbd "C-c C-a") 'magit-just-amend))

(setq magit-repository-directories
      `(("~/.emacs.d/" . 0)
        ("~/GitRepos/" . 1)
        ("~/IdeaProjects/" . 1)))

;; full screen magit-status

(defadvice magit-status (around magit-fullscreen activate)
  (window-configuration-to-register :magit-fullscreen)
  ad-do-it
  (delete-other-windows))

(defun magit-quit-session ()
  "Restores the previous window configuration and kills the magit buffer"
  (interactive)
  (kill-buffer)
  (jump-to-register :magit-fullscreen))

(define-key magit-status-mode-map (kbd "q") 'magit-quit-session)

;;Emacs comes with a version control interface called "VC", see (emacs)Version Control. It is enabled be default, and if you don’t use it in addition to Magit, then you should disable it to keep it from performing unnecessary work:

(setq vc-handled-backends nil)

;;You can also disable its use for Git but keep using it when using another version control system:

(setq vc-handled-backends (delq 'Git vc-handled-backends))

Dumb Jump

(use-package dumb-jump
  :defer 1
  :bind (("M-g o" . dumb-jump-go-other-window)
         ("M-g s" . dumb-jump-go)
         ("M-g x" . dumb-jump-go-prefer-external)
         ("M-g z" . dumb-jump-go-prefer-external-other-window))
  :config
  (setq dumb-jump-selector 'ivy) ;; (setq dumb-jump-selector 'helm)
  :init
  (dumb-jump-mode)
  :ensure t
  )

;;smart-Jump

(use-package smart-jump
  :defer 1
  :ensure t
  :config
  (smart-jump-setup-default-registers))

Origami folding

(use-package origami
  :defer t
  :ensure t
  ;;:ensure quelpa
  ;;:quelpa (origami :repo "seblemaguer/origami.el" :fetcher github)
  :custom
  (origami-show-fold-header t)

  :custom-face
  (origami-fold-replacement-face ((t (:inherit magit-diff-context-highlight))))
  (origami-fold-fringe-face ((t (:inherit magit-diff-context-highlight))))

  :init
  (defhydra origami-hydra (:color blue :hint none)
    "
      _:_: recursively toggle node       _a_: toggle all nodes    _t_: toggle node
      _o_: show only current node        _u_: undo                _r_: redo
      _R_: reset
      "
    (":" origami-recursively-toggle-node)
    ("a" origami-toggle-all-nodes)
    ("t" origami-toggle-node)
    ("o" origami-show-only-node)
    ("u" origami-undo)
    ("r" origami-redo)
    ("R" origami-reset))

  :bind (:map origami-mode-map
              ("C-:" . origami-hydra/body))
  :config
  (face-spec-reset-face 'origami-fold-header-face))

IBUFFER

(global-set-key (kbd "C-x C-b") 'ibuffer)
(setq ibuffer-saved-filter-groups
      (quote (("default"
               ("dired" (mode . dired-mode))
               ("org" (name . "^.*org$"))
               ("magit" (mode . magit-mode))
               ("IRC" (or (mode . circe-channel-mode) (mode . circe-server-mode)))
               ("web" (or (mode . web-mode) (mode . js2-mode)))
               ("shell" (or (mode . eshell-mode) (mode . shell-mode)))
               ("mu4e" (or

                        (mode . mu4e-compose-mode)
                        (name . "\*mu4e\*")
                        ))
               ("programming" (or
                               (mode . clojure-mode)
                               (mode . clojurescript-mode)
                               (mode . python-mode)
                               (mode . c++-mode)))
               ("emacs" (or
                         (name . "^\\*scratch\\*$")
                         (name . "^\\*Messages\\*$")))
               ))))
(add-hook 'ibuffer-mode-hook
          (lambda ()
            (ibuffer-auto-mode 1)
            (ibuffer-switch-to-saved-filter-groups "default")))

;; don't show these
                                        ;(add-to-list 'ibuffer-never-show-predicates "zowie")
;; Don't show filter groups if there are no buffers in that group
(setq ibuffer-show-empty-filter-groups nil)

;; Don't ask for confirmation to delete marked buffers
(setq ibuffer-expert t)

(use-package ibuffer-tramp
  :ensure t)

(use-package ibuffer-projectile
  :after projectile
  :config
  (defun ibuffer-projectile-run ()
    (ibuffer-projectile-set-filter-groups)
    (unless (eq ibuffer-sorting-mode 'alphabetic)
      (ibuffer-do-sort-by-alphabetic)))
  :hook
  (ibuffer . ibuffer-projectile-run)
  :custom
  (ibuffer-projectile-group-name-function
   (lambda (_name root) (abbreviate-file-name root))))

(use-package ibuffer-vc
  :init
  (add-hook 'ibuffer-hook
            (lambda ()
              (ibuffer-vc-set-filter-groups-by-vc-root)
              (unless (eq ibuffer-sorting-mode 'alphabetic)
                (ibuffer-do-sort-by-alphabetic)))))

Treemacs

(use-package treemacs
  :ensure t
  :defer t
  :init
  (with-eval-after-load 'winum
    (define-key winum-keymap (kbd "M-0") #'treemacs-select-window))
  :config
  (progn
    (setq treemacs-collapse-dirs                 (if (executable-find "python3") 3 0)
          treemacs-deferred-git-apply-delay      0.5
          treemacs-display-in-side-window        t
          treemacs-eldoc-display                 t
          treemacs-file-event-delay              5000
          treemacs-file-follow-delay             0.2
          treemacs-follow-after-init             t
          treemacs-git-command-pipe              ""
          treemacs-goto-tag-strategy             'refetch-index
          treemacs-indentation                   2
          treemacs-indentation-string            " "
          treemacs-is-never-other-window         nil
          treemacs-max-git-entries               5000
          treemacs-missing-project-action        'ask
          treemacs-no-png-images                 nil
          treemacs-no-delete-other-windows       t
          treemacs-project-follow-cleanup        nil
          treemacs-persist-file                  (expand-file-name "var/.cache/treemacs-persist" user-emacs-directory)
          treemacs-recenter-distance             0.1
          treemacs-recenter-after-file-follow    nil
          treemacs-recenter-after-tag-follow     nil
          treemacs-recenter-after-project-jump   'always
          treemacs-recenter-after-project-expand 'on-distance
          treemacs-show-cursor                   nil
          treemacs-show-hidden-files             t
          treemacs-silent-filewatch              nil
          treemacs-silent-refresh                nil
          treemacs-sorting                       'alphabetic-desc
          treemacs-space-between-root-nodes      t
          treemacs-tag-follow-cleanup            t
          treemacs-tag-follow-delay              1.5
          treemacs-width                         35)

    ;; The default width and height of the icons is 22 pixels. If you are
    ;; using a Hi-DPI display, uncomment this to double the icon size.
    ;;(treemacs-resize-icons 44)

    (treemacs-follow-mode t)
    (treemacs-filewatch-mode t)
    (treemacs-fringe-indicator-mode t)
    (pcase (cons (not (null (executable-find "git")))
                 (not (null (executable-find "python3"))))
      (`(t . t)
       (treemacs-git-mode 'deferred))
      (`(t . _)
       (treemacs-git-mode 'simple))))
  :bind
  (:map global-map
        ("C-x t t" . treemacs)
        ("M-0"       . treemacs-select-window)
        ("C-x t 1"     . treemacs-delete-other-windows)
        ))


(use-package treemacs-projectile
  :defer t
  :ensure t
  :bind (:map global-map
              ("C-c o p" . treemacs-projectile))
  :config
  (setq treemacs-header-function #'treemacs-projectile-create-header)
  )

(use-package treemacs-icons-dired
  :after treemacs dired
  :ensure t
  :config (treemacs-icons-dired-mode))

(use-package treemacs-magit
  :after treemacs magit
  :ensure t)

(use-package treemacs-evil
  :after treemacs evil
  :ensure t)

;;(define-key treemacs-mode-map [mouse-1] #'treemacs-single-click-expand-action)

(use-package treemacs-persp
  :after treemacs persp-mode
  :ensure t
  :config (treemacs-set-scope-type 'Perspectives))

Aggresive indent

(use-package aggressive-indent
  :defer t
  :ensure t
  :config
  (global-aggressive-indent-mode 1)
  ;;(add-to-list 'aggressive-indent-excluded-modes 'html-mode)
  )

FZF

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

RipGrep

(use-package deadgrep
  :defer t
  :ensure t
  :bind (("C-c d g" . deadgrep))
  :config
  (setq-default deadgrep--search-type 'regexp) ;Default is 'string

  (defun my/deadgrep--jump-to-and-execute (re)
    "Execute the button that matches RE and push it."
    (goto-char (point-min))
    (re-search-forward re)
    (backward-char 3)
    (push-button))

  (defun my/deadgrep-change-search-term ()
    "Change the search term."
    (interactive)
    (my/deadgrep--jump-to-and-execute "^Search term: .*change$"))

  (defun my/deadgrep-change-search-type-to-string ()
    "Change the search type to 'string'."
    (interactive)
    (my/deadgrep--jump-to-and-execute "^Search type: .*string"))

  (defun my/deadgrep-change-search-type-to-words ()
    "Change the search type to 'words'."
    (interactive)
    (my/deadgrep--jump-to-and-execute "^Search type: .*words"))

  (defun my/deadgrep-change-search-type-to-regexp ()
    "Change the search type to 'regexp'."
    (interactive)
    (my/deadgrep--jump-to-and-execute "^Search type: .*regexp"))

  (defun my/deadgrep-change-case-to-smart ()
    "Change the case sensitivity to 'smart'."
    (interactive)
    (my/deadgrep--jump-to-and-execute "^Case: .*smart"))

  (defun my/deadgrep-change-case-to-sensitive ()
    "Change the case sensitivity to 'sensitive'."
    (interactive)
    (my/deadgrep--jump-to-and-execute "^Case: .*sensitive"))

  (defun my/deadgrep-change-case-to-ignore ()
    "Change the case sensitivity to 'ignore'."
    (interactive)
    (my/deadgrep--jump-to-and-execute "^Case: .*ignore"))

  (defun my/deadgrep-change-context-to-none ()
    "Don't show ny context around the search results."
    (interactive)
    (my/deadgrep--jump-to-and-execute "^Context: .*none"))

  (defun my/deadgrep-change-context-to-before ()
    "Set 'before' context for the search results."
    (interactive)
    (my/deadgrep--jump-to-and-execute "^Context: .*before"))

  (defun my/deadgrep-change-context-to-after ()
    "Set 'after' context for the search results."
    (interactive)
    (my/deadgrep--jump-to-and-execute "^Context: .*after"))

  (defun my/deadgrep-change-directory ()
    "Change the root directory for searches."
    (interactive)
    (my/deadgrep--jump-to-and-execute "^Directory: .*$"))

  (defun my/deadgrep-search-all-files ()
    "Change file search scope to 'all'."
    (interactive)
    (my/deadgrep--jump-to-and-execute "^Files: .*all"))

  (defun my/deadgrep-search-files-by-type ()
    "Search only in the specified file types."
    (interactive)
    (my/deadgrep--jump-to-and-execute "^Files: .*type"))

  (defun my/deadgrep-search-files-by-glob ()
    "Search in files names that match the specified glob."
    (interactive)
    (my/deadgrep--jump-to-and-execute "^Files: .*glob"))

  (bind-keys
   :map deadgrep-mode-map
   ("s" . my/deadgrep-change-search-term)
   ("ts" . my/deadgrep-change-search-type-to-string)
   ("tw" . my/deadgrep-change-search-type-to-words)
   ("tr" . my/deadgrep-change-search-type-to-regexp)
   ("cs" . my/deadgrep-change-case-to-smart)
   ("cc" . my/deadgrep-change-case-to-sensitive)
   ("ci" . my/deadgrep-change-case-to-ignore)
   ("xn" . my/deadgrep-change-context-to-none)
   ("xb" . my/deadgrep-change-context-to-before)
   ("xa" . my/deadgrep-change-context-to-after)
   ("d" . my/deadgrep-change-directory)
   ("fa" . my/deadgrep-search-all-files)
   ("ft" . my/deadgrep-search-files-by-type)
   ("fg" . my/deadgrep-search-files-by-glob))
  )

(use-package rg
  :defer t
  :ensure t
  :commands rg)

Easy kill

(use-package easy-kill
  :defer 1
  :ensure t
  :config
  (global-set-key [remap kill-ring-save] #'easy-kill)
  (global-set-key [remap mark-sexp] #'easy-mark))

PATH

(use-package exec-path-from-shell
  :ensure t
  :if (memq window-system '(mac ns))
  :init
  (progn
    (setq exec-path-from-shell-variables '("JAVA_HOME"
                                           "PATH"
                                           "WORKON_HOME"
                                           "MANPATH"))
    (exec-path-from-shell-initialize))
  :config
  (setq exec-path-from-shell-arguments '("-l"))
  (exec-path-from-shell-initialize)
  (exec-path-from-shell-copy-env "LC_ALL")
  (exec-path-from-shell-copy-env "LANG")
  (exec-path-from-shell-copy-env "LC_TYPE")
  (exec-path-from-shell-copy-env "SSH_AGENT_PID")
  (exec-path-from-shell-copy-env "SSH_AUTH_SOCK")
  (exec-path-from-shell-copy-env "SHELL")
  (exec-path-from-shell-copy-env "JAVA_HOME")
  )

;; https://emacs.stackexchange.com/questions/4090/org-mode-cannot-find-pdflatex-using-mac-os

(defun set-exec-path-from-shell-PATH ()
  "Sets the exec-path to the same value used by the user shell"
  (let ((path-from-shell
         (replace-regexp-in-string
          "[[:space:]\n]*$" ""
          (shell-command-to-string "$SHELL -l -c 'echo $PATH'"))))
    (setenv "PATH" path-from-shell)
    (setq exec-path (split-string path-from-shell path-separator))))

;; call function now
(set-exec-path-from-shell-PATH)

(cond ((display-graphic-p)
       ;; A known problem with GUI Emacs on MacOS: it runs in an isolated
       ;; environment, so envvars will be wrong. That includes the PATH
       ;; Emacs picks up. `exec-path-from-shell' fixes this. This is slow
       ;; and benefits greatly from compilation.
       (setq exec-path
             (or (eval-when-compile
                   (when (require 'exec-path-from-shell nil t)
                     (setq exec-path-from-shell-check-startup-files nil)
                     (nconc exec-path-from-shell-variables '("GOPATH" "GOROOT" "PYTHONPATH"))
                     (exec-path-from-shell-initialize)
                     exec-path))
                 exec-path))))

Wgrep

(use-package wgrep
  :defer t
  :ensure t
  )
(use-package wgrep-ag
  :defer t
  :ensure t
  )
(require 'wgrep-ag)

Regex

;;(use-package pcre2el
;;  :ensure t
;;  :config
;;  (pcre-mode)
;;  )

Eyebrowse

(use-package eyebrowse
  :defer t
  :ensure t
  :config
  (eyebrowse-mode)
  )

PDF Tools

(use-package pdf-tools
  :defer 3
  :ensure t
  :config
  (pdf-tools-install)
  (setq-default pdf-view-display-size 'fit-page)
  (bind-keys :map pdf-view-mode-map
             ("\\" . hydra-pdftools/body)
             ("<s-spc>" .  pdf-view-scroll-down-or-next-page)
             ("g"  . pdf-view-first-page)
             ("G"  . pdf-view-last-page)
             ("l"  . image-forward-hscroll)
             ("h"  . image-backward-hscroll)
             ("j"  . pdf-view-next-page)
             ("k"  . pdf-view-previous-page)
             ("e"  . pdf-view-goto-page)
             ("u"  . pdf-view-revert-buffer)
             ("al" . pdf-annot-list-annotations)
             ("ad" . pdf-annot-delete)
             ("aa" . pdf-annot-attachment-dired)
             ("am" . pdf-annot-add-markup-annotation)
             ("at" . pdf-annot-add-text-annotation)
             ("y"  . pdf-view-kill-ring-save)
             ("i"  . pdf-misc-display-metadata)
             ("s"  . pdf-occur)
             ("b"  . pdf-view-set-slice-from-bounding-box)
             ("r"  . pdf-view-reset-slice))
  (use-package org-pdfview
    :ensure t))

(defhydra hydra-pdftools (:color blue :hint nil)
  "
                                                                      ╭───────────┐
       Move  History   Scale/Fit     Annotations  Search/Link    Do   │ PDF Tools │
   ╭──────────────────────────────────────────────────────────────────┴───────────╯
         ^^_g_^^      _B_    ^↧^    _+_    ^ ^     [_al_] list    [_s_] search    [_u_] revert buffer
         ^^^↑^^^      ^↑^    _H_    ^↑^  ↦ _W_ ↤   [_am_] markup  [_o_] outline   [_i_] info
         ^^_p_^^      ^ ^    ^↥^    _0_    ^ ^     [_at_] text    [_F_] link      [_d_] dark mode
         ^^^↑^^^      ^↓^  ╭─^─^─┐  ^↓^  ╭─^ ^─┐   [_ad_] delete  [_f_] search link
    _h_ ←pag_e_→ _l_  _N_  │ _P_ │  _-_    _b_     [_aa_] dired
         ^^^↓^^^      ^ ^  ╰─^─^─╯  ^ ^  ╰─^ ^─╯   [_y_]  yank
         ^^_n_^^      ^ ^  _r_eset slice box
         ^^^↓^^^
         ^^_G_^^
   --------------------------------------------------------------------------------
        "
  ("\\" hydra-master/body "back")
  ("<ESC>" nil "quit")
  ("al" pdf-annot-list-annotations)
  ("ad" pdf-annot-delete)
  ("aa" pdf-annot-attachment-dired)
  ("am" pdf-annot-add-markup-annotation)
  ("at" pdf-annot-add-text-annotation)
  ("y"  pdf-view-kill-ring-save)
  ("+" pdf-view-enlarge :color red)
  ("-" pdf-view-shrink :color red)
  ("0" pdf-view-scale-reset)
  ("H" pdf-view-fit-height-to-window)
  ("W" pdf-view-fit-width-to-window)
  ("P" pdf-view-fit-page-to-window)
  ("n" pdf-view-next-page-command :color red)
  ("p" pdf-view-previous-page-command :color red)
  ("d" pdf-view-dark-minor-mode)
  ("b" pdf-view-set-slice-from-bounding-box)
  ("r" pdf-view-reset-slice)
  ("g" pdf-view-first-page)
  ("G" pdf-view-last-page)
  ("e" pdf-view-goto-page)
  ("o" pdf-outline)
  ("s" pdf-occur)
  ("i" pdf-misc-display-metadata)
  ("u" pdf-view-revert-buffer)
  ("F" pdf-links-action-perfom)
  ("f" pdf-links-isearch-link)
  ("B" pdf-history-backward :color red)
  ("N" pdf-history-forward :color red)
  ("l" image-forward-hscroll :color red)
  ("h" image-backward-hscroll :color red))

(setq pdf-view-use-scaling t)
(require 'pdf-tools)
(require 'org-pdfview)

EditorConfig

(use-package editorconfig
  :defer 3
  :ensure t
  :config
  (editorconfig-mode 1))

Yaml Mode

(use-package yaml-mode
  :defer 1
  :ensure t
  :mode (("\\.yaml\\'" . yaml-mode)
         ("\\.yml\\'" . yaml-mode))
  )

(use-package flycheck-yamllint
  :ensure t
  :defer 3
  :init
  (progn
    (eval-after-load 'flycheck
      '(add-hook 'flycheck-mode-hook 'flycheck-yamllint-setup))))

;;(use-package lsp-yaml
;;  :quelpa (lsp-yaml :fetcher github :repo "iquiw/lsp-yaml")
;;  :after lsp
;;  :config
;;  (add-hook 'yaml-mode-hook #'lsp))


;;(load-if-exists "/Users/ckoneru/.emacs.d/custom-el-scripts/init-lsp-yaml.el")

(use-package yaml-imenu
  :defer 1
  :ensure t
  :init
  (yaml-imenu-enable)
  )

Docker-Mode

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

(use-package docker-tramp
  :defer t
  :ensure t
  )

(use-package dockerfile-mode
  :defer t
  :ensure t
  :mode "Dockerfile[^/]*\\'")

(use-package docker-compose-mode
  :defer t
  :ensure t
  :mode "docker-compose[^/]*\\.yml\\'")

EShell-Enhancements

(use-package esh-autosuggest
  :ensure t
  :disabled t
  :hook (eshell-mode . esh-autosuggest-mode))

(use-package esh-help
  :ensure t
  :defer t
  :config
  (setup-esh-help-eldoc))

(use-package eshell-prompt-extras
  :defer t
  :ensure t
  :after esh-opt
  :custom
  (eshell-prompt-function #'epe-theme-dakrone)
  :config
  (require 'virtualenvwrapper)  ; We want python venv support
  (autoload 'epe-theme-dakrone "eshell-prompt-extras")
  (setq eshell-highlight-prompt nil
        eshell-prompt-function 'epe-theme-dakrone)
  )

;; Show git info in prompt
(use-package eshell-git-prompt
  :ensure t
  :disabled t  ; Use eshell-prompt-extras
  :after eshell
  :config ;;(eshell-git-prompt-use-theme 'powerline)
  ;; XXX: Wait for powerline font https://github.com/powerline/fonts/issues/154
  (eshell-git-prompt-use-theme 'robbyrussell))

(use-package eshell-fringe-status
  :defer t
  :ensure t
  :hook
  (eshell-mode . eshell-fringe-status-mode))

(use-package eshell-did-you-mean
  :defer t
  :ensure t)

(add-to-list 'load-path (expand-file-name "~/.emacs.d/custom-el-scripts/aweshell"))
(require 'aweshell)

;; Increase eshell history size from default of only 128
(setq eshell-history-size 8192)

(use-package eshell-z
  :defer t
  :ensure t
  :after eshell)

(use-package eshell-up
  :defer t
  :ensure t
  :after eshell)

;; Autocomplete for git commands in shell and
;; the git command from magit ('!')
(use-package pcmpl-git
  :ensure t
  :after pcomplete)

(use-package pcmpl-pip
  :defer t
  :ensure t
  :after pcomplete)

(use-package pcmpl-args
  :defer t
  :ensure t
  :after pcomplete)

(use-package pcmpl-homebrew
  :defer t
  :ensure t
  :after pcomplete)

(add-hook 'eshell-mode-hook
          (lambda ()
            (add-to-list 'eshell-visual-commands "ssh")
            (add-to-list 'eshell-visual-commands "tail")
            (add-to-list 'eshell-visual-commands "top")))

(add-hook 'eshell-mode-hook (lambda ()
                              (eshell/alias "e" "find-file $1")
                              (eshell/alias "ff" "find-file $1")
                              (eshell/alias "emacs" "find-file $1")
                              (eshell/alias "ee" "find-file-other-window $1")

                              (eshell/alias "gd" "magit-diff-unstaged")
                              (eshell/alias "gds" "magit-diff-staged")
                              (eshell/alias "d" "dired $1")
                              ;; The 'ls' executable requires the Gnu version on the Mac
                              (let ((ls (if (file-exists-p "/usr/local/bin/gls")
                                            "/usr/local/bin/gls"
                                          "/bin/ls")))
                                (eshell/alias "ll" (concat ls " -AlohG --color=always")))
                              ))

;;(defun eshell/eshell-host->tramp (username hostname &optional prefer-root)
;;  "Returns a TRAMP reference based on a USERNAME and HOSTNAME
;;that refers to any host or IP address."
;;  (cond ((string-match-p "^/" host)
;;         host)
;;        ((or (and prefer-root (not username)) (equal username "root"))
;;         (format "/ssh:%s|sudo:%s:" hostname hostname))
;;        ((or (null username) (equal username user-login-name))
;;         (format "/ssh:%s:" hostname))
;;        (t
;;         (format "/ssh:%s|sudo:%s|sudo@%s:%s:" hostname hostname username hostname)));;)

(add-hook 'eshell-mode-hook
          (lambda ()
            (bind-keys :map eshell-mode-map
                       ("C-r" . counsel-esh-history))))

(add-hook 'eshell-mode-hook (lambda () (linum-mode -1)))

(evil-set-initial-state 'eshell-mode 'emacs)

(add-hook 'eshell-mode-hook (lambda () (linum-relative-mode -1)))

(use-package eshell-toggle
  :custom
  (eshell-toggle-size-fraction 3)
  (eshell-toggle-use-projectile-root t)
  (eshell-toggle-run-command nil)
  (eshell-toggle-init-function #'eshell-toggle-init-eshell)
  :quelpa
  (eshell-toggle :repo "4DA/eshell-toggle" :fetcher github :version original)
  :bind
  ("s-`" . eshell-toggle))

(use-package eshell-up
  :ensure t)

;; TODO - Do not use it until a '.bash_aliases' file is crated
;;(use-package load-bash-alias
;;  :ensure t
;;  :config
;;  (setq load-bash-alias-bashrc-file "~/.bashrc")
;;  (setq load-bash-alias-exclude-aliases-regexp "^alias magit\\|^alias oc"))

Groovy

(use-package groovy-mode
  :defer t
  :ensure t
  :config
  (add-to-list 'auto-mode-alist '("\\.g\\(?:ant\\|roovy\\)\\'" . groovy-mode))
  (add-to-list 'auto-mode-alist '("Jenkinsfile" . groovy-mode))
  (add-to-list 'auto-mode-alist '("Jenkinsfile\\'" . groovy-mode)))

(use-package groovy-imports :ensure t)
(use-package flycheck-gradle
  :ensure t
  :defer t)

;;(load-if-exists "~/.emacs.d/custom-el-scripts/lsp-groovy.el")

;;(require 'lsp-mode)

;;(require 'lsp-groovy)
(setq lsp-server-install-dir (concat user-emacs-directory "custom-el-scripts/lsp/")
      lsp-groovy-server-file (concat lsp-server-install-dir "groovy-language-server/build/libs/groovy-language-server-all.jar")
      )

;;(add-hook 'groovy-mode-hook 'lsp)

Duplicate Things

(use-package duplicate-thing
  :defer t
  :bind ("H-C-e d" . duplicate-thing)
  :ensure t)

Custom Utils

(setq custom-file "/Users/ckoneru/.emacs.d/custom-el-scripts/custom-util-function.el")
(when (file-exists-p custom-file)
  (load custom-file))

Ensime/Scala/Sbt

;;(use-package ensime
;;  :ensure t
;;  :pin melpa)
;;
;;(use-package sbt-mode
;;  :ensure t
;;  :pin melpa)
;;
;;(use-package scala-mode
;;  :ensure t
;;  :pin melpa)


;; Enable scala-mode and sbt-mode
(use-package scala-mode
  :defer 3
  :ensure t
  :mode "\\.s\\(cala\\|bt\\)$")

(use-package sbt-mode
  :defer 3
  :ensure t
  :commands sbt-start sbt-command
  :config
  ;; WORKAROUND: https://github.com/ensime/emacs-sbt-mode/issues/31
  ;; allows using SPACE when in the minibuffer
  (substitute-key-definition
   'minibuffer-complete-word
   'self-insert-command
   minibuffer-local-completion-map))

;; Enable nice rendering of diagnostics like compile errors.
;;(use-package flycheck
;;  :defer t
;;  :ensure t
;;  :init (global-flycheck-mode))

;;; Config for Eglot

;; Enable scala-mode and sbt-mode
;;(use-package scala-mode
;;  :mode "\\.s\\(cala\\|bt\\)$")
;;
;;(use-package sbt-mode
;;  :commands sbt-start sbt-command
;;  :config
;;  ;; WORKAROUND: https://github.com/ensime/emacs-sbt-mode/issues/31
;;  ;; allows using SPACE when in the minibuffer
;;  (substitute-key-definition
;;   'minibuffer-complete-word
;;   'self-insert-command
;;   minibuffer-local-completion-map))
;;
;;(use-package eglot
;;  :pin melpa-stable
;;  :config
;;  (add-to-list 'eglot-server-programs '(scala-mode . ("metals-emacs")))
;;  ;; (optional) Automatically start metals for Scala files.
;;  :hook (scala-mode . eglot-ensure))

Java

(load-if-exists "/Users/ckoneru/.emacs.d/custom-el-scripts/init-java.el")

Languaues

;;(add-to-list 'load-path (concat user-emacs-directory "custom-el-scripts/languages"))

(load-if-exists "~/.emacs.d/custom-el-scripts/languages/go-dlv.el")
(load-if-exists "~/.emacs.d/custom-el-scripts/languages/lang-go.el")
;;(load-if-exists "./custom-el-scripts/languages/lang-ruby.el")
;;(load-if-exists "./custom-el-scripts/languages/lang-php.el")
;;(load-if-exists "./custom-el-scripts/languages/lang-javascript.el")
;;(load-if-exists "./custom-el-scripts/languages/lang-web.el")
;;(load-if-exists "./custom-el-scripts/languages/lang-rust.el")

;;(require 'lang-ruby)

(require 'lang-go)

;;(require 'lang-php)

;;(require 'lang-javascript)

;;(require 'lang-web)

;;(require 'lang-rust)

;;(require 'lang-c)

Hive-Mode

(load-if-exists "/Users/ckoneru/.emacs.d/custom-el-scripts/init-hive.el")

Save Place/ Recentf/ PBCOPY

;; History
(use-package saveplace
  :defer t
  :ensure nil
  :hook (after-init . save-place-mode))

;; Recent files
(use-package recentf
  :defer t
  :ensure nil
  :hook (after-init . recentf-mode)
  :custom
  (recentf-max-saved-items 20000000)
  (recentf-auto-cleanup 'never)
  (recentf-exclude '((expand-file-name package-user-dir)
                     ".cache"
                     "cache"
                     "recentf"
                     "COMMIT_EDITMSG\\'"))
  :preface
  (defun my/recentf-save-list-silence ()
    (interactive)
    (let ((message-log-max nil))
      (if (fboundp 'shut-up)
          (shut-up (recentf-save-list))
        (recentf-save-list)))
    (message ""))
  (defun my/recentf-cleanup-silence ()
    (interactive)
    (let ((message-log-max nil))
      (if shutup-p
          (shut-up (recentf-cleanup))
        (recentf-cleanup)))
    (message ""))
  :hook
  (focus-out-hook . (my/recentf-save-list-silence my/recentf-cleanup-silence)))

(when (eq system-type 'darwin)            ; Better copy paste on mac
  (use-package pbcopy
    :defer t
    :ensure t
    :config (turn-on-pbcopy)))

AG - The silver searcher

(use-package ag
  :defer t
  :ensure t
  :custom
  (ag-highligh-search t)
  (ag-reuse-buffers t)
  (ag-reuse-window t)
  :bind
  ("H-M-p a" . ag-project)
  :config
  (use-package wgrep-ag))

MWIM

(use-package mwim
  :defer t
  :ensure t
  :bind
  ("H-C-g a" . mwim-beginning-of-code-or-line)
  ("H-C-g e" . mwim-end-of-code-or-line))

Dashboard

(use-package dashboard
  :ensure t
  :diminish
  (dashboard-mode page-break-lines-mode)
  :custom
  (dashboard-center-content t)
  (dashboard-startup-banner 'logo)
  (dashboard-items '((recents . 15)
                     (projects . 5)
                     (bookmarks . 5)))
  :custom-face
  (dashboard-heading ((t (:foreground "#f1fa8c" :weight bold))))
  :hook
  (after-init . dashboard-setup-startup-hook))

Dimmer

(use-package dimmer
  :ensure t
  :unless noninteractive
  ;;:disabled
  :custom
  (dimmer-fraction 0.2)
  ;;(dimmer-exclusion-regexp-list
  ;; '(".*Minibuf.*"
  ;;   ".*which-key.*"
  ;;   ".*Messages.*"
  ;;   ".*Async.*"
  ;;   ".*Warnings.*"
  ;;   ".*LV.*"
  ;;   ".*Ilist.*")
  ;; )
  :config
  (dimmer-mode t))

Bicycle - Cycle outline and code visibility

(use-package bicycle
  :defer t
  :after outline
  :bind (:map outline-minor-mode-map
              ([C-tab] . bicycle-cycle)
              ([S-tab] . bicycle-cycle-global)))

;;(use-package prog-mode
;;:config
(add-hook 'prog-mode-hook 'outline-minor-mode)
(add-hook 'prog-mode-hook 'hs-minor-mode)
;;)

Rainbow

(use-package rainbow-delimiters
  :defer t
  :ensure t
  :hook
  (prog-mode . rainbow-delimiters-mode)
  :config
  (set-face-attribute 'rainbow-delimiters-unmatched-face nil
                      :foreground "red"
                      :inherit 'error
                      :box t))

Kubernates

(use-package kubernetes
  :defer 3
  :ensure t
  :commands (kubernetes-overview))

;; If you want to pull in the Evil compatibility package.
(use-package kubernetes-evil
  :defer 3
  :ensure t
  :after kubernetes)

(use-package k8s-mode
  :defer 3
  :ensure t
  :hook (k8s-mode . yas-minor-mode)
  :config
  ;;(setq k8s-search-documentation-browser-function 'browse-url-firefox)
  (setq k8s-site-docs-url "https://kubernetes.io/docs/reference/generated/kubernetes-api/")
  (setq k8s-site-docs-version "v1.13")
  )

(add-hook 'k8s-mode-hook 'yas-minor-mode)

(use-package kubernetes-tramp
  :defer 3
  :ensure t)

(use-package kubernetes-helm
  :defer 3
  :ensure t)

(use-package kubel
  :defer 3
  :ensure t)

(use-package kubel-evil
  :defer 3
  :ensure t)

Json

;;; Languages
(use-package js2-mode                   ; Javascript
  :defer 3
  :ensure t
  :mode (("\\.jsx?\\'" . js2-mode))
  :commands (j2-mode))

(use-package json-mode                  ; JSON
  :defer 3
  :ensure t
  :mode (("\\.json\\'" . json-mode))
  :commands (json-mode))

(use-package json-navigator
  :defer 3
  :ensure t)

(use-package web-beautify
  :defer 3
  :ensure t)

(use-package json-reformat
  :defer 3
  :ensure t)

Csv Mode

(use-package csv-mode
  :defer 3
  :ensure t
  :mode "\\.[Cc][Ss][Vv]\\'"
  :init

  ;; Use for *.tsv files.
  ;; TODO: set `csv-separators' buffer-locally instead of globally.
  (defun my-tsv-in-csv-mode ()
    (csv-mode)
    (custom-set-variables '(csv-separators '("\t")))) ; We can't use `setq' because the `:set' hook wouldn't be run.
  (add-to-list 'auto-mode-alist '("\\.tsv\\'" . my-tsv-in-csv-mode))
  :config
  ;;(setq csv-separators '("," ";" "|" "    "))
  (progn
    (setq csv-separators '("," ";" "|" "\t"))
    )
  )

(setq csv-separators '("," ";" "|" "\t"))
(setq csv-align-padding 2)
;;(setq csv-field-quotes '("\"" "'"))
(setq csv-header-lines 1)
(require 'csv-mode)

;;(add-to-list 'auto-mode-alist '("\\.[Tt][Ss][Vv]\\'" . csv-mode))
;;
;;(add-hook 'csv-mode-hook
;;          (lambda ()
;;            (if (equal (file-name-extension buffer-file-name) "tsv")
;;                (setq-local csv-separators '("\t" "," "|"))
;;              (setq-local csv-separators '("," "\t" "|")))))
;;
;;(defun csv-separators-toggle ()
;;  (interactive)
;;  (cond ((equal (car csv-separators) ",")
;;         (setq-local csv-separators '("\t" "," "|"))
;;         (message "Separator -> TAB"))
;;        (t
;;         (setq-local csv-separators '("," "\t" "|"))
;;         (message "Separator -> ,"))))

Indentation-tools

(use-package indent-tools
  :defer t
  :ensure t
  :bind
  ("C-c h i" . indent-tools-hydra/body))

Move-text

(use-package move-text
  :defer 1
  :ensure t
  :bind
  (("M-<up>" . move-text-up)
   ("M-<down>" . move-text-down)))

Quick-run

(use-package quickrun
  :defer 1
  :ensure t
  :bind
  (("<f7>r r" . quickrun)
   ("<f7>r c". quickrun-compile-only)))

(defhydra my/hydra-quickrun (:color blue
                                    :hint nil)
  "
 _s_: quickrun     _a_: with arg    _c_: compile only       _q_: quit
 _r_: run region   _S_: shell       _R_: replace region
"
  ("s" quickrun)
  ("r" quickrun-region)
  ("a" quickrun-with-arg)
  ("S" quickrun-shell)
  ("c" quickrun-compile-only)
  ("R" quickrun-replace-region)
  ("q" nil :color blue))

(bind-keys*
 ("M-m s q" . my/hydra-quickrun/body))

Auto-update packages

(use-package auto-package-update
  :defer t
  :ensure t
  :config
  (setq auto-package-update-delete-old-versions t)
  (setq auto-package-update-hide-results t)
  (auto-package-update-maybe))

Evil-numbers

(use-package evil-numbers
  :defer 2
  :ensure t)

(global-set-key (kbd "C-c C-i +") 'evil-numbers/inc-at-pt)
(global-set-key (kbd "C-c C-i -") 'evil-numbers/dec-at-pt)

(define-key evil-normal-state-map (kbd "C-c C-i +") 'evil-numbers/inc-at-pt)
(define-key evil-normal-state-map (kbd "C-c C-i -") 'evil-numbers/dec-at-pt)

Evil Lion mode

;; See Doc - https://github.com/edkolev/evil-lion
(use-package evil-lion
  :defer 1
  :ensure t
  :config
  (evil-lion-mode)
  :bind (:map evil-normal-state-map
         ("g l " . evil-lion-left)
         ("g L " . evil-lion-right)
         :map evil-visual-state-map
         ("g l " . evil-lion-left)
         ("g L " . evil-lion-right)))

Evil Exchange

(use-package evil-exchange
  :defer 1
  :ensure t)

Evil-goggles

(use-package evil-goggles
  :defer t
  :ensure t
  :config
  (evil-goggles-mode)

  ;; optionally use diff-mode's faces; as a result, deleted text
  ;; will be highlighed with `diff-removed` face which is typically
  ;; some red color (as defined by the color theme)
  ;; other faces such as `diff-added` will be used for other actions
  (evil-goggles-use-diff-faces)
  )

Evil-org

(use-package evil-org
  :defer t
  :ensure t
  :after org
  :config
  (add-hook 'org-mode-hook 'evil-org-mode)
  (add-hook 'evil-org-mode-hook
            (lambda ()
              (evil-org-set-key-theme)))
  (require 'evil-org-agenda)
  (evil-org-agenda-set-keys))

Goto last change

(use-package goto-chg
  :defer 1
  :ensure t
  :bind* (("M-m g ;" . goto-last-change)
          ("M-m g ," . goto-last-change-reverse)))

Ztree

(use-package ztree
  :defer 1
  :ensure t
  :bind* (("M-m g v" . ztree-dir)
          ("M-m g V" . ztree-diff))
  :init
  (setq ztree-dir-move-focus t))

GG_Tags

(use-package ggtags
  :defer 1
  :ensure t
  :diminish ggtags-mode
  :bind* (("M-m T"   . ggtags-find-tag-regexp)
          ("M-m g t" . ggtags-create-tags)
          ("M-m g T" . ggtags-update-tags))
  :init
  (setq-local imenu-create-index-function #'ggtags-build-imenu-index)
  :config
  (add-hook 'prog-mode-hook 'ggtags-mode))

(use-package counsel-gtags
  :ensure t
  :commands counsel-gtags-mode
  :bind (:map
         counsel-gtags-mode-map
         ("M-." . counsel-gtags-dwim)
         ("M-," . counsel-gtags-go-backward))
  ;;:hook (
  ;;(swift-mode . counsel-gtags-mode)
  ;;(swift-mode . ggtags-mode)
  ;;)
  )

Commenting

(use-package comment-dwim-2
  :defer 1
  :ensure t
  :bind* (("M-m g c" . comment-dwim-2)))

Cycle-quotes

(use-package cycle-quotes
  :defer 1
  :ensure t
  :bind* (("M-m s q" . cycle-quotes)))

(which-key-add-key-based-replacements
  "s q" "switch quotes")

Highlight Indentation

(use-package highlight-indentation
  :defer t
  :ensure t
  :commands (highlight-indentation-mode)
  :config
  ;;(set-face-background 'highlight-indentation-face "#ffe39f")
  (set-face-background 'highlight-indentation-current-column-face "#f1c40f")
  )

;; highlight indentations in python
(use-package highlight-indent-guides
  :defer t
  :ensure t
  :init (setq highlight-indent-guides-responsive 'stack)
  :hook
  ((prog-mode yaml-mode) . highlight-indent-guides-mode)
  :custom
  (highlight-indent-guides-auto-enabled t)
  :config
  ;; Don't highlight first level (that would be a line at column 1)
  (defun my-highlighter (level responsive display)
    (if (> 1 level) ; replace `1' with the number of guides you want to hide
        nil
      (highlight-indent-guides--highlighter-default level responsive display)))

  (setq highlight-indent-guides-highlighter-function 'my-highlighter)
  (setq highlight-indent-guides-method 'character)
  (setq highlight-indent-guides-character ?\|)
  (setq highlight-indent-guides-auto-odd-face-perc 15)
  (setq highlight-indent-guides-auto-even-face-perc 15)
  (setq highlight-indent-guides-auto-character-face-perc 20)
  )


(add-hook 'python-mode 'highlight-indent-guides-mode)
(add-hook 'yaml-mode 'highlight-indent-guides-mode)
(add-hook 'k8s-mode 'highlight-indent-guides-mode)

(add-hook 'python-mode 'highlight-indentation-current-column-mode)
(add-hook 'yaml-mode 'highlight-indentation-current-column-mode)
(add-hook 'k8s-mode 'highlight-indentation-current-column-mode)

(add-hook 'prog-mode-hook 'highlight-indent-guides-mode)
(add-hook 'prog-mode-hook 'highlight-indentation-current-column-mode)

Region State

(use-package region-state
  :defer t
  :ensure t
  :config
  (region-state-mode))

Google This

(use-package google-this
  :defer 2
  :ensure t
  :commands (google-this-word
             google-this-region
             google-this-symbol
             google-this-clean-error-string
             google-this-line
             google-this-search
             google-this-cpp-reference))

(defun my/google-this ()
  "Google efficiently"
  (interactive)
  (if (region-active-p)
      (google-this-region 1)
    (google-this-symbol 1)))

(bind-keys*
  ("M-m A" . my/google-this))

(defhydra my/hydra-google (:color blue
                           :hint nil)
  "
 _w_: word   _r_: region    _v_: symbol   _l_: line
 _g_: google _c_: cpp       _s_: string   _q_: quit
 "
  ("w" google-this-word)
  ("r" google-this-region)
  ("v" google-this-symbol)
  ("s" google-this-clean-error-string)
  ("l" google-this-line)
  ("g" google-this-search)
  ("c" google-this-cpp-reference)
  ("q" nil :color blue))

(bind-keys*
  ("M-m g G" . my/hydra-google/body))

browse-at-remote

(use-package browse-at-remote
  :defer 3
  :ensure t
  :bind* (("M-m g i" . browse-at-remote)
          ("M-m g I" . browse-at-remote-kill)))

discover-my-major

(use-package discover-my-major
  :defer t
  :ensure t
  :bind (("C-h C-m" . discover-my-major)
         ("C-h M-m" . discover-my-mode)))

Memory usage

(use-package memory-usage               ; Analyse the memory usage of Emacs
  :defer t
  :ensure t
  :commands (memory-usage))

FAPP

(use-package ffap                       ; Find files at point
  :bind ("C-c f p" . ffap)
  :config (setq ffap-machine-p-known 'reject))

LogView

(use-package logview
  :defer t
  :ensure t
  :mode ("syslog\\(?:\\.[0-9]+\\)" "\\.log\\(?:\\.[0-9]+\\)?\\'")
  :config
  (setq datetime-timezone 'UTC
        logview-additional-level-mappings '(("ICP"
                                             (error       "ERROR")
                                             (warning     "WARNING")
                                             (information "INFO")
                                             (debug       "DEBUG")
                                             (trace       "TRACE")))
        logview-additional-timestamp-formats '(("easyloggingpp" (java-pattern . "HH:mm:ss,SSS")))
        logview-additional-submodes '(("ICP" . ((format . "TIMESTAMP LEVEL ")
                                                (levels . "ICP")
                                                (timestamp . ("easyloggingpp"))))))
  )

Paradox

(use-package paradox
  :ensure t
  :defer t
  :config
  (setq paradox-spinner-type 'progress-bar
        paradox-execute-asynchronously t))

snapshot-timemachine

;;(use-package snapshot-timemachine
;;  :ensure t
;;  :init

  ;; Default Backup directory
  ;;Commenting as handled by no-litttering package
  ;;(defvar backup-directory "~/.emacs.d/var/backups/")
  ;;(setq backup-directory-alist `((".*" . ,backup-directory)))

  ;;(when (not (file-exists-p backup-directory))
  ;;  (make-directory backup-directory t))

  ;; Auto-save
  (defvar auto-save-directory "~/.emacs.d/var/auto-save/")
  (setq auto-save-file-name-transforms `((".*" ,auto-save-directory t)))

  (when (not (file-exists-p auto-save-directory))
    (make-directory auto-save-directory t))

  ;; Tramp backup
  (defvar tramp-backup-directory "~/.emacs.d/var/tramp-backups/")
  (setq tramp-backup-directory-alist `((".*" . ,tramp-backup-directory)))

  (when (not (file-exists-p tramp-backup-directory))
    (make-directory tramp-backup-directory t))

  (setq make-backup-files t               ; backup of a file the first time it is saved.
        backup-by-copying t               ; don't clobber symlinks
        version-control t                 ; version numbers for backup files
        delete-old-versions t             ; delete excess backup files silently
        delete-by-moving-to-trash t
        kept-old-versions 6               ; oldest versions to keep when a new numbered backup is made (default: 2)
        kept-new-versions 9               ; newest versions to keep when a new numbered backup is made (default: 2)
        auto-save-default t               ; auto-save every buffer that visits a file
        auto-save-timeout 60              ; number of seconds idle time before auto-save (default: 30)
        auto-save-interval 600            ; number of keystrokes between auto-saves (default: 300)
        )

 ;; :config

 ;; (defun snapshot-timemachine-backup-finder (file)
 ;;   "Find snapshots of FILE in rsnapshot backups."
 ;;   (let* ((file (expand-file-name file))
 ;;          (file-adapted (replace-regexp-in-string "/" "!" file))
 ;;          (backup-files(directory-files backup-directory t (format "%s.*" file-adapted))))
 ;;     (seq-map-indexed (lambda (backup-file index)
 ;;                        (make-snapshot :id index
 ;;                                       :name (format "%d" index)
 ;;                                       :file backup-file
 ;;                                       :date (nth 5 (file-attributes backup-file))))
 ;;                      backup-files)))

 ;; (setq snapshot-timemachine-snapshot-finder #'snapshot-timemachine-backup-finder))

;;(require 'snapshot-timemachine)

XML

(use-package nxml-mode
  ;;:disabled
  :ensure nil
  :no-require t
  :mode ("\\.xml$" . nxml-mode)
  :commands (pretty-print-xml-region)
  :defer t
  :init
  ;; Mapping xml to nxml
  (fset 'xml-mode 'nxml-mode)

  :config

  ;; Global configuration
  (setq nxml-child-indent 2
        nxml-auto-insert-xml-declaration-flag t
        nxml-slash-auto-complete-flag t
        nxml-bind-meta-tab-to-complete-flag t)

  ;; Outline hook
  (add-hook 'nxml-mode-hook
            (lambda ()
              (outline-minor-mode)
              (setq outline-regexp "^[ \t]*\<[a-zA-Z]+")))

  ;; Helper to format
  (defun my/pretty-print-xml-region (begin end)
    "Pretty format XML markup in region. You need to have nxml-mode
 http://www.emacswiki.org/cgi-bin/wiki/NxmlMode installed to do
 this.  The function inserts linebreaks to separate tags that have
 nothing but whitespace between them.  It then indents the markup
 by using nxml's indentation rules."
    (interactive "r")
    (save-excursion
      (nxml-mode)
      (goto-char begin)
      (while (search-forward-regexp "\>[ \\t]*\<" nil t)
        (backward-char) (insert "\n"))
      (indent-region begin end))))

;; had to use absolute path for this to work.
(setq lsp-xml-jar-file "/Users/ckoneru/.emacs.d/custom-el-scripts/lsp/org.eclipse.lsp4xml-0.3.0-uber.jar")
;;(add-hook 'nxml-mode-hook 'lsp)

Gradle

(use-package gradle-mode
  :defer t
  :ensure t
  :config
  (setq gradle-gradlew-executable "./gradlew"
        gradle-use-gradlew t)
  (gradle-mode))

(use-package flycheck-gradle
  :defer t
  :ensure t
  :commands (flycheck-gradle-setup)
  :init
  (mapc
   (lambda (x)
     (add-hook x #'flycheck-gradle-setup))
   '(java-mode-hook kotlin-mode-hook)))

Winnow

(use-package winnow
  :defer t
  :ensure t
  :init
  (add-hook 'compilation-mode-hook 'winnow-mode)
  (add-hook 'ag-mode-hook 'winnow-mode))

Images

(use-package image+
  :defer t
  :ensure t
  :init
  (add-hook 'image-mode-hook
            '(lambda ()
               (require 'image+)
               (imagex-sticky-mode)))

  :bind (:map image-mode-map
              ("=" . imagex-sticky-zoom-in)
              ("-" . imagex-sticky-zoom-out)
              ("m" . imagex-sticky-maximize)
              ("g" . imagex-sticky-restore-original)
              ("S" . imagex-sticky-save-image)
              ("r" . imagex-sticky-rotate-right)
              ("l" . imagex-sticky-rotate-left)
              ("/" . imagex-sticky-binding/body))

  :config
  (defhydra imagex-sticky-binding () ;; global-map "C-x C-l"
    "Manipulating Image"
    ("+" imagex-sticky-zoom-in "zoom in")
    ("-" imagex-sticky-zoom-out "zoom out")
    ("M" imagex-sticky-maximize "maximize")
    ("O" imagex-sticky-restore-original "restore original")
    ("S" imagex-sticky-save-image "save file")
    ("r" imagex-sticky-rotate-right "rotate right")
    ("l" imagex-sticky-rotate-left "rotate left")))

(eval-after-load 'image+ '(imagex-global-sticky-mode 1))

System Monitoring

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

Page-break-lines

(use-package page-break-lines
  :defer t
  :ensure t
  :diminish page-break-lines-mode
  :config
  (global-page-break-lines-mode t))

BM–For Bookmarks

(use-package bm
  :ensure t
  :defer t
  :demand t

  :init
  ;; restore on load (even before you require bm)
  (setq bm-restore-repository-on-load t)


  :config
  ;; Allow cross-buffer 'next'
  (setq bm-cycle-all-buffers t)

  ;; where to store persistant files
  ;;(setq bm-repository-file "~/.emacs.d/var/bm-repository");; handled by no-littering package

  ;; save bookmarks
  (setq-default bm-buffer-persistence t)

  ;; Loading the repository from file when on start up.
  (add-hook 'after-init-hook 'bm-repository-load)

  ;; Saving bookmarks
  (add-hook 'kill-buffer-hook #'bm-buffer-save)

  ;; Saving the repository to file when on exit.
  ;; kill-buffer-hook is not called when Emacs is killed, so we
  ;; must save all bookmarks first.
  (add-hook 'kill-emacs-hook #'(lambda nil
                                 (bm-buffer-save-all)
                                 (bm-repository-save)))

  ;; The `after-save-hook' is not necessary to use to achieve persistence,
  ;; but it makes the bookmark data in repository more in sync with the file
  ;; state.
  (add-hook 'after-save-hook #'bm-buffer-save)

  ;; Restoring bookmarks
  (add-hook 'find-file-hooks   #'bm-buffer-restore)
  (add-hook 'after-revert-hook #'bm-buffer-restore)

  ;; The `after-revert-hook' is not necessary to use to achieve persistence,
  ;; but it makes the bookmark data in repository more in sync with the file
  ;; state. This hook might cause trouble when using packages
  ;; that automatically reverts the buffer (like vc after a check-in).
  ;; This can easily be avoided if the package provides a hook that is
  ;; called before the buffer is reverted (like `vc-before-checkin-hook').
  ;; Then new bookmarks can be saved before the buffer is reverted.
  ;; Make sure bookmarks is saved before check-in (and revert-buffer)
  (add-hook 'vc-before-checkin-hook #'bm-buffer-save)


  ;; :bind (("H-b n" . bm-next)
  ;;        ("H-b p" . bm-previous)
  ;;        ("H-b b" . bm-toggle))


  (bind-key "C-c h b"
            (defhydra hydra-bm (:color pink
                                       :hint nil
                                       :body-pre (when (not (use-region-p))
                                                   (push-mark)))
              "
Bookmark  _n_ext (_N_ in lifo order)            _b_ toggle bookmark        _l_ bm list                                            _s_ toggle persistence
          _p_revious (_P_ in lifo order)        _a_nnotate               _x_/_X_ remove all bm from current/all buffer(s)
          show _A_nnotation                     _M_ toggle bookmark       _L_ bm list all
"
              ("b"   bm-toggle)
              ("M"   bm-toggle :color blue)
              ("a"   bm-bookmark-annotate :color blue)
              ("A"   bm-bookmark-show-annotation)
              ("n"   bm-common-next)
              ("N"   bm-lifo-next)
              ("l"   bm-show)
              ("L"   bm-show-all)
              ("p"   bm-common-previous)
              ("P"   bm-lifo-previous)
              ("s"   bm-toggle-buffer-persistence)
              ("x"   bm-remove-all-current-buffer :color blue)
              ("X"   bm-remove-all-all-buffers :color blue)
              ("r"   pop-to-mark-command :color blue)
              ("RET" nil "cancel" :color blue)
              ("q"   nil "cancel" :color blue)))
  )

Hide-Show

(use-package hideshow
  :defer t
  :bind (("C-c TAB" . hs-toggle-hiding)
         ("C-\\" . hs-toggle-hiding)
         ("M-+" . hs-show-all))
  :init (add-hook #'prog-mode-hook #'hs-minor-mode)
  :diminish hs-minor-mode
  :config
  (setq hs-special-modes-alist
        (mapcar 'purecopy
                '((c-mode "{" "}" "/[*/]" nil nil)
                  (c++-mode "{" "}" "/[*/]" nil nil)
                  (java-mode "{" "}" "/[*/]" nil nil)
                  (js-mode "{" "}" "/[*/]" nil)
                  (json-mode "{" "}" "/[*/]" nil)
                  (javascript-mode  "{" "}" "/[*/]" nil)))))

HL-ANYTHING

(use-package hl-anything
  :defer t
  :ensure t
  :diminish hl-highlight-mode
  :commands hl-highlight-mode
  )

Cool-Moves

;;(use-package cool-moves
;;  :load-path "~/.emacs.d/cool-moves")

(add-to-list 'load-path "~/.emacs.d/custom-el-scripts/cool-moves")
(load "cool-moves")

Subword: CamelCase aware editing operations

(use-package subword
  :defer t
  :ensure t
  :hook ((python-mode yaml-mode go-mode clojure-mode cider-repl-mode java-mode cds-mode js2-mode) . subword-mode))

EWW

(use-package eww
  :ensure t
  :defer t
  :config
  (add-hook 'eww-mode-hook 'visual-line-mode)
  (setq eww-header-line-format nil
        shr-width 80
        shr-use-fonts nil
        shr-color-visible-distance-min 10
        shr-color-visible-luminance-min 80))

;; org-eww is replaced by ol-eww.el in org-contrib
;;(load-if-exists "~/.emacs.d/custom-el-scripts/org-eww.el")
;;(require 'org-eww)

Shr: Simple html renderer

(use-package shr
  :ensure t
  :defer t
  :config
  (setq shr-width 80)
  (setq shr-external-browser 'eww-browse-url)
  (setq shr-color-visible-luminance-min 80))

Hl-todo: Highlight and navigate TODO keywords

(use-package hl-todo
  :ensure t
  :defer 2
  :config (global-hl-todo-mode))

Automatically remove trailing whitespace (only if I put them there)

(use-package ws-butler
  :defer 2
  :ensure t
  :hook ((text-mode prog-mode) . ws-butler-mode)
  :config (setq ws-butler-keep-whitespace-before-point nil))

CRUX

(use-package crux
  :defer t
  :ensure t
  :bind (("C-c o" . crux-open-with)
         ("C-a" . crux-move-beginning-of-line)))

zop-to-char: Remove multiple characters at once

;; Replace zap-to-char functionaity with the more powerful zop-to-char
(use-package zop-to-char
  :defer t
  :ensure t
  :bind (("M-z" . zop-up-to-char)
         ("M-Z" . zop-to-char)))

Visual-regex:

(use-package visual-regexp
  :defer t
  :ensure t
  :bind (:map mode-specific-map
              :prefix-map visual-regexp-prefix-map
              :prefix "r"
              ("r" . vr/query-replace)
              ("R" . vr/replace)
              ))

(use-package visual-regexp-steroids
  :after visual-regexp
  )

;;; Query exchange
;; Inspired from http://www.emacswiki.org/emacs/QueryExchange and definition of
;; `query-replace-regexp' from replace.el
(defun query-exchange (string-1 string-2 &optional delimited start end)
  "Exchange string-1 and string-2 interactively.
The user is prompted at each instance like query-replace. Exchanging
happens within a region if one is selected."
  (interactive
   (let ((common
          (query-replace-read-args
           (concat "Query replace"
                   (if current-prefix-arg " word" "")
                   " regexp"
                   (if (and transient-mark-mode mark-active) " in region" ""))
           t)))
     (list (nth 0 common) (nth 1 common) (nth 2 common)
           ;; These are done separately here
           ;; so that command-history will record these expressions
           ;; rather than the values they had this time.
           (if (and transient-mark-mode mark-active)
               (region-beginning))
           (if (and transient-mark-mode mark-active)
               (region-end)))))
  (perform-replace
   (concat "\\(" string-1 "\\)\\|" string-2)
   '(replace-eval-replacement replace-quote
                              (if (match-string 1) string-2 string-1))
   t t delimited nil nil start end))

Imenu

(use-package imenu
  :ensure t
  :defer t
  ;;:hook (emacs-lisp-mode . imenu-use-package)
  :config
  ;; Recenter window after imenu jump so cursor doesn't end up on the last line
  (add-hook 'imenu-after-jump-hook 'recenter)  ; or 'reposition-window
  (set-default 'imenu-auto-rescan t))

(use-package imenu-anywhere
  :ensure t
  :bind (("M-I" . ivy-imenu-anywhere)
         ("C-c i" . ivy-imenu-anywhere)))


(use-package imenu-list
  :ensure t
  :config
  (setq-default imenu-list-position "left"))

Xref

Select from xref candidates with ivy

;;(use-package ivy-xref
;;  :ensure t
;;  :after (ivy xref)
;;  :config
;;  (setq xref-show-xrefs-function #'ivy-xref-show-xrefs)
;;  (setq xref-show-definitions-function #'ivy-xref-show-defs))

(use-package ivy-xref
  :defer 2
  :ensure t
  :init (if (< emacs-major-version 27)
            (setq xref-show-xrefs-function #'ivy-xref-show-xrefs)
          (setq xref-show-definitions-function #'ivy-xref-show-defs)))

Plant-UML Config

;; active Org-babel languages
;;(org-babel-do-load-languages
;;  'org-babel-load-languages
;;  '((shell . t)
;;    (plantuml . t)
;;    (emacs-lisp . t)
;;    (java . t)
;;    (python . t)
;;    (sed . t)
;;    (sql . t)
;;    (awk . t)
;;    (R . t)
;;    (awk . t)
;;    (dot . t)
;;    (ruby . t)
;;    (js . t)
;;    (C . t)))
;;
;;(add-to-list 'org-src-lang-modes (quote ("dot". graphviz-dot)))
;;(add-to-list 'org-src-lang-modes (quote ("plantuml" . fundamental)))
;;(setq org-plantuml-jar-path (expand-file-name "/Users/ckoneru/GitRepos/plantuml.jar"))
;;(add-to-list
;; 'org-src-lang-modes '("plantuml" . plantuml))
;;(use-package plantuml-mode
;;  :ensure t
;;  :custom
;;  (plantuml-jar-path "/Users/ckoneru/GitRepos/plantuml.jar")
;;  :mode "\\.uml\\'")
(use-package plantuml-mode
  :defer 3
  :ensure t
  :mode "\\.uml\\'"
  :init
  (setq plantuml-jar-path "/Users/ckoneru/GitRepos/plantuml.jar"))
(use-package flycheck-plantuml
  :defer 3
  :ensure t
  :commands (flycheck-plantuml-setup)
  :init
  (with-eval-after-load 'flycheck
    (flycheck-plantuml-setup)))

Mermaid-mode

(use-package mermaid-mode
  :defer 2
  :ensure t
  :config
  (setq mermaid-mmdc-location "~/GitRepos/node_modules/.bin/mmdc"))

(use-package ob-mermaid
  :defer 2
  :ensure t
  :config
  (setq ob-mermaid-cli-path "~/GitRepos/node_modules/.bin/mmdc")
  )

color-identifier

(use-package color-identifiers-mode
  :defer t
  :ensure t
  :hook ((after-init . global-color-identifiers-mode)))

Ranger

(use-package ranger
  :defer t
  :ensure t
  :config (setq ranger-width-preview 0.5))

Super-save

(use-package super-save
  :ensure t
  :config
  (super-save-mode +1))

;; add integration with ace-window
(add-to-list 'super-save-triggers 'ace-window)

(setq super-save-auto-save-when-idle t)

;; save on find-file
(add-to-list 'super-save-hook-triggers 'find-file-hook)

(setq super-save-remote-files nil)

BeginEnd

(use-package beginend
  :defer t
  :ensure t
  :hook ((after-init . beginend-global-mode)))

ANZU

(use-package anzu
  :defer t
  :ensure t
  :hook ((after-init . global-anzu-mode))
  :custom
  (anzu-search-threshold 1000)
  (anzu-replace-threshold nil)
  (anzu-deactivate-region nil)
  ;;(anzu-replace-to-string-separator "") ;; This is default
  (anzu-replace-to-string-separator "=>")
  (anzu-cons-mode-line-p nil)
  :bind (
         ([remap query-replace-regexp] . anzu-query-replace-regexp)
         ([remap query-replace] . anzu-query-replace)
         ("M-s %" . anzu-query-replace-at-cursor)
         )
  )

Centaur-tabs

;;(use-package centaur-tabs
;;  :ensure t
;;  :demand
;;  :config
;;  (centaur-tabs-mode t)
;;  :bind
;;  ("H-t t <left>" . centaur-tabs-backward)
;;  ("H-t t <right>" . centaur-tabs-forward))

(use-package centaur-tabs
  :ensure t
  :demand
  ;;:load-path "~/.emacs.d/other/centaur-tabs"
  :config
  (setq centaur-tabs-style "wave"
        centaur-tabs-height 32
        centaur-tabs-set-icons t
        centaur-tabs-set-modified-marker t
        centaur-tabs-set-bar 'over)
  (centaur-tabs-headline-match)
  ;; (setq centaur-tabs-gray-out-icons 'buffer)
  ;; (centaur-tabs-enable-buffer-reordering)
  ;; (setq centaur-tabs-adjust-buffer-order t)
  (centaur-tabs-mode t)
  (setq uniquify-separator "/")
  (setq uniquify-buffer-name-style 'forward)
  (defun centaur-tabs-buffer-groups ()
    "`centaur-tabs-buffer-groups' control buffers' group rules.

 Group centaur-tabs with mode if buffer is derived from `eshell-mode' `emacs-lisp-mode' `dired-mode' `org-mode' `magit-mode'.
 All buffer name start with * will group to \"Emacs\".
 Other buffer group by `centaur-tabs-get-group-name' with project name."
    (list
     (cond
      ((or (string-equal "*" (substring (buffer-name) 0 1))
           (memq major-mode '(magit-process-mode
                              magit-status-mode
                              magit-diff-mode
                              magit-log-mode
                              magit-file-mode
                              magit-blob-mode
                              magit-blame-mode
                              )))
       "Emacs")
      ((derived-mode-p 'prog-mode)
       "Editing")
      ((derived-mode-p 'dired-mode)
       "Dired")
      ((memq major-mode '(helpful-mode
                          help-mode))
       "Help")
      ((memq major-mode '(org-mode
                          org-agenda-clockreport-mode
                          org-src-mode
                          org-agenda-mode
                          org-beamer-mode
                          org-indent-mode
                          org-bullets-mode
                          org-cdlatex-mode
                          org-agenda-log-mode
                          diary-mode))
       "OrgMode")
      (t
       (centaur-tabs-get-group-name (current-buffer))))))
  :hook
  (dashboard-mode . centaur-tabs-local-mode)
  (term-mode . centaur-tabs-local-mode)
  (calendar-mode . centaur-tabs-local-mode)
  (org-agenda-mode . centaur-tabs-local-mode)
  (helpful-mode . centaur-tabs-local-mode)
  :bind
  ("s-<left>" . centaur-tabs-backward)
  ("s-<right>" . centaur-tabs-forward)
  ("s-<up>" . centaur-tabs-forward-group)
  ("s-<down>" . centaur-tabs-backward-group)
  ("s-1" . centaur-tabs-select-visible-tab)
  ("s-2" . centaur-tabs-select-visible-tab)
  ("s-3" . centaur-tabs-select-visible-tab)
  ("s-4" . centaur-tabs-select-visible-tab)
  ("s-5" . centaur-tabs-select-visible-tab)
  ("s-6" . centaur-tabs-select-visible-tab)
  ("s-7" . centaur-tabs-select-visible-tab)
  ("s-8" . centaur-tabs-select-visible-tab)
  ("s-9" . centaur-tabs-select-visible-tab)
  ("s-<" . centaur-tabs-move-current-tab-to-left)
  ("s->" . centaur-tabs-move-current-tab-to-right)
  ("H-t t t" . centaur-tabs-counsel-switch-group)
  ("H-t t p" . centaur-tabs-group-by-projectile-project)
  ("H-t t g" . centaur-tabs-group-buffer-groups)
  (:map evil-normal-state-map
        ("g t" . centaur-tabs-forward)
        ("g T" . centaur-tabs-backward)))

Recentf

(require 'recentf)

;; get rid of `find-file-read-only' and replace it with something
;; more useful.
(global-set-key (kbd "C-x C-r") 'counsel-recentf)

;; enable recent files mode.
(recentf-mode t)

;;  50 files ought to be enough.
(setq recentf-max-saved-items 50)

(defun ido-recentf-open ()
  "Use `ido-completing-read' to \\[find-file] a recent file"
  (interactive)
  (if (find-file (ido-completing-read "Find recent file: " recentf-list))
      (message "Opening file...")
    (message "Aborting")))

AutoInsert

(use-package autoinsert
  :defer t
  :ensure t
  :init
  (define-auto-insert
    '("\\.py" . "Python Language")
    '("Python Language"
      "#!/usr/bin/env python3\n"
      "# -*- coding: utf-8 -*-\n"
      "author   : Chetan Koneru \n"
      "date     : " (format-time-string "%b %e, %Y") \n
      "email    : Chetan " \n
      "filename : " (file-name-nondirectory (buffer-file-name)) \n
      "project  : " (file-name-nondirectory (directory-file-name (or projectile-project-root default-directory))) \n
      "license  : GPL-3.0+\n\n"
      "\"\"\"\n")))

Benchmark-init

(use-package benchmark-init
  :ensure t
  :config
  ;; To disable collection of benchmark data after init is done.
  (add-hook 'after-init-hook 'benchmark-init/deactivate))

Highlight’s

(use-package hl-line
  :defer t
  :ensure t
  :hook ((after-init . global-hl-line-mode)))

(use-package highlight-numbers
  :defer t
  :ensure t
  :hook '(after-init-hook prog-mode-hook text-mode-hook org-mode-hook))

Rainbow-Mode

(use-package rainbow-mode
  :defer t
  :ensure t
  :hook (((after-init
           text-mode
           org-mode
           css-mode
           html-mode
           prog-mode). rainbow-mode))
  :diminish rainbow-mode)

Popup

(use-package popup :ensure t :defer t)
(use-package popwin
  :ensure t
  :defer t
  :config
  (popwin-mode 1)
  (setq popwin:close-popup-window-timer-interval 0.1)
  (setq popwin:close-popup-window-timer nil))

Point History

;;(use-package point-history
;;  :quelpa (point-history :fetcher github :url "https://github.com/quelpa/quelpa-use-package.git")
;;  :hook (after-init . point-history-mode)
;;  :bind ("C-c C-/" . point-history-show)
;;  :init (gsetq point-history-ignore-buffer "^ \\*Minibuf\\|^ \\*point-history-show*"))

(use-package point-history
  :straight (point-history :type git :host github :repo "blue0513/point-history")
  :hook (after-init . point-history-mode)
  ;;:bind ("C-c C-/" . point-history-show)
  :config
  (point-history-mode t)
  :init (gsetq point-history-ignore-buffer "^ \\*Minibuf\\|^ \\*point-history-show*"))

(use-package ivy-point-history
  :straight (ivy-point-history :type git :host github :repo "SuzumiyaAoba/ivy-point-history")
  :bind ("C-c C-/" . ivy-point-history))

MMM-Mode

  • MMM mode lets you edit multiple languages within one buffer.
(use-package mmm-mode
  :defer t
  :ensure t
  :commands mmm-mode
  :config
  (require 'mmm-auto))

Reformatter

(use-package reformatter
  :quelpa (reformatter :fetcher github :repo "purcell/reformatter.el"))

(reformatter-define xml-format
  :program "xmllint"
  :args '("--format" "-")
  :mode nil)

Shell-Pop

(use-package shell-pop
  :defer t
  :ensure t
  :bind (("H-x H-t" . shell-pop))
  :config
  (setq shell-pop-shell-type (quote ("ansi-term" "*ansi-term*" (lambda nil (ansi-term shell-pop-term-shell)))))
  (setq shell-pop-term-shell "/bin/zsh")
  ;; need to do this manually or not picked up by `shell-pop'
  (shell-pop--set-shell-type 'shell-pop-shell-type shell-pop-shell-type))

Clojure and Cider

(use-package clojure-mode
  :defer t
  :ensure t
  :mode (("\\.clj\\'" . clojure-mode)
         ("\\.edn\\'" . clojure-mode))
  :init
  (add-hook 'clojure-mode-hook #'yas-minor-mode)
  (add-hook 'clojure-mode-hook #'linum-mode)
  (add-hook 'clojure-mode-hook #'subword-mode)
  (add-hook 'clojure-mode-hook #'smartparens-mode)
  (add-hook 'clojure-mode-hook #'rainbow-delimiters-mode)
  (add-hook 'clojure-mode-hook #'eldoc-mode)
  (add-hook 'clojure-mode-hook #'idle-highlight-mode))

(use-package cider
  :ensure t
  :defer t
  :init (add-hook 'cider-mode-hook #'clj-refactor-mode)
  :diminish subword-mode
  :config
  (setq nrepl-log-messages t
        cider-repl-display-in-current-window t
        cider-repl-use-clojure-font-lock t
        cider-prompt-save-file-on-load 'always-save
        cider-font-lock-dynamically '(macro core function var)
        nrepl-hide-special-buffers t
        cider-overlays-use-font-lock t)
  (cider-repl-toggle-pretty-printing))

(use-package cider-eval-sexp-fu
  :defer t)

(use-package clj-refactor
  :defer t
  :ensure t
  :diminish clj-refactor-mode
  :config (cljr-add-keybindings-with-prefix "C-c C-m"))

(use-package clojure-snippets
  :defer t
  :ensure t)

OX-Pandoc

(use-package pandoc-mode
  :defer t
  :ensure t
  :hook
  (markdown-mode . pandoc-mode)
  (pandoc-mode-hook . pandoc-load-default-settings)
  )

(use-package ox-pandoc
  :ensure t
  :after ox
  :defer t)

(use-package toc-org
  :defer t
  :ensure t)

persistent-scrach

;; persistent-scratch
(use-package persistent-scratch
  :defer t
  :ensure t
  :config
  (persistent-scratch-setup-default))

Empty lines with Tulde

;;(use-package  vi-tilde-fringe
;;  :ensure t
;;  :init (add-hook 'prog-mode-hook 'vi-tilde-fringe-mode)
;;  :config (global-vi-tilde-fringe-mode)
;;  )

(setq-default indicate-empty-lines t)

Cheat

;;(quelpa '(cheat :fetcher github :repo "pbellon/cheat"))
;;(quelpa '(cheat :fetcher github :url "https://github.com/pbellon/cheat.git"))
;;(require 'cheat)
;;(cheat--setup)

;;(use-package cheat
;;  :quelpa (cheat :fetcher github :url "https://github.com/pbellon/cheat.git")
;;  ;;:straight (cheat :type git :host github :repo "pbellon/cheat")
;;  :config
;;  (cheat--setup))

terminal in emacs setting

(use-package eterm-256color
  :defer 2
  :ensure t)
;;(add-to-list 'load-path "~/.emacs.d/multi-libvterm")
;;(require 'multi-libvterm)

(add-to-list 'load-path "~/.emacs.d/custom-el-scripts/emacs-libvterm")
(require 'vterm)

(setq vterm-shell "/bin/zsh"
      vterm-term-environment-variable "eterm-color"
      vterm-max-scrollback 10000)

(add-hook 'vterm-mode-hook
          (lambda ()
            (setq-local evil-insert-state-cursor 'bar)
            (evil-insert-state)))
;;(define-key vterm-mode-map [return]                      #'vterm-send-return)

(setq vterm-keymap-exceptions nil)
(evil-define-key 'insert vterm-mode-map [delete] #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-e")      #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-f")      #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-a")      #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-v")      #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-b")      #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-w")      #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-u")      #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-d")      #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-n")      #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-m")      #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-p")      #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-j")      #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-k")      #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-r")      #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-t")      #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-g")      #'vterm--self-insert)
(evil-define-key 'insert vterm-mode-map (kbd "C-c C-c")  #'vterm-send-ctrl-c)
(evil-define-key 'insert vterm-mode-map (kbd "C-SPC")    #'vterm--self-insert)
(evil-define-key 'normal vterm-mode-map (kbd "C-d")      #'vterm--self-insert)
;;(evil-define-key 'normal vterm-mode-map (kbd ",c")       #'multi-libvterm)
;;(evil-define-key 'normal vterm-mode-map (kbd ",n")       #'multi-libvterm-next)
;;(evil-define-key 'normal vterm-mode-map (kbd ",p")       #'multi-libvterm-prev)
(evil-define-key 'normal vterm-mode-map (kbd "i")        #'evil-insert-resume)
(evil-define-key 'normal vterm-mode-map (kbd "o")        #'evil-insert-resume)
(evil-define-key 'normal vterm-mode-map (kbd "<return>") #'evil-insert-resume)

Sane term

;;----------------------------------------------------------------------------
;; Check filename before call setq
;;----------------------------------------------------------------------------
(defmacro setq-when-file-existed (sym filename)
  "Set SYM when FILENAME is existed."
  (declare (indent 1) (debug t))
  `(when (file-exists-p ,filename)
     (setq ,sym (expand-file-name ,filename))))

(use-package sane-term
  :defer t
  :commands sane-term
  :bind (("H-t s" . sane-term))
  :config
  ;;; term use zsh
  (setq-when-file-existed sane-term-shell-command (executable-find "/usr/local/bin/zsh")))

Nyan-mode

(use-package nyan-mode
  :defer t
  :ensure t
  :init (setq nyan-animate-nyancat t
              nyan-bar-length 16
              nyan-wavy-trail t)
  :custom
  (nyan-cat-face-number 4)
  (nyan-animate-nyancat t)
  :hook
  (after-init . nyan-mode)
  (doom-modeline-mode . nyan-mode))

Copyit

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

Golden-ratio

;; Golden Ratio
(use-package golden-ratio                 ; Auto resize windows
  :defer t
  :ensure t
  :diminish golden-ratio-mode
  :init
  (golden-ratio-mode 1)
  (setq golden-ratio-auto-scale t)
  :config
  (setq golden-ratio-extra-commands
        (append golden-ratio-extra-commands
                '(evil-window-left
                  evil-window-right
                  evil-window-up
                  evil-window-down)))

  (setq golden-ratio-exclude-buffer-names '("*Org Select*")
        golden-ratio-exclude-modes '(messages-buffer-mode
                                     fundamental-mode
                                     ediff-mode
                                     calendar-mode
                                     wget-mode
                                     calc-mode
                                     calc-trail-mode
                                     )
        golden-ratio-recenter t)
  )

(add-to-list 'golden-ratio-extra-commands 'ace-window)

;;(with-eval-after-load 'golden-ratio
;;  (defun my-refresh-golden-ratio (&rest _)
;;    "Queue a refresh of the `golden-ratio' proportions."
;;    (when golden-ratio-mode
;;      ;; Refresh the golden-ratio proportions after a small delay.
;;      (run-with-idle-timer 0.02 nil 'golden-ratio))))
;;(advice-add 'select-window :after 'my-refresh-golden-ratio)

reveal-in-osx-finder

(use-package reveal-in-osx-finder
  :defer 3
  :ensure t)

Multiple-files editing in one buffer

(use-package multifiles
  :defer t
  :ensure t
  :bind ("C-!" . mf/mirror-region-in-multifile))

Sort-words

(use-package sort-words
  :defer t
  :ensure t)

Smart-forward

(use-package smart-forward
  :defer t
  :ensure t
  :config
  (global-set-key (kbd "H-<up>") 'smart-up)
  (global-set-key (kbd "H-<down>") 'smart-down)
  (global-set-key (kbd "H-<left>") 'smart-backward)
  (global-set-key (kbd "H-<right>") 'smart-forward)
  )

Isolate - surround string or region with delimiters

(use-package isolate
  :defer t
  :ensure t
  )
(defun activate-mark-hook@set-transient-map ()
  (set-transient-map
   (let ((map (make-sparse-keymap)))
     (define-key map "s" #'isolate-quick-add)
     (define-key map "S" #'isolate-long-add)
     (define-key map "d" #'isolate-quick-delete)
     (define-key map "D" #'isolate-long-delete)
     (define-key map "c" #'isolate-quick-change)
     (define-key map "C" #'isolate-long-change)
     map)
   #'region-active-p))

(add-hook 'activate-mark-hook #'activate-mark-hook@set-transient-map)

Terraform-mode

(use-package terraform-mode
  :defer t
  :ensure t
  :mode "\\.tf$"
  :config
  (add-hook 'terraform-mode-hook #'terraform-format-on-save-mode)
  )

(use-package terraform-doc
  :defer t
  :ensure t)

(use-package company-terraform
  :defer t
  :ensure t
  :after company
  :hook (terraform-mode . company-terraform-init))

(add-to-list 'lsp-language-id-configuration '(terraform-mode . "terraform"))

(lsp-register-client
 (make-lsp-client :new-connection (lsp-stdio-connection '("~/.emacs.d/custom-el-scripts/lsp/terraform-lsp/terraform-lsp" "-enable-log-file"))
                  :major-modes '(terraform-mode)
                  :server-id 'terraform-ls))

(add-hook 'terraform-mode-hook #'lsp)

Region Convert

(use-package region-convert
  :defer t
  :ensure t
  :bind
  ("C-c C" . region-convert)
  )

Kotlin-mode

(use-package kotlin-mode
  :defer 3
  :ensure t
  )

Gherkin-mode

(use-package gherkin-mode
  :defer 3
  :ensure t)

World-time-mode

(use-package world-time-mode
  :defer 5
  :ensure t)

Swap region

;;M-x swap-regions [select the first region] C-M-c [select the second region] C-M-c
(use-package swap-regions
  :defer t
  :ensure t)

Project abbrev

;; abbrev: expand abbreviations
(use-package abbrev
  :ensure nil
  :defer t
  :hook
  ((prog-mode org-mode text-mode erc-mode LaTeX-mode) . abbrev-mode)
  (expand-load
   . (lambda ()
       (add-hook 'expand-expand-hook 'indent-according-to-mode)
       (add-hook 'expand-jump-hook 'indent-according-to-mode)))
  :bind*
  ("H-;" . endless/ispell-word-then-abbrev)
  :config
  ;; Silently save abbrevs on quitting emacs
  (setq save-abbrevs 'silently)

  ;;Read the abbreviations file on startup
  (if (file-exists-p abbrev-file-name)
      (quietly-read-abbrev-file))

  (defun endless/simple-get-word ()
    (car-safe (save-excursion (ispell-get-word nil))))

  (defun endless/ispell-word-then-abbrev (p)
    "Call `ispell-word', then create an abbrev for it.
With prefix P, create local abbrev. Otherwise it will
be global.
If there's nothing wrong with the word at point, keep
looking for a typo until the beginning of buffer. You can
skip typos you don't want to fix with `SPC', and you can
abort completely with `C-g'."
    (interactive "P")
    (let (bef aft)
      (save-excursion
        (while (if (setq bef (endless/simple-get-word))
                   ;; Word was corrected or used quit.
                   (if (ispell-word nil 'quiet)
                       nil ; End the loop.
                     ;; Also end if we reach `bob'.
                     (not (bobp)))
                 ;; If there's no word at point, keep looking
                 ;; until `bob'.
                 (not (bobp)))
          (backward-word)
          (backward-char))
        (setq aft (endless/simple-get-word)))
      (if (and aft bef (not (equal aft bef)))
          (let ((aft (downcase aft))
                (bef (downcase bef)))
            (define-abbrev
              (if p local-abbrev-table global-abbrev-table)
              bef aft)
            (message "\"%s\" now expands to \"%s\" %sally"
                     bef aft (if p "loc" "glob")))
        (user-error "No typo at or before point")))))

(use-package project-abbrev
  :ensure t
  :bind
  ("C-<return>" . project-abbrev-complete-word)
  :config
  (setq project-abbrev-config-file "project-abbrev.config")
  )

Highlight symbol

(use-package highlight-symbol
  :defer t
  :ensure t
  :bind
  (("M-g h" . highlight-symbol)
   ("M-p" . highlight-symbol-prev)
   ("M-n" . highlight-symbol-next))
  :config
  (set-face-attribute 'highlight-symbol-face nil
                      :background "default"
                      :foreground "#FA009A")
  (setq highlight-symbol-idle-delay 0)
  (setq highlight-symbol-on-navigation-p t)
  (add-hook 'prog-mode-hook #'highlight-symbol-mode)
  (add-hook 'prog-mode-hook #'highlight-symbol-nav-mode))

Downplay Mode

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

Lsp-Ivy

(use-package lsp-ivy
  :defer t
  ;;:quelpa (lsp-ivy :fetcher github :repo "emacs-lsp/lsp-ivy")
  :ensure t
  :after lsp-mode
  :bind (("C-?" . lsp-ivy-workspace-symbol))
  )

ADOC

(use-package adoc-mode
  :defer t
  :ensure t
  :mode "\\.adoc\\'"
  :config
  (add-hook 'adoc-mode-hook
            #'(lambda ()
                (auto-fill-mode -1)
                (visual-line-mode 1)
                (visual-fill-column-mode 1))))

Smart-shift

(use-package smart-shift
  :defer t
  :ensure t
  :config
  (global-smart-shift-mode 1)
  (setq smart-shift-indentation-level 2)
  :bind
  ("s-[" . smart-shift-right)
  ("s-]" . smart-shift-left)
  )

Highlight2clipboard

(use-package highlight2clipboard
  :defer t
  :ensure t
  :config
  (highlight2clipboard-mode 1))

page-break-line

(use-package page-break-lines
  :defer t
  )

Backup-walker

(use-package backup-walker
  :defer 3
  :commands backup-walker-start)

(require 'backup-walker)
;; Make Emacs backup everytime I save

(defun my/force-backup-of-buffer ()
  "Lie to Emacs, telling it the curent buffer has yet to be backed up."
  (setq buffer-backed-up nil))

(add-hook 'before-save-hook  'my/force-backup-of-buffer)

OX-clip

(use-package ox-clip
  :defer t
  :after org
  :bind ("C-x c c" . ox-clip-formatted-copy))

org-cliplink

(use-package org-cliplink
  :defer t
  :ensure t
  :after org
  :bind
  ("C-x c l" . org-cliplink)
  )

My Notes and Wiki setup

(use-package org-brain
  :defer 3
  :ensure t
  :after org
  :init
  (setq org-brain-path "~/GitRepos/my-org-notes")
  ;; For Evil users
  (with-eval-after-load 'evil
    (evil-set-initial-state 'org-brain-visualize-mode 'emacs))
  :config
  (setq org-id-track-globally t)
  (setq org-id-locations-file "~/GitRepos/my-org-notes/brain-ids/.org-id-locations")
  (setq org-brain-visualize-default-choices 'all)
  (setq org-brain-title-max-length 12)
  (setq org-brain-include-file-entries nil
        org-brain-file-entries-use-title nil))

(use-package deft
  :defer t
  :commands (deft)
  :init (setq deft-directory "~/GitRepos/my-org-notes/"
              deft-recursive t
              deft-text-mode 'org-mode
              deft-use-filename-as-title t
              deft-extensions '("org" "md"))
  )

(defun org-brain-deft ()
  "Use `deft' for files in `org-brain-path'."
  (interactive)
  (let ((deft-directory org-brain-path)
        (deft-recursive t)
        (deft-extensions '("org")))
    (deft)))

(defun org-brain-cliplink-resource ()
  "Add a URL from the clipboard as an org-brain resource.
Suggest the URL title as a description for resource."
  (interactive)
  (let ((url (org-cliplink-clipboard-content)))
    (org-brain-add-resource
     url
     (org-cliplink-retrieve-title-synchronously url)
     t)))

;;(define-key org-brain-visualize-mode-map (kbd "L") #'org-brain-cliplink-resource)

Ox-hugo

(use-package ox-hugo
  :defer 2
  :ensure t            ;Auto-install the package from Melpa (optional)
  :after ox)

Lsp-mode

(use-package lsp-mode
  :defer t
  :ensure t
  :commands (lsp lsp-deferred)
  :custom
  (lsp-auto-guess-root nil)
  (lsp-enable-snippet t)
  (lsp-eldoc-render-all t)
  (lsp-enable-imenu t)
  (lsp-prefer-flymake nil) ; Use flycheck instead of flymake
  :bind (:map lsp-mode-map ("C-c C-f" . lsp-format-buffer))
  :hook (
         (python-mode . lsp)
         (sh-mode . lsp)
         (terraform-mode . lsp)
         (scala-mode . lsp)
         (dockerfile-mode . lsp)
         (go-mode . lsp-deferred)
         (html-mode . lsp)
         ;;(xml-mode . lsp)
         )
  :config
  (setq lsp-prefer-flymake nil)
  ;; LSP debugging
  (setq lsp-print-io t)
  (setq lsp-log-io t)
  (setq lsp-trace t)
  (setq lsp-print-performance t)
  (setq lsp-session-file (expand-file-name "~/.emacs.d/var/lsp-session.el"))
  ;; Set up before-save hooks to format buffer and add/delete imports.
  ;; Make sure you don't have other gofmt/goimports hooks enabled.
  ;;(defun lsp-go-install-save-hooks ()
  ;;  (add-hook 'before-save-hook #'lsp-format-buffer t t)
  ;;  (add-hook 'before-save-hook #'lsp-organize-imports t t))
  ;;(add-hook 'go-mode-hook #'lsp-go-install-save-hooks)
  )


(use-package lsp-ui
  :defer t
  :after lsp-mode
  :diminish
  :commands lsp-ui-mode
  :hook (lsp-mode . lsp-ui-mode)
  :custom-face
  (lsp-ui-doc-background ((t (:background nil))))
  (lsp-ui-doc-header ((t (:inherit (font-lock-string-face italic)))))
  :bind (:map lsp-ui-mode-map
              ([remap xref-find-definitions] . lsp-ui-peek-find-definitions)
              ([remap xref-find-references] . lsp-ui-peek-find-references)
              ("C-c u" . lsp-ui-imenu))
  :custom
  (lsp-ui-doc-enable t)
  (lsp-ui-doc-header t)
  (lsp-ui-doc-include-signature t)
  (lsp-ui-doc-position 'top)
  (lsp-ui-doc-border (face-foreground 'default))
  (lsp-ui-sideline-enable nil)
  (lsp-ui-sideline-ignore-duplicate t)
  (lsp-ui-sideline-show-code-actions nil)
  :config
  ;; Use lsp-ui-doc-webkit only in GUI
  (setq lsp-ui-doc-use-webkit t)
  ;; WORKAROUND Hide mode-line of the lsp-ui-imenu buffer
  ;; https://github.com/emacs-lsp/lsp-ui/issues/243
  (defadvice lsp-ui-imenu (after hide-lsp-ui-imenu-mode-line activate)
    (setq mode-line-format nil)))

(use-package lsp-treemacs
  :defer t
  :ensure t :commands lsp-treemacs-errors-list)

;; Add company-lsp backend for metals
;;(use-package company-lsp
;;:ensure t
;;:config
;;(setq compnay-lsp-enable-snippet t)
;;(push 'company-lsp company-backends))
(use-package company-lsp
  :defer t
  :commands company-lsp
  :custom
  (company-lsp-cache-candidates 'auto)
  :config
  (setq compnay-lsp-enable-snippet t)
  (push 'company-lsp company-backends)
  (add-to-list 'company-lsp-filter-candidates '(mspyls . t))
  (defun company-lsp--on-completion (response prefix)
    " This is a (hack) workaround for candidate filtering issues in mspyls.
Handle completion RESPONSE.
PREFIX is a string of the prefix when the completion is requested.
Return a list of strings as the completion candidates."
    (let* ((incomplete (and (hash-table-p response) (gethash "isIncomplete" response)))
           (items (cond ((hash-table-p response) (gethash "items" response))
                        ((sequencep response) response)))
           (candidates (mapcar (lambda (item)
                                 (company-lsp--make-candidate item prefix))
                               (lsp--sort-completions items)))
           (server-id (lsp--client-server-id (lsp--workspace-client lsp--cur-workspace)))
           (should-filter (or (eq company-lsp-cache-candidates 'auto) ; change from t to 'auto
                              (and (null company-lsp-cache-candidates)
                                   (company-lsp--get-config company-lsp-filter-candidates server-id)))))
      (when (null company-lsp--completion-cache)
        (add-hook 'company-completion-cancelled-hook #'company-lsp--cleanup-cache nil t)
        (add-hook 'company-completion-finished-hook #'company-lsp--cleanup-cache nil t))
      (when (eq company-lsp-cache-candidates 'auto)
        ;; Only cache candidates on auto mode. If it's t company caches the
        ;; candidates for us.
        (company-lsp--cache-put prefix (company-lsp--cache-item-new candidates incomplete)))
      (if should-filter
          (company-lsp--filter-candidates candidates prefix)
        candidates))))

Flyspell

;;http://blog.binchen.org/posts/what-s-the-best-spell-check-set-up-in-emacs.html
;;https://github.com/redguardtoo/emacs.d/blob/master/lisp/init-spelling.el
(use-package flyspell
  :defer t
  :commands (ispell-change-dictionary
             flyspell-buffer
             flyspell-mode
             flyspell-region)
  :config
  (setq flyspell-issue-message-flag nil)
  (setq flyspell-issue-welcome-flag nil)
  (setq ispell-program-name "aspell")
  (setq ispell-dictionary "en_US")
  (setq ispell-extra-args '("--sug-mode=ultra"))
  ;;(add-hook 'text-mode-hook 'flyspell-mode)
  ;;(add-hook 'prog-mode-hook 'flyspell-prog-mode)

  ;;(define-key flyspell-mode-map (kbd "C-;") nil)
  ;; TODO (emacs 27): ispell-change-dictionary-hook
  )

TOML

(use-package toml-mode
  :defer t
  :ensure t
  :config
  (add-to-list 'auto-mode-alist '("\\.t[o]ml\\'" . toml-mode)))

Manage-minor-mode

(use-package manage-minor-mode
  :defer t)

Nov

;; nov: Epub reader for emacs
;; https://github.com/wasamasa/nov.el
(use-package nov
  :defer 3
  :mode ("\\.epub\\'" . nov-mode)
  :hook ((nov-mode . visual-line-mode)
         (nov-mode . visual-fill-column-mode))
  :config
  (setq nov-text-width most-positive-fixnum)
  (setq visual-fill-column-center-text t))

RealGud

;; realgud: Debugger interface for emacs
;; https://github.com/realgud/realgud/
(use-package realgud
  :defer 3)

Selected

(use-package selected
  :defer 5
  :bind (:map selected-keymap
              ("w" . kill-region)
              ("~" . hydra-change-case/body)
              ("c" . copy-region-as-kill)
              ("d" . duplicate-current-line-or-region)
              ("E" . eval-region)
              ("e" . er/expand-region)
              ("f" . fill-region)
              ("q" . vr/query-replace)
              (";" . comment-or-uncomment-region)
              )
  :init
  (selected-global-mode))

Langtool

(use-package langtool
  :defer 5
  :config
  ;; place the language-tool directory in $HOME
  (setq langtool-language-tool-jar
        "/usr/local/Cellar/languagetool/4.8/libexec/languagetool-commandline.jar")
  (setq langtool-default-language "en-US")

  ;; hydra for langtool check
  (defhydra hydra-langtool (:color pink
                                   :hint nil)
    "
_c_: check    _n_: next error
_C_: correct  _p_: prev error _d_: done checking
"
    ("n"  langtool-goto-next-error)
    ("p"  langtool-goto-previous-error)
    ("c"  langtool-check)
    ("C"  langtool-correct-buffer)
    ("d"  langtool-check-done :color blue)
    ("q" nil "quit" :color blue))
  (bind-key "C-c h l l t" 'hydra-langtool/body))

region-occurrences-highlighter

(use-package region-occurrences-highlighter
  :ensure t
  :defer 1
  :config
  (add-hook 'prog-mode-hook #'region-occurrences-highlighter-mode)
  (add-hook 'org-mode-hook #'region-occurrences-highlighter-mode)

  (add-hook 'text-mode-hook #'region-occurrences-highlighter-mode)

  )

Zoom-window

(use-package zoom-window
  :defer 1
  :ensure t
  :bind ("C-x C-z" . zoom-window-zoom))

Loccur

(use-package loccur
  :ensure t
  :defer 3
  :bind
  (("M-s M-l" . loccur-current)
   ("M-s M-L" . loccur)
   ("M-s C-l" . loccur-previous-match)))

Buffer-expose

(load-if-exists "~/.emacs.d/custom-el-scripts/buffer-expose/buffer-expose.el")
(buffer-expose-mode 1)

reset GC

;;; end
;; reset GC
;;(setq gc-cons-threshold 16777216
;;      gc-cons-percentage 0.1)
(defvar best-gc-cons-threshold
;;4000000
100000000
"Best default gc threshold value.  Should NOT be too big!")
(setq gc-cons-threshold best-gc-cons-threshold)