7dc3fc681aa50f52e4ddba22aebbe723a2dbd191
[dotfiles.git] / emacs.d / config.org
1 #+TITLE: Emacs Configuration file
2 #+AUTHOR: Peng Li
3 #+EMAIL: seudut@gmail.com
4
5 * Introduction
6
7 Most config are just copied from [[https://github.com/howardabrams/dot-files][howardabrams]]'s and [[https://github.com/abo-abo/oremacs][abo-abo's]] dotfiles
8
9 * Basic Settings
10 ** Setting loading Path
11 Set system PATH and emacs exec path
12 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
13   (setenv "PATH" (concat (getenv "PATH")
14                          ":" "/usr/local/bin"
15                          ":" "/Library/TeX/texbin"))
16   (setq exec-path (append exec-path '("/usr/local/bin")))
17   (setq exec-path (append exec-path '("/Library/TeX/texbin/")))
18 #+END_SRC
19
20 ** Package Initialization
21 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
22   (require 'package)
23
24   (setq package-archives '(("mepla" . "http://melpa.milkbox.net/packages/")
25                            ("gnu" . "http://elpa.gnu.org/packages/")
26                            ("org" . "http://orgmode.org/elpa/")))
27
28   (package-initialize)
29 #+END_SRC       
30
31 ** My constant
32 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
33   (defconst my-name "Peng Li")
34   (defconst my-email "seudut@gmail.com")
35   (defconst MY-EMACS-DIR (concat (getenv "HOME") "/.emacs.d"))
36   (defconst MY-EMACS-TMP (concat MY-EMACS-DIR "/temp"))
37   (unless (file-exists-p MY-EMACS-TMP)
38     (mkdir MY-EMACS-TMP))
39 #+END_SRC
40
41 ** General Setting
42 *** scroll bar, tool-bar and menu-bar
43 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
44   (if (display-graphic-p)
45       (progn
46         (scroll-bar-mode 0)
47         (tool-bar-mode 0)
48         (menu-bar-mode 1))
49     (menu-bar-mode 0))
50
51   ;; (setq debug-on-error t)
52   (setq inhibit-startup-message t)
53
54   (defalias 'yes-or-no-p 'y-or-n-p)
55   (show-paren-mode 1)
56   ;; don't backupf
57   (setq make-backup-files nil)
58
59   ;;supress the redefined warning at startup
60   (setq ad-redefinition-action 'accept)
61
62   (setq scroll-step 1)
63   (setq scroll-margin 5)
64
65   (when (display-graphic-p)
66     (fringe-mode '(0 . 0)))
67
68   (blink-cursor-mode 0)
69   ;; (setq-default indicate-empty-lines t)
70   ;; (setq-default indicate-abuffer-boundaries 'right)
71 #+END_SRC
72
73 *** Custom file 
74 #+BEGIN_SRC emacs-lisp :tangle yes :results silent 
75   (setq custom-file "~/.emacs.d/custom.el")
76   (if (file-exists-p custom-file)
77       (load custom-file))
78 #+END_SRC
79
80 *** Switch the focus to help window when it appears
81 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
82   (setq help-window-select t)
83 #+END_SRC
84
85 *** Set default window size
86 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
87   (setq initial-frame-alist
88         '((width . 120)
89           (height . 50)))
90
91   ;; (setq-default indicate-empty-lines t)
92 #+END_SRC
93
94 *** Stop auto save
95 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
96   (setq auto-save-default nil)
97
98   ;; restore last session
99   ;; (desktop-save-mode t)
100 #+END_SRC
101
102 *** temp folder
103 Make a temp directory for all cache/history files
104 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
105   (defconst sd-temp-directory
106     (file-name-as-directory "~/.emacs.d/temp"))
107
108   (unless (file-exists-p sd-temp-directory)
109     (mkdir sd-temp-directory))
110 #+END_SRC
111
112 *** Save minibuffer history
113 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
114   (setq savehist-file (concat sd-temp-directory "history"))
115   (setq history-length 1000)
116   (setq savehist-additional-variables '(kill-ring search-ring regexp-search-ring))
117   (savehist-mode 1)
118
119   ;; set temp file path for recentf and auto-save
120   (setq recentf-save-file (concat sd-temp-directory "recentf"))
121   (setq recentf-max-saved-items 1000)
122   (setq auto-save-list-file-prefix (concat sd-temp-directory "auto-save-list/.saves-"))
123 #+END_SRC
124
125 *** Max file size
126 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
127   (setq large-file-warning-threshold nil)
128 #+END_SRC
129
130 *** Xterm mode
131 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
132   (unless (display-graphic-p)
133     (xterm-mouse-mode))
134 #+END_SRC
135 * Package Management Tools
136 ** Use-package
137 Using [[https://github.com/jwiegley/use-package][use-package]] to manage emacs packages
138 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
139   (unless (package-installed-p 'use-package)
140     (package-refresh-contents)
141     (package-install 'use-package))
142
143   (require 'use-package)
144 #+END_SRC
145
146 ** El-get
147 [[https://github.com/dimitri/el-get][El-get]] is package management tool, whicl allows to install external elisp package from any git repository not in mepla. 
148 Check out [[http://tapoueh.org/emacs/el-get.html][el-get]].
149 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
150   (use-package el-get
151     :ensure t
152     :init
153     (add-to-list 'load-path "~/.emacs.d/el-get"))
154 #+END_SRC
155
156 ** paradox
157 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
158   (use-package paradox
159     :ensure t)
160 #+END_SRC
161
162 * Color and Fonts Settings
163 ** highlight current line
164 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
165   ;; (global-hl-line-mode)
166   ;; don't want high light current line in eshell/term mode
167   (add-hook 'prog-mode-hook 'hl-line-mode)
168   (add-hook 'text-mode-hook 'hl-line-mode)
169   (add-hook 'dired-mode-hook 'hl-line-mode)
170
171   ;; only highlight selected window
172   (setq hl-line-sticky-flag nil)
173
174   (setq-default fill-column 120)
175   (add-hook 'text-mode-hook 'turn-on-auto-fill)
176 #+END_SRC
177
178 ** Smart Comments
179 [[https://github.com/paldepind/smart-comment][smart-comments]]
180 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
181   (use-package smart-comment
182     :ensure t
183     :bind ("M-;" . smart-conmment))
184 #+END_SRC
185
186 ** Font Setting
187 *** syntax highlighting
188 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
189   (global-font-lock-mode 1)
190 #+END_SRC
191
192 *** [[https://github.com/i-tu/Hasklig][Hasklig]] and Source Code Pro, defined fonts family
193 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
194   (if window-system
195       (defvar sd/fixed-font-family
196         (cond ((x-list-fonts "Hasklig")         "Hasklig")
197               ((x-list-fonts "Source Code Pro") "Source Code Pro:weight=light") ;; weigth=light
198               ((x-list-fonts "Anonymous Pro")   "Anonymous Pro")
199               ((x-list-fonts "M+ 1mn")          "M+ 1mn"))
200         "The fixed width font based on what is installed, `nil' if not defined."))
201 #+END_SRC
202
203 Setting the fonts alignment issue
204 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
205   (if window-system
206       (when sd/fixed-font-family
207         (set-frame-font sd/fixed-font-family)
208         (set-face-attribute 'default nil :font sd/fixed-font-family :height 120)
209         (set-face-font 'default sd/fixed-font-family)))
210 #+END_SRC
211
212 *** Chinese fonts
213 Fix the font alignment issue when both Chinese and English hybird in org-mode table. Refer [[http://coldnew.github.io/blog/2013/11-16_d2f3a/][解決 org-mode 表格內中英文對齊的問題]]
214 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
215   (defvar emacs-english-font "Source Code Pro" "The font name of English.")
216
217   (defvar emacs-cjk-font "STHeiti" "The font name for CJK.")
218
219   (defvar emacs-font-size-pair '(13 . 16) "Default font size pair for (english . chinese)")
220
221   (defvar emacs-font-size-pair-list
222     '(( 5 .  6) (10 . 12)
223       (11 . 14) (12 . 14)
224       (13 . 16) (14 . 16) (15 . 18) (16 . 20) (17 . 20)
225       (18 . 22) (19 . 22) (20 . 24) (21 . 26)
226       (24 . 28) (26 . 32) (28 . 34)
227       (30 . 36) (34 . 40) (36 . 44))
228     "This list is used to store matching (englis . chinese) font-size.")
229
230   (defun font-exist-p (fontname)
231     "Test if this font is exist or not."
232     (if (or (not fontname) (string= fontname ""))
233         nil
234       (if (not (x-list-fonts fontname)) nil t)))
235
236   (defun set-font (english chinese size-pair)
237     "Setup emacs English and Chinese font on x window-system."
238     (if (font-exist-p english)
239         (set-frame-font (format "%s:pixelsize=%d" english (car size-pair)) t))
240     (if (font-exist-p chinese)
241         (dolist (charset '(han cjk-misc) ;; '(kana han symbol cjk-misc bopomofo)
242                  )
243           (set-fontset-font (frame-parameter nil 'font) charset
244                             (font-spec :family chinese :size (cdr size-pair))))))
245
246   (defun emacs-step-font-size (step)
247     "Increase/Decrease emacs's font size."
248     (let ((scale-steps emacs-font-size-pair-list))
249       (if (< step 0) (setq scale-steps (reverse scale-steps)))
250       (setq emacs-font-size-pair
251             (or (cadr (member emacs-font-size-pair scale-steps))
252                 emacs-font-size-pair))
253       (when emacs-font-size-pair
254         (message "emacs font size set to %.1f" (car emacs-font-size-pair))
255         (set-font emacs-english-font emacs-cjk-font emacs-font-size-pair))))
256
257   (defun increase-emacs-font-size ()
258     "Decrease emacs's font-size acording emacs-font-size-pair-list."
259     (interactive) (emacs-step-font-size 1))
260
261   (defun decrease-emacs-font-size ()
262     "Increase emacs's font-size acording emacs-font-size-pair-list."
263     (interactive) (emacs-step-font-size -1))
264 #+END_SRC
265
266
267 ** Color Theme
268
269 Loading theme should be after all required loaded, refere [[https://github.com/jwiegley/use-package][:defer]] in =use-package=
270
271 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
272   (setq vc-follow-symlinks t)
273   (use-package molokai-theme
274     :ensure t)
275
276   (use-package color-theme
277     :ensure t
278     :init (require 'color-theme)
279     :config (use-package color-theme-sanityinc-tomorrow
280               :ensure t
281               :no-require t
282               :config
283               ;; (load-theme 'sanityinc-tomorrow-bright t)
284               (load-theme 'molokai t)
285               ))
286
287   ;(eval-after-load 'color-theme
288   ;  (load-theme 'sanityinc-tomorrow-bright t))
289
290 #+END_SRC
291
292 Change the Org-mode colors 
293
294 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
295
296   (defun org-src-color-blocks-light ()
297     "Colors the block headers and footers to make them stand out more for lighter themes"
298     (interactive)
299     (custom-set-faces
300      '(org-block-begin-line
301       ((t (:underline "#A7A6AA" :foreground "#008ED1" :background "#EAEAFF"))))
302      '(org-block-background
303        ((t (:background "#FFFFEA"))))
304      '(org-block
305        ((t (:background "#FFFFEA"))))
306      '(org-block-end-line
307        ((t (:overline "#A7A6AA" :foreground "#008ED1" :background "#EAEAFF"))))
308
309      '(mode-line-buffer-id ((t (:foreground "#005000" :bold t))))
310      '(which-func ((t (:foreground "#008000"))))))
311
312   (defun org-src-color-blocks-dark ()
313     "Colors the block headers and footers to make them stand out more for dark themes"
314     (interactive)
315     (custom-set-faces
316      '(org-block-begin-line
317        ((t (:foreground "#008ED1" :background "#002E41"))))
318      '(org-block-background
319        ((t (:background "#000000"))))
320      '(org-block
321        ((t (:background "#000000"))))
322      '(org-block-end-line
323        ((t (:foreground "#008ED1" :background "#002E41"))))
324
325      '(mode-line-buffer-id ((t (:foreground "black" :bold t))))
326      '(which-func ((t (:foreground "green"))))))
327
328   (org-src-color-blocks-dark)
329
330 #+END_SRC
331
332 improve color for org-mode
333 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
334   (deftheme ha/org-theme "Sub-theme to beautify org mode")
335
336   (if window-system
337       (defvar sd/variable-font-tuple
338         (cond ((x-list-fonts "Source Sans Pro") '(:font "Source Sans Pro"))
339               ((x-list-fonts "Lucida Grande")   '(:font "Lucida Grande"))
340               ((x-list-fonts "Verdana")         '(:font "Verdana"))
341               ((x-family-fonts "Sans Serif")    '(:family "Sans Serif"))
342               (nil (warn "Cannot find a Sans Serif Font.  Install Source Sans Pro.")))
343         "My variable width font available to org-mode files and whatnot."))
344
345   (defun sd/org-color ()
346     (let* ((sd/fixed-font-tuple (list :font sd/fixed-font-family))
347            (base-font-color     (face-foreground 'default nil 'default))
348            (background-color    (face-background 'default nil 'default))
349            (primary-color       (face-foreground 'mode-line nil))
350            (secondary-color     (face-background 'secondary-selection nil 'region))
351            (base-height         (face-attribute 'default :height))
352            (headline           `(:inherit default :weight bold :foreground ,base-font-color)))
353       (custom-theme-set-faces 'ha/org-theme
354                               `(org-agenda-structure ((t (:inherit default :height 2.0 :underline nil))))
355                               `(org-verbatim ((t (:inherit 'fixed-pitched :foreground "#aef"))))
356                               `(org-table ((t (:inherit 'fixed-pitched))))
357                               `(org-block ((t (:inherit 'fixed-pitched))))
358                               `(org-block-background ((t (:inherit 'fixed-pitched))))
359                               `(org-block-begin-line ((t (:inherit 'fixed-pitched))))
360                               `(org-block-end-line ((t (:inherit 'fixed-pitched))))
361                               `(org-level-8 ((t (,@headline ,@sd/variable-font-tuple))))
362                               `(org-level-7 ((t (,@headline ,@sd/variable-font-tuple))))
363                               `(org-level-6 ((t (,@headline ,@sd/variable-font-tuple))))
364                               `(org-level-5 ((t (,@headline ,@sd/variable-font-tuple))))
365                               `(org-level-4 ((t (,@headline ,@sd/variable-font-tuple
366                                                             :height ,(round (* 1.1 base-height))))))
367                               `(org-level-3 ((t (,@headline ,@sd/variable-font-tuple
368                                                             :height ,(round (* 1.25 base-height))))))
369                               `(org-level-2 ((t (,@headline ,@sd/variable-font-tuple
370                                                             :height ,(round (* 1.5 base-height))))))
371                               `(org-level-1 ((t (,@headline ,@sd/variable-font-tuple
372                                                             :height ,(round (* 1.75 base-height))))))
373                               `(org-document-title ((t (,@headline ,@sd/variable-font-tuple :height 1.5 :underline nil)))))))
374
375
376 #+END_SRC
377
378 search text theme
379 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
380   (set-face-attribute 'lazy-highlight nil :background "yellow" :foreground "black" :weight 'bold)
381 #+END_SRC
382
383 ** Rainbow-delimiter
384
385 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
386
387   (use-package rainbow-delimiters
388     :ensure t
389     :init
390     (add-hook 'prog-mode-hook #'rainbow-delimiters-mode))
391
392 #+END_SRC
393
394 ** page-break-lines
395 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
396   (use-package page-break-lines
397     :ensure t
398     :config
399     (global-page-break-lines-mode)
400     ;; (turn-on-page-break-lines-mode)
401     )
402 #+END_SRC
403
404 ** rainbow-mode
405
406 Enable rainbow mode in emacs lisp mode
407
408 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
409   (use-package rainbow-mode
410     :ensure t
411   ;  :init
412   ;  (add-hook emacs-lisp-mode-hook 'rainbow-mode)
413     )
414
415 #+END_SRC
416
417 ** cusor color
418 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
419   (if (display-graphic-p)
420       (set-cursor-color 'red))
421 #+END_SRC
422
423 * Mode-line
424 ** clean mode line
425 clean mode line, Refer to [[https://www.masteringemacs.org/article/hiding-replacing-modeline-strings][Marstering Emacs]], some greek character see [[http://xahlee.info/math/math_unicode_greek.html][math_unicode_greek]]
426 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
427   (defvar mode-line-cleaner-alist
428     `((auto-complete-mode . " α")
429       (paredit-mode . " π")
430       (eldoc-mode . "")
431       (abbrev-mode . "")
432       (projectile-mode . "")
433       (ivy-mode . "")
434       (undo-tree-mode . "")
435       ;; default is WK
436       (which-key-mode . "")
437       ;; default is SP
438       (smartparens-mode . "")
439       ;; default is LR
440       (linum-relative-mode . "")
441       ;; default is ARev
442       (auto-revert-mode . "")
443       ;; default is Ind
444       (org-indent-mode . "")
445       ;; default is  Fly
446       (flyspell-mode . "")
447       (irony-mode . "")
448       (page-break-lines-mode . "")
449       (yas-minor-mode . "y")
450       ;; default jj
451       (evil-escape-mode . "")
452       ;; Major modes
453       (lisp-interaction-mode . "λ")
454       (hi-lock-mode . "")
455       (python-mode . "Py")
456       (emacs-lisp-mode . "EL")
457       (eshell-mode . "𝞔")
458       (dired-mode . "𝞓")
459       (ibuffer-mode . "𝞑")
460       (org-mode . "𝞞")
461       (nxhtml-mode . "nx"))
462     "Alist for `clean-mode-line'.
463
464   When you add a new element to the alist, keep in mind that you
465   must pass the correct minor/major mode symbol and a string you
466   want to use in the modeline *in lieu of* the original.")
467
468
469   (defun clean-mode-line ()
470     (interactive)
471     (loop for cleaner in mode-line-cleaner-alist
472           do (let* ((mode (car cleaner))
473                    (mode-str (cdr cleaner))
474                    (old-mode-str (cdr (assq mode minor-mode-alist))))
475                (when old-mode-str
476                    (setcar old-mode-str mode-str))
477                  ;; major mode
478                (when (eq mode major-mode)
479                  (setq mode-name mode-str)))))
480
481
482   (add-hook 'after-change-major-mode-hook 'clean-mode-line)
483 #+END_SRC
484
485 ** Powerline mode
486 Install powerline mode [[https://github.com/milkypostman/powerline][powerline]]
487 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
488   (use-package powerline
489     :ensure t
490     :config
491     ;; (powerline-center-theme)
492     )
493
494   ;; (use-package smart-mode-line
495   ;;   :ensure t)
496   ;; (use-package smart-mode-line-powerline-theme
497   ;;   :ensure t)
498 #+END_SRC
499
500 Revised powerline-center-theme
501 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
502   (defun sd/powerline-simpler-vc (s)
503     (if s
504         (replace-regexp-in-string "Git[:-]" "" s)
505       s))
506
507   (defface sd/powerline-active1 '((t (:background "yellow" :foreground "black" :inherit mode-line)))
508     "My Powerline face 1 based on powerline-active1."
509     :group 'powerline)
510
511   (defface sd/buffer-modified-active1 '((t (:background "red" :foreground "black" :inherit mode-line)))
512     "My Powerline face 1 based on powerline-active1."
513     :group 'powerline)
514
515   (defface sd/buffer-view-active1 '((t (:background "green" :foreground "black" :inherit mode-line)))
516     "My Powerline face 1 based on powerline-active1."
517     :group 'powerline)
518
519   (defface sd/mode-line-buffer-id
520     '((t (:background "yellow" :foreground "black" :inherit mode-line-buffer-id)))
521     "My powerline mode-line face, based on mode-line-buffer-id"
522     :group 'powerline)
523
524   ;; Don't show buffer modified for scratch and eshell mode
525   (defun sd/buffer-is-eshel-or-scratch ()
526     "Dot not show modified indicator for buffers"
527     (interactive)
528     (unless (or (string-match "*scratch*" (buffer-name))
529                 (equal major-mode 'eshell-mode))
530       t))
531
532   (defun sd/powerline-center-theme_revised ()
533     "Setup a mode-line with major and minor modes centered."
534     (interactive)
535     (setq-default mode-line-format
536                   '("%e"
537                     (:eval
538                      (let* ((active (powerline-selected-window-active))
539                             ;; (mode-line-buffer-id (if active 'sd/mode-line-buffer-id 'mode-line-buffer-id-inactive))
540                             (mode-line-buffer-id (if active 'sd/mode-line-buffer-id 'powerline-inactive1))
541                             (mode-line (if active 'mode-line 'mode-line-inactive))
542                             (my-face1 (if active 'sd/powerline-active1 'powerline-inactive1))
543                             (my-face-buffer-modified (if (and (sd/buffer-is-eshel-or-scratch) (buffer-modified-p) (not buffer-read-only)) 
544                                                          'sd/buffer-modified-active1
545                                                        (if buffer-read-only 'sd/buffer-view-active1
546                                                          my-face1)))
547                             (face1 (if active 'powerline-active1 'powerline-inactive1))
548                             (face2 (if active 'powerline-active2 'powerline-inactive2))
549                             (separator-left (intern (format "powerline-%s-%s"
550                                                             (powerline-current-separator)
551                                                             (car powerline-default-separator-dir))))
552                             (separator-right (intern (format "powerline-%s-%s"
553                                                              (powerline-current-separator)
554                                                              (cdr powerline-default-separator-dir))))
555                             (lhs (list (powerline-raw "%* " my-face-buffer-modified 'l)
556                                        ;; (powerline-buffer-size mode-line 'l)
557                                        (powerline-buffer-id mode-line-buffer-id 'l)
558                                        (powerline-raw " " my-face1)
559                                        (funcall separator-left my-face1 face1)
560                                        (powerline-narrow face1 'l)
561                                        ;; (powerline-vc face1)
562                                        (sd/powerline-simpler-vc (powerline-vc face1))))
563                             (rhs (list (powerline-raw global-mode-string face1 'r)
564                                        (powerline-raw "%4l" face1 'r)
565                                        (powerline-raw ":" face1)     
566                                        (powerline-raw "%3c" face1 'r)
567                                        (funcall separator-right face1 my-face1)
568                                        ;; (powerline-raw " " my-face1)
569                                        (powerline-raw (format-time-string " %I:%M %p  ") my-face1 'r)
570                                        ;; (powerline-raw "%6p" my-face1 'r)
571                                        ;; (powerline-hud my-face1 face1 )
572                                        ))
573                             (center (list (powerline-raw " " face1)
574                                           (funcall separator-left face1 face2)
575                                           (powerline-raw (when  (and (boundp 'evil-mode)  evil-mode) evil-mode-line-tag) face2)
576                                           (when (and (boundp 'erc-track-minor-mode) erc-track-minor-mode)
577                                             (powerline-raw erc-modified-channels-object face2 'l))
578                                           (powerline-major-mode face2 'l)
579                                           (powerline-process face2)
580                                           (powerline-raw " :" face2)
581                                           (powerline-minor-modes face2 'l)
582                                           (powerline-raw " " face2)
583                                           (funcall separator-right face2 face1))))
584                        (concat (powerline-render lhs)
585                                (powerline-fill-center face1 (/ (powerline-width center) 2.0))
586                                (powerline-render center)
587                                (powerline-fill face1 (powerline-width rhs))
588                                (powerline-render rhs)))))))
589
590   (sd/powerline-center-theme_revised)
591 #+END_SRC
592
593 Fix the issue in mode line when showing triangle 
594 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
595   (setq ns-use-srgb-colorspace nil)
596 #+END_SRC
597
598 set height in mode line
599 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
600   (defconst sd/mode-line-font-heigh 100
601     "Defaulet the fontsize on mode line.")
602
603   (with-eval-after-load "powerline"
604     (when (display-graphic-p)
605       (set-face-attribute 'mode-line-inactive nil :height sd/mode-line-font-heigh)
606       (set-face-attribute 'mode-line nil :height sd/mode-line-font-heigh)
607       (let* ((base-font-size (face-attribute 'default :height)))
608         ;; 100/140;0.8
609         (set-variable 'powerline-height (/ base-font-size 10))
610         (set-variable 'powerline-text-scale-factor (/ (float sd/mode-line-font-heigh) base-font-size)))))
611 #+END_SRC
612
613 * IDO & SMEX
614 ** IDO
615 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
616   (use-package ido
617     :ensure t
618     :init (setq ido-enable-flex-matching t
619                 ido-ignore-extensions t
620                 ido-use-virtual-buffers t
621                 ido-use-faces nil
622                 ido-everywhere t)
623     (setq ido-save-directory-list-file (concat sd-temp-directory "ido.last"))
624     :config
625     (ido-mode 1)
626     (ido-everywhere 1)
627     (add-to-list 'completion-ignored-extensions ".pyc")
628
629
630     (define-key ido-buffer-completion-map (kbd "C-w") #'ido-delete-backward-word-updir)
631     (define-key ido-file-completion-map (kbd "C-w") #'ido-delete-backward-word-updir)
632     (define-key ido-file-dir-completion-map (kbd "C-w") #'ido-delete-backward-updir)
633     ;; (define-key ido-file-dir-completion-map (kbd "C-i") #'ido-copy-current-word)
634     )
635
636   (icomplete-mode t)
637 #+END_SRC
638
639 ** FLX
640 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
641   (use-package flx-ido
642     :ensure t
643     :config (flx-ido-mode nil))
644 #+END_SRC
645
646 ** IDO-vertically
647 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
648   (use-package ido-vertical-mode
649     :ensure t
650     :init
651     (setq ido-vertical-define-keys 'C-n-C-p-up-and-down)
652     :config
653     (ido-vertical-mode 1))
654 #+END_SRC
655
656 ** SMEX
657 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
658   (use-package smex
659     :ensure t
660     :init
661     (setq smex-save-file (concat sd-temp-directory "smex-items"))
662     (smex-initialize)
663     :bind
664     ("M-x" . smex)
665     ("M-X" . smex-major-mode-commands))
666 #+END_SRC
667
668 ** Ido-ubiquitous
669 Use [[https://github.com/DarwinAwardWinner/ido-ubiquitous][ido-ubiquitous]] for ido everywhere. It makes =describe-function= can also use ido
670 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
671   (use-package ido-ubiquitous
672     :ensure t
673     :init
674     (setq magit-completing-read-function 'magit-ido-completing-read)
675     (setq gnus-completing-read-function 'gnus-ido-completing-read)
676     :config
677     (ido-ubiquitous-mode 1))
678 #+END_SRC
679
680 ** Ido-exit-target
681 [[https://github.com/waymondo/ido-exit-target][ido-exit-target]] let you open file/buffer on =other-windows= when call =ido-switch-buffer=
682 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
683   (use-package ido-exit-target
684     :ensure t
685     :init
686     (mapcar #'(lambda (map)
687               (define-key map (kbd "C-j") #'ido-exit-target-other-window)
688               (define-key map (kbd "C-k") #'ido-exit-target-split-window-below))
689             (list ido-buffer-completion-map
690                   ;; ido-common-completion-map
691                   ido-file-completion-map
692                   ido-file-dir-completion-map)))
693 #+END_SRC
694
695 ** helm
696 let helm windows split inside current window
697 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
698   (with-eval-after-load 'helm
699     (setq helm-split-window-in-side-p t))
700 #+END_SRC
701
702 * Swiper & Ivy & Counsel
703 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
704   (use-package counsel
705     :ensure t
706     :defer t
707     :init
708     (use-package ivy :ensure t)
709     (ivy-mode 1)
710     (setq ivy-use-virtual-buffers nil
711           ivy-wrap t
712           ivy-count-format "%d/%d ")
713     (set-face-attribute 'ivy-current-match nil :background "Orange" :foreground "black")
714     (global-set-key (kbd "M-x") 'counsel-M-x)
715     ;; (global-set-key (kbd "C-h f") 'counsel-describe-function)
716     ;; (global-set-key (kbd "C-h v") 'counsel-describe-variable)
717     (global-set-key (kbd "C-x C-f") 'counsel-find-file)
718     (define-key read-expression-map (kbd "C-r") 'counsel-expression-history)
719     (global-set-key (kbd "C-c C-r") 'ivy-resume))
720
721   ;; (use-package counsel-projectile
722   ;;   :ensure t
723   ;;   :defer t)
724
725   (add-to-list 'load-path "~/project/counsel-projectile/")
726   (require 'counsel-projectile)
727   (setq counsel-projectile-use-buffer-preselect t)
728   (setq projectile-completion-system 'ivy)
729 #+END_SRC
730
731 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
732   (defun sd/swith-buffer-other-window ()
733     (interactive)
734     (ivy-set-action (cond ((eq (ivy-state-caller ivy-last) 'ivy-switch-buffer)
735                            'ivy--switch-buffer-other-window-action)
736                           ((eq (ivy-state-caller ivy-last) 'counsel-recentf)
737                            'find-file-other-window)
738                           ((eq (ivy-state-caller ivy-last) 'projectile-find-file)
739                            'projectile-find-file-other-window)
740                           ((eq (ivy-state-caller ivy-last) 'counsel-projectile-find-file)
741                            'counsel-projectile-find-file-action-other-window)
742                           (t
743                            nil)))
744     (ivy-done)
745     (ivy-shrink-after-dispatching))
746
747   (with-eval-after-load "ivy"
748     (define-key ivy-minibuffer-map (kbd "C-o") 'ivy-dispatching-done)
749     (define-key ivy-minibuffer-map (kbd "C-k") #'sd/swith-buffer-other-window))
750 #+END_SRC
751
752 stolen from [[https://github.com/mariolong/emacs.d/blob/f6a061594ef1b5d1f4750e9dad9dc97d6e122840/emacs-init.org][here]]
753 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
754   (use-package swiper
755     :ensure t
756     ;; :init
757     :config
758     ;; (ivy-mode)
759     (global-set-key (kbd "s-/") 'swiper)
760     (define-key swiper-map (kbd "M-r") 'swiper-query-replace)
761     (define-key swiper-map (kbd "C-.") (lambda ()
762                                          (interactive)
763                                          (insert (format "%s" (with-ivy-window (thing-at-point 'word))))))
764     (define-key swiper-map (kbd "M-.") (lambda ()
765                                          (interactive)
766                                          (insert (format "%s" (with-ivy-window (thing-at-point 'symbol)))))))
767
768 #+END_SRC
769 * Org-mode Settings
770 ** Org-mode Basic setting
771 Always indents header, and hide header leading starts so that no need type =#+STATUP: indent= 
772 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
773   (use-package org
774     :ensure t
775     :init
776     (setq org-startup-indented t)
777     (setq org-hide-leading-starts t)
778     (setq org-src-fontify-natively t)
779     (setq org-src-tab-acts-natively t)
780     (setq org-confirm-babel-evaluate nil)
781     (setq org-use-speed-commands t)
782     (setq org-completion-use-ido t)
783     (setq org-startup-with-inline-images t)
784     ;; latex preview
785     ;; (setq org-startup-with-latex-preview t)
786     ;; (setq org-format-latex-options (plist-put org-format-latex-options :scale 1.2))
787     (require 'org-habit)
788     (add-to-list 'org-modules 'org-habit)
789     (setq org-habit-graph-column 50)
790     (setq org-hide-emphasis-markers t)
791     (setq org-html-validation-link nil)
792     ;; open link when return clicked
793     (setq org-return-follows-link t)
794     ;; open the ppt file by external open instead of emacs
795     (add-to-list 'org-file-apps '("\\.pptx" . "open %s"))
796     (add-to-list 'org-file-apps '("\\.doc" . "open %s"))
797     (setq org-image-actual-width nil))
798 #+END_SRC
799
800
801 ** Org babel
802 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
803   (el-get-bundle hasu/emacs-ob-racket
804     :features ob-racket)
805
806   ;; Lua support
807   ;(use-package ob-lua
808   ;  :ensure t)
809
810   ;; use current window for org source buffer editting
811
812   (setq org-src-window-setup 'current-window )
813   (define-key org-mode-map (kbd "C-'") nil)
814   ;; C-M-i is mapped to imenu globally
815   (define-key org-mode-map (kbd "C-M-i") nil)
816   ;; set the ditta.jar path
817
818   (setq org-ditaa-jar-path "/usr/local/Cellar/ditaa/0.9/libexec/ditaa0_9.jar")
819   (unless 
820       (file-exists-p org-ditaa-jar-path)
821     (message "seudut: ditaa.jar not found at %s " org-ditaa-jar-path))
822
823   (org-babel-do-load-languages 'org-babel-load-languages
824                                '((python . t)
825                                  (C . t)
826                                  (perl . t)
827                                  (calc . t)
828                                  (latex . t)
829                                  (java . t)
830                                  (ruby . t)
831   ;                               (lua . t)
832                                  (lisp . t)
833                                  (scheme . t)
834                                  (racket . t)
835                                  (sh . t)
836                                  (sqlite . t)
837                                  (js . t)
838                                  (gnuplot . t)
839                                  (ditaa . t)
840                                  (plantuml . t)))
841
842
843   ;; toggle image preview 
844   (add-hook 'org-babel-after-execute-hook 'sd/display-inline-images 'append)
845
846   (defun sd/display-inline-images ()
847     (condition-case nil
848         (org-display-inline-images)
849       (error nil)))
850
851   ;; ditaa artist mode
852   (with-eval-after-load "artist"
853     (define-key artist-mode-map [down-mouse-3] 'artist-mouse-choose-operation))
854 #+END_SRC
855 *** plantUML
856 [[http://eschulte.github.io/babel-dev/DONE-integrate-plantuml-support.html][DONE-integrate-plantuml-support]]
857 #+BEGIN_SRC sh
858   ## support plantuml
859   brew install plantuml
860 #+END_SRC
861
862 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
863   (use-package plantuml-mode
864     :ensure t)
865
866   (setq org-plantuml-jar-path
867         (expand-file-name "/usr/local/Cellar/plantuml/8041/plantuml.8041.jar"))
868
869   (set-variable 'plantuml-jar-path
870                 (expand-file-name "/usr/local/Cellar/plantuml/8041/plantuml.8041.jar"))
871 #+END_SRC
872
873 ** Org-bullets
874 use [[https://github.com/sabof/org-bullets][org-bullets]] package to show utf-8 charactes
875 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
876   (use-package org-bullets
877     :ensure t
878     :init
879     (add-hook 'org-mode-hook (apply-partially #'org-bullets-mode t)))
880
881   (setq org-bullets-bullet-list '("⦿" "✪" "◉" "○" "►" "◆"))
882
883   ;; increase font size when enter org-src-mode
884   ;; (add-hook 'org-src-mode-hook (lambda () (text-scale-increase 2)))
885
886   ;; define a face for org-bullets
887   (defface org-bullet-face
888       '((t (:foreground "green yellow")))
889   "Face used for the org-bullets.")
890   (setq org-bullets-face-name (quote  org-bullet-face))
891   (set-face-attribute 'org-bullet-face t :foreground "burlywood" :weight 'normal :height 1.6)
892 #+END_SRC
893
894 ** Worf Mode
895 [[https://github.com/abo-abo/worf][worf]] mode is an extension of vi-like binding for org-mode. 
896 In =worf-mode=, it is mapping =[=, =]= as =worf-backward= and =worf-forward= in global, wich
897 cause we cannot input =[= and =]=, so here I unset this mappings. And redifined this two to
898 =M-[= and =M-]=. see this [[https://github.com/abo-abo/worf/issues/19#issuecomment-223756599][issue]]
899 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
900   (use-package worf
901     :ensure t
902     :commands worf-mode
903     :init
904     (require 'ivy)
905     (add-hook 'org-mode-hook 'worf-mode))
906 #+END_SRC
907
908 ** Get Things Done
909 Refer to [[http://doc.norang.ca/org-mode.html][Organize Your Life in Plain Text]]
910 *** basic setup
911 standard key binding
912 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
913   (global-set-key "\C-cl" 'org-store-link)
914   (global-set-key "\C-ca" 'org-agenda)
915   (global-set-key "\C-cb" 'org-iswitchb)
916 #+END_SRC
917
918 *** Plain List 
919 Replace the list bullet =-=, =+=,  with =•=, a litter change based [[https://github.com/howardabrams/dot-files/blob/master/emacs-org.org][here]]
920 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
921   ;; (use-package org-mode
922   ;;   :init
923   ;;   (font-lock-add-keywords 'org-mode
924   ;;    '(("^ *\\([-+]\\) "
925   ;;           (0 (prog1 () (compose-region (match-beginning 1) (match-end 1) "•")))))))
926 #+END_SRC
927  
928 *** Todo Keywords
929 refer to [[http://coldnew.github.io/coldnew-emacs/#orgheadline94][fancy todo states]], 
930 To track TODO state changes, the =!= is to insert a timetamp, =@= is to insert a note with
931 timestamp for the state change.
932 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
933     ;; (setq org-todo-keywords
934     ;;        '((sequence "☛ TODO(t)" "|" "✔ DONE(d)")
935     ;;          (sequence "⚑ WAITING(w)" "|")
936     ;;          (sequence "|" "✘ CANCELLED(c)")))
937   ; (setq org-todo-keyword-faces
938   ;        (quote ("TODO" .  (:foreground "red" :weight bold))
939   ;               ("NEXT" .  (:foreground "blue" :weight bold))
940   ;               ("WAITING" . (:foreground "forest green" :weight bold))
941   ;               ("DONE" .  (:foreground "magenta" :weight bold))
942   ;               ("CANCELLED" . (:foreground "forest green" :weight bold))))
943
944
945   (setq org-todo-keywords
946         (quote ((sequence "TODO(t)" "NEXT(n)" "|" "DONE(d!)")
947                 ;; (sequence "WAITING(w@/!)" "HOLD(h@/!)" "|" "CANCELLED(c@/!)" "PHONE" "MEETING")
948                 (sequence "WAITING(w@/!)" "HOLD(h@/!)" "|" "CANCELLED(c@/!)" ))))
949
950   (setq org-todo-keyword-faces
951         (quote (("TODO" :foreground "red" :weight bold)
952                 ("NEXT" :foreground "blue" :weight bold)
953                 ("DONE" :foreground "forest green" :weight bold)
954                 ("WAITING" :foreground "orange" :weight bold)
955                 ("HOLD" :foreground "magenta" :weight bold)
956                 ("CANCELLED" :foreground "forest green" :weight bold)
957                 ;; ("MEETING" :foreground "forest green" :weight bold)
958                 ;; ("PHONE" :foreground "forest green" :weight bold)
959                 )))
960 #+END_SRC
961
962 Fast todo selections
963
964 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
965   (setq org-use-fast-todo-selection t)
966   (setq org-treat-S-cursor-todo-selection-as-state-change nil)
967 #+END_SRC
968
969 TODO state triggers and tags, [[http://doc.norang.ca/org-mode.html][Organize Your Life in Plain Text]]
970
971 - Moving a task to =CANCELLED=, adds a =CANCELLED= tag
972 - Moving a task to =WAITING=, adds a =WAITING= tag
973 - Moving a task to =HOLD=, add =HOLD= tags
974 - Moving a task to =DONE=, remove =WAITING=, =HOLD= tag
975 - Moving a task to =NEXT=, remove all waiting/hold/cancelled tags
976
977 This tags are used to filter tasks in agenda views
978 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
979   (setq org-todo-state-tags-triggers
980         (quote (("CANCELLED" ("CANCELLED" . t))
981                 ("WAITING" ("WAITING" . t))
982                 ("HOLD" ("WAITING") ("HOLD" . t))
983                 (done ("WAITING") ("HOLD"))
984                 ("TODO" ("WAITING") ("CANCELLED") ("HOLD"))
985                 ("NEXT" ("WAITING") ("CANCELLED") ("HOLD"))
986                 ("DONE" ("WAITING") ("CANCELLED") ("HOLD")))))
987 #+END_SRC
988
989 Logging Stuff 
990 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
991   ;; log time when task done
992   ;; (setq org-log-done (quote time))
993   ;; save clocking into to LOGBOOK
994   (setq org-clock-into-drawer t)
995   ;; save state change notes and time stamp into LOGBOOK drawer
996   (setq org-log-into-drawer t)
997   (setq org-clock-into-drawer "CLOCK")
998 #+END_SRC
999
1000 *** Tags
1001 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1002   (setq org-tag-alist (quote ((:startgroup)
1003                               ("@office" . ?e)
1004                               ("@home" . ?h)
1005                               (:endgroup)
1006                               ("WAITING" . ?w)
1007                               ("HOLD" . ?h)
1008                               ("CANCELLED" . ?c))))
1009
1010   ;; Allow setting single tags without the menu
1011   (setq org-fast-tag-selection-single-key (quote expert))
1012 #+END_SRC
1013
1014 *** Capture - Refile - Archive
1015
1016 Capture lets you quickly store notes with little interruption of your work flow.
1017
1018 **** Capture Templates
1019
1020 When a new taks needs to be added, categorize it as 
1021
1022 All captured file which need next actions are stored in =refile.org=, 
1023 - A new task / note (t) =refile.org=
1024 - A work task in office =office.org=
1025 - A jourenl =diary.org=
1026 - A new habit (h) =refile.org=
1027
1028 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1029   (setq org-directory "~/org")
1030   (setq org-default-notes-file "~/org/refile.org")
1031   (setq sd/org-diary-file "~/org/diary.org")
1032
1033   (global-set-key (kbd "C-c c") 'org-capture)
1034
1035   (setq org-capture-templates
1036         (quote (("t" "Todo" entry (file org-default-notes-file)
1037                  "* TODO %?\n:LOGBOOK:\n- Added: %U\t\tAt: %a\n:END:")
1038                 ("n" "Note" entry (file org-default-notes-file)
1039                  "* %? :NOTE:\n:LOGBOOK:\n- Added: %U\t\tAt: %a\n:END:")
1040                 ("j" "Journal" entry (file+datetree sd/org-diary-file)
1041                  "* %?\n:LOGBOOK:\n:END:" :clock-in t :clock-resume t)
1042                 ("h" "Habit" entry (file org-default-notes-file)
1043                  "* NEXT %?\n:LOGBOOK:\n%a\nSCHEDULED: %(format-time-string \"%<<%Y-%m-%d %a .+1d/3d>>\")\n:END:\n:PROPERTIES:\n:STYLE: habit\n:REPEAT_TO_STATE: NEXT\n:END:\n "))))
1044 #+END_SRC
1045
1046 **** Refiling Tasks
1047
1048 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1049   (setq org-refile-targets (quote (;; (nil :maxlevel . 9)
1050                                    (org-agenda-files :maxlevel . 9))))
1051
1052   (setq org-refile-use-outline-path t)
1053
1054   (setq org-refile-allow-creating-parent-nodes (quote confirm))
1055 #+END_SRC
1056
1057 *** Agenda Setup
1058 Setting agenda files and the agenda view
1059 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1060   (setq org-agenda-files (quote ("~/org/gtd.org")))
1061
1062   ;; only show today's tasks in agenda view
1063   ;; (setq org-agenda-span 'day)
1064   ;; Use current windows for agenda view
1065   ;; (setq org-agenda-window-setup 'current-window)
1066
1067   ;; show all feature entries for repeating tasks,
1068   ;; this is already setting by default
1069   (setq org-agenda-repeating-timestamp-show-all t)
1070
1071   ;; Show all agenda dates - even if they are empty
1072   (setq org-agenda-show-all-dates t)
1073 #+END_SRC
1074
1075 ** Org mobile
1076 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1077   (with-eval-after-load "org"
1078     (require 'org-mobile)
1079     ;; Set to the location of your Org files on your local system
1080     ;; (setq org-directory "~/org")
1081     ;; Set to the name of the file where new notes will be stored
1082     (setq org-mobile-inbox-for-pull "~/org/flagged.org")
1083     ;; Set to <your Dropbox root directory>/MobileOrg.
1084     (setq org-mobile-directory "~/Dropbox/Apps/MobileOrg"))
1085 #+END_SRC
1086
1087 ** Export PDF
1088 Install MacTex-basic [[http://www.tug.org/mactex/morepackages.html][MacTex-basic]]  and some tex packages
1089 #+BEGIN_SRC sh 
1090   wget http://tug.org/cgi-bin/mactex-download/BasicTeX.pkg
1091
1092   sudo tlmgr update --self
1093
1094   sudo tlmgr install titlesec framed threeparttable wrapfig multirow enumitem bbding titling tabu mdframed tcolorbox textpos import varwidth needspace tocloft ntheorem environ trimspaces collection-fontsrecommended capt-of
1095 #+END_SRC
1096
1097 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1098   ;; ;; allow for export=>beamer by placing
1099
1100   ;; http://emacs-fu.blogspot.com/2011/04/nice-looking-pdfs-with-org-mode-and.html
1101   ;; #+LaTeX_CLASS: beamer in org files
1102   (unless (boundp 'org-export-latex-classes)
1103     (setq org-export-latex-classes nil))
1104   (add-to-list 'org-export-latex-classes
1105     ;; beamer class, for presentations
1106     '("beamer"
1107        "\\documentclass[11pt]{beamer}\n
1108         \\mode<{{{beamermode}}}>\n
1109         \\usetheme{{{{beamertheme}}}}\n
1110         \\usecolortheme{{{{beamercolortheme}}}}\n
1111         \\beamertemplateballitem\n
1112         \\setbeameroption{show notes}
1113         \\usepackage[utf8]{inputenc}\n
1114         \\usepackage[T1]{fontenc}\n
1115         \\usepackage{hyperref}\n
1116         \\usepackage{color}
1117         \\usepackage{listings}
1118         \\lstset{numbers=none,language=[ISO]C++,tabsize=4,
1119     frame=single,
1120     basicstyle=\\small,
1121     showspaces=false,showstringspaces=false,
1122     showtabs=false,
1123     keywordstyle=\\color{blue}\\bfseries,
1124     commentstyle=\\color{red},
1125     }\n
1126         \\usepackage{verbatim}\n
1127         \\institute{{{{beamerinstitute}}}}\n          
1128          \\subject{{{{beamersubject}}}}\n"
1129
1130        ("\\section{%s}" . "\\section*{%s}")
1131  
1132        ("\\begin{frame}[fragile]\\frametitle{%s}"
1133          "\\end{frame}"
1134          "\\begin{frame}[fragile]\\frametitle{%s}"
1135          "\\end{frame}")))
1136
1137     ;; letter class, for formal letters
1138
1139     (add-to-list 'org-export-latex-classes
1140
1141     '("letter"
1142        "\\documentclass[11pt]{letter}\n
1143         \\usepackage[utf8]{inputenc}\n
1144         \\usepackage[T1]{fontenc}\n
1145         \\usepackage{color}"
1146  
1147        ("\\section{%s}" . "\\section*{%s}")
1148        ("\\subsection{%s}" . "\\subsection*{%s}")
1149        ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
1150        ("\\paragraph{%s}" . "\\paragraph*{%s}")
1151        ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
1152
1153
1154   (require 'ox-md)
1155   (require 'ox-beamer)
1156
1157   (setq org-latex-pdf-process
1158         '("pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
1159           "pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
1160           "pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"))
1161
1162   (setq TeX-parse-self t)
1163
1164   (setq TeX-PDF-mode t)
1165   (add-hook 'LaTeX-mode-hook
1166             (lambda ()
1167               (LaTeX-math-mode)
1168               (setq TeX-master t)))
1169
1170 #+END_SRC
1171
1172 ** Export Html
1173 Color higlight the source code block in exported html, [[http://stackoverflow.com/questions/24082430/org-mode-no-syntax-highlighting-in-exported-html-page][org-mode-no-syntax-highlighting-in-exported-html-page]]
1174 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1175   (use-package htmlize
1176     :ensure t)
1177 #+END_SRC
1178
1179 ** Org structure template
1180 extend org-mode's easy templates, refer to [[http://coldnew.github.io/coldnew-emacs/#orgheadline94][Extend org-modes' esay templates]]
1181 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1182   ;; ‘s’     ‘#+BEGIN_SRC ... #+END_SRC’
1183   ;; ‘e’     ‘#+BEGIN_EXAMPLE ... #+END_EXAMPLE’
1184   ;; ‘q’     ‘#+BEGIN_QUOTE ... #+END_QUOTE’
1185   ;; ‘v’     ‘#+BEGIN_VERSE ... #+END_VERSE’
1186   ;; ‘c’     ‘#+BEGIN_CENTER ... #+END_CENTER’
1187   ;; ‘l’     ‘#+BEGIN_LaTeX ... #+END_LaTeX’
1188   ;; ‘L’     ‘#+LaTeX:’
1189   ;; ‘h’     ‘#+BEGIN_HTML ... #+END_HTML’
1190   ;; ‘H’     ‘#+HTML:’
1191   ;; ‘a’     ‘#+BEGIN_ASCII ... #+END_ASCII’
1192   ;; ‘A’     ‘#+ASCII:’
1193   ;; ‘i’     ‘#+INDEX:’ line
1194   ;; ‘I’     ‘#+INCLUDE:’ line
1195
1196
1197   (add-to-list 'org-structure-template-alist
1198                '("E" "#+BEGIN_SRC emacs-lisp :tangle yes :results silent\n?\n#+END_SRC"))
1199   (add-to-list 'org-structure-template-alist
1200                '("R" "#+BEGIN_SRC racket :tangle no :results output replace\n?\n#+END_SRC"))
1201   (add-to-list 'org-structure-template-alist
1202                '("S" "#+BEGIN_SRC sh :results output replace\n?\n#+END_SRC"))
1203   (add-to-list 'org-structure-template-alist
1204                '("p" "#+BEGIN_SRC plantuml :file uml.png \n?\n#+END_SRC"))
1205   (add-to-list 'org-structure-template-alist
1206                '("P" "#+BEGIN_SRC perl \n?\n#+END_SRC"))
1207   (add-to-list 'org-structure-template-alist
1208                '("f" "#+BEGIN_SRC fundamental :tangle ?\n\n#+END_SRC"))
1209   (add-to-list 'org-structure-template-alist
1210                '("C" "#+BEGIN_SRC c :tangle ?\n\n#+END_SRC"))
1211   (add-to-list 'org-structure-template-alist
1212                '("m" "\\begin{equation}\n?\n\\end{equation}"))
1213   (add-to-list 'org-structure-template-alist
1214                '("b" "#+STARTUP: showall
1215   ,#+STARTUP: inlineimages
1216   ,#+OPTIONS: toc:nil\n"))
1217   (add-to-list 'org-structure-template-alist
1218                '("d" "#+BEGIN_SRC ditaa :file ?  :cmdline -r -s 0.8 :cache yes \n\n#+END_SRC"))
1219   (add-to-list 'org-structure-template-alist
1220                '("u" "#+BEGIN_SRC plantuml :file ? \n\n#+END_SRC"))
1221
1222 #+END_SRC
1223
1224 ** Org theme
1225 *** variable-pitch-mode and fixed-pitch-mode
1226 [[https://yoo2080.wordpress.com/2013/05/30/monospace-font-in-tables-and-source-code-blocks-in-org-mode-proportional-font-in-other-parts/][monospace font in tables and source code blocks in org-mode, proportional font in other parts]]
1227 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1228   (when (display-graphic-p)
1229     (unless (find-font (font-spec :name "Ubuntu Mono"))
1230       (warn "Font not found Ubuntu Mono"))
1231     (unless (find-font (font-spec :name "Source Code Pro"))
1232       (warn "Font not found Source Code Pro"))
1233     (unless (find-font (font-spec :name "Source Sans Pro"))
1234       (warn "Font not found Source Sans Pro")))
1235
1236   (set-face-attribute 'variable-pitch nil :font "Source Sans Pro" :height 160)
1237   (set-face-attribute 'fixed-pitch nil :font "Source Code Pro" :height (face-attribute 'default :height))
1238
1239
1240   ;; Install Ubuntu Mono fonts and apply it in org-table to align Chinese fonts
1241   ;; (with-eval-after-load "org"
1242   ;;   (mapc (lambda (face)
1243   ;;           (set-face-attribute face nil :inherit 'fixed-pitch))
1244   ;;         (list
1245   ;;          'org-code
1246   ;;          'org-block
1247   ;;          'org-block-background
1248   ;;          'org-block-begin-line
1249   ;;          'org-block-end-line))
1250   ;;   (set-face-attribute 'org-table nil :family "Ubuntu Mono" :height 140)
1251   ;;   (set-face-attribute 'org-formula nil :family "Ubuntu Mono" :height 140)
1252   ;;   ;; org-special-keyword inherited from font-lock-keywork originally; as org is changed to variable-pitch, it cause
1253   ;;   ;; the font in special-keywords are not monospace
1254   ;;   (set-face-attribute 'org-special-keyword nil :inherit '(font-lock-keyword-face fixed-pitch))
1255   ;;   ;; same as above 
1256   ;;   (set-face-attribute 'org-verbatim nil :inherit '(shadow fixed-pitch))
1257   ;;   (set-face-attribute 'org-block-begin-line nil :inherit 'shadow :slant 'italic :foreground nil)
1258   ;;   (set-face-attribute 'org-block-end-line nil :inherit 'shadow :slant 'italic :foreground nil)
1259     
1260   ;;   ;; fix indent broken by variable-pitch-mode
1261   ;;   ;; http://emacs.stackexchange.com/questions/26864/variable-pitch-face-breaking-indentation-in-org-mode
1262   ;;   (require 'org-indent)
1263   ;;   (set-face-attribute 'org-indent nil :inherit '(org-hide fixed-pitch)))
1264
1265   ;; (with-eval-after-load "org"
1266   ;;   (let ((default-font-size (- (face-attribute 'default :height) (if (display-graphic-p) 20 0))))
1267   ;;     (set-face-attribute 'org-code nil :height default-font-size)
1268   ;;     (set-face-attribute 'org-block nil :height default-font-size)
1269   ;;     (set-face-attribute 'org-block-begin-line nil :background nil :foreground nil :inherit 'shadow :slant 'italic :height default-font-size)
1270   ;;     (set-face-attribute 'org-block-end-line nil :background nil :foreground nil :inherit 'shadow :slant 'italic :height default-font-size)
1271   ;;     (when (find-font (font-spec :name "Ubuntu Mono"))
1272   ;;       (set-face-attribute 'org-table nil :family "Ubutu Mono" :height default-font-size)
1273   ;;       (set-face-attribute 'org-formula nil :family "Ubutu Mono" :height default-font-size))))
1274
1275   (add-hook 'org-mode-hook
1276             (lambda ()
1277               (let ((default-font-size (- (face-attribute 'default :height) (if (display-graphic-p) 20 0))))
1278                 (set-face-attribute 'org-code nil :height default-font-size)
1279                 (set-face-attribute 'org-block nil :height default-font-size)
1280                 (set-face-attribute 'org-block-begin-line nil :background nil :foreground nil :inherit 'shadow :slant 'italic :height default-font-size)
1281                 (set-face-attribute 'org-block-end-line nil :background nil :foreground nil :inherit 'shadow :slant 'italic :height default-font-size)
1282                 (when (find-font (font-spec :name "Ubuntu Mono"))
1283                   (set-face-attribute 'org-table nil :family "Ubutu Mono" :height default-font-size)
1284                   (set-face-attribute 'org-formula nil :family "Ubutu Mono" :height default-font-size)))))
1285 #+END_SRC
1286
1287 Also correct the face of  =org-meta-line= in =org-table= 
1288 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1289   (with-eval-after-load "org"
1290     (set-face-attribute 'org-meta-line nil :font "Source Code Pro" :height 120 :slant 'italic :inherit 'font-lock-comment-face))
1291 #+END_SRC
1292
1293 *** Org-head face
1294 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1295   ;; (with-eval-after-load "org"
1296   ;;   (let* ((base-height (face-attribute 'variable-pitch :height))
1297   ;;          (base-font-color (face-foreground 'default nil  'default)))
1298   ;;     (set-face-attribute 'org-document-title nil :weight 'bold :height (+ 60 base-height))
1299   ;;     (set-face-attribute 'org-level-1 nil :weight 'bold :height (+ 40 base-height))
1300   ;;     (set-face-attribute 'org-level-2 nil :weight 'bold :height (+ 30 base-height))
1301   ;;     (set-face-attribute 'org-level-3 nil :weight 'bold :height (+ 20 base-height))
1302   ;;     (set-face-attribute 'org-level-4 nil :weight 'bold :height (+ 10 base-height))
1303   ;;     (set-face-attribute 'org-level-5 nil :weight 'bold)
1304   ;;     (set-face-attribute 'org-level-6 nil :weight 'bold)
1305   ;;     (set-face-attribute 'org-level-7 nil :weight 'bold)
1306   ;;     (set-face-attribute 'org-level-8 nil :weight 'bold)))
1307 #+END_SRC
1308
1309 ** Org Blog
1310 Fetch dependencies file, which is not in this repository.
1311 #+BEGIN_SRC perl :results silent :tangle yes
1312   print `curl https://raw.githubusercontent.com/seudut/blog/master/my-publish.el -o ./elisp/my-publish.el`;
1313 #+END_SRC
1314
1315 Load 
1316 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1317   (add-to-list 'load-path "~/.emacs.d/elisp")
1318
1319   (when (file-exists-p "~/.emacs.d/elisp/my-publish.el")
1320     (require 'my-publish)
1321     (blog-setup-project-alist "~/Private/blog/"))
1322 #+END_SRC
1323
1324
1325 Refer to [[http://orgmode.org/worg/org-tutorials/org-publish-html-tutorial.html][org-publish-html-tutorial]], and [[https://ogbe.net/blog/blogging_with_org.html][blogging_with_org]]
1326
1327 * Magit
1328 [[https://github.com/magit/magit][Magit]] is a very cool git interface on Emacs.
1329 and Defined keys, using vi keybindings, Refer abo-abo's setting [[https://github.com/abo-abo/oremacs/blob/c5cafdcebc88afe9e73cc8bd40c49b70675509c7/modes/ora-nextmagit.el][here]]
1330 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1331   (use-package magit
1332     :ensure t
1333     :init
1334     ;; don't ask me to confirm the unsaved change 
1335     (setq magit-save-repository-buffers nil)
1336     ;; default is 50
1337     (setq git-commit-summary-max-length 100)
1338     :commands magit-status magit-blame
1339     :config
1340     (dolist (map (list magit-status-mode-map
1341                        magit-log-mode-map
1342                        magit-diff-mode-map
1343                        magit-staged-section-map))
1344       (define-key map "j" 'magit-section-forward)
1345       (define-key map "k" 'magit-section-backward)
1346       (define-key map "D" 'magit-discard)
1347       (define-key map "O" 'magit-discard-file)
1348       (define-key map "n" nil)
1349       (define-key map "p" nil)
1350       (define-key map "v" 'recenter-top-bottom)
1351       (define-key map "i" 'magit-section-toggle))
1352     (define-key magit-mode-map "q" (lambda () (interactive)
1353                                      (magit-mode-bury-buffer t))))
1354 #+END_SRC
1355
1356 * Eshell
1357 ** Eshell alias
1358 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1359   (defalias 'e 'find-file)
1360   (defalias 'ff 'find-file)
1361   (defalias 'ee 'find-files)
1362 #+END_SRC
1363
1364 ** eshell temp directory
1365 set default eshell history folder
1366 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1367   (setq eshell-directory-name (concat  sd-temp-directory "eshell"))
1368 #+END_SRC
1369
1370 ** Eshell erase buffer
1371 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1372   (require 'utilities)
1373
1374   ;; (add-hook 'eshell-mode-hook (lambda ()
1375   ;;                               (local-set-key (kbd "C-l") 'sd/eshell-clear-buffer)))
1376   ;; (add-hook 'eshell-mode-map (lambda () (interactive)
1377   ;;                              (define-key eshell-mode-map (kbd "<tab>") 'completion-at-point)))
1378
1379   (defun sd/eshell-hook ()
1380     (interactive)
1381     (define-key eshell-mode-map (kbd "C-j") #'eshell-send-input)
1382     (define-key eshell-mode-map (kbd "C-l") #'sd/eshell-clear-buffer))
1383
1384   (add-hook 'eshell-mode-hook #'sd/eshell-hook)
1385
1386
1387   ;; (add-hook 'eshell-mode-hook (apply-partially #'local-set-key (kbd "C-l") 'sd/eshell-clear-buffer))
1388 #+END_SRC
1389
1390 ** Toggle Eshell
1391 Toggle an eshell in split window below, refer [[http://www.howardism.org/Technical/Emacs/eshell-fun.html][eshell-here]]
1392 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1393   (defun sd/window-has-eshell ()
1394     "Check if current windows list has a eshell buffer, and return the window"
1395     (interactive)
1396     (let ((ret nil))
1397       (walk-windows (lambda (window)
1398                       (if (equal (with-current-buffer (window-buffer window) major-mode)
1399                                  'eshell-mode)
1400                           (setq ret window)))
1401                     nil nil)
1402       ret))
1403
1404   (defun sd/toggle-project-eshell ()
1405     "Toggle a eshell buffer vertically"
1406     (interactive)
1407     (if (sd/window-has-eshell)
1408         (if (equal major-mode 'eshell-mode)
1409             (progn
1410               (if (equal (length (window-list)) 1)
1411                   (mode-line-other-buffer)
1412                 (delete-window)))
1413           (select-window (sd/window-has-eshell)))
1414       (progn
1415         (split-window-vertically (- (/ (window-total-height) 3)))
1416         (other-window 1)
1417         (if (projectile-project-p)
1418             (projectile-run-eshell)
1419           (eshell)))))
1420
1421   (global-set-key (kbd "s-e") 'sd/toggle-project-eshell)
1422 #+END_SRC
1423
1424 ** exec-path-from-shell
1425 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1426   (use-package exec-path-from-shell
1427     :ensure t
1428     :init
1429     (setq exec-path-from-shell-check-startup-files nil)
1430     :config
1431     (exec-path-from-shell-initialize))
1432 #+END_SRC
1433
1434 * Misc Settings
1435 ** [[https://github.com/abo-abo/hydra][Hydra]]
1436 *** hydra install
1437 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1438   (use-package hydra
1439     :ensure t
1440     ;; disable new line in minibuffer when hint hydra
1441     :init
1442     (setq hydra-lv nil))
1443 #+END_SRC
1444
1445 *** Windmove Splitter
1446
1447 Refer [[https://github.com/abo-abo/hydra/blob/master/hydra-examples.el][hydra-example]], to enlarge or shrink the windows splitter
1448
1449 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1450
1451   (defun hydra-move-splitter-left (arg)
1452     "Move window splitter left."
1453     (interactive "p")
1454     (if (let ((windmove-wrap-around))
1455           (windmove-find-other-window 'right))
1456         (shrink-window-horizontally arg)
1457       (enlarge-window-horizontally arg)))
1458
1459   (defun hydra-move-splitter-right (arg)
1460     "Move window splitter right."
1461     (interactive "p")
1462     (if (let ((windmove-wrap-around))
1463           (windmove-find-other-window 'right))
1464         (enlarge-window-horizontally arg)
1465       (shrink-window-horizontally arg)))
1466
1467   (defun hydra-move-splitter-up (arg)
1468     "Move window splitter up."
1469     (interactive "p")
1470     (if (let ((windmove-wrap-around))
1471           (windmove-find-other-window 'up))
1472         (enlarge-window arg)
1473       (shrink-window arg)))
1474
1475   (defun hydra-move-splitter-down (arg)
1476     "Move window splitter down."
1477     (interactive "p")
1478     (if (let ((windmove-wrap-around))
1479           (windmove-find-other-window 'up))
1480         (shrink-window arg)
1481       (enlarge-window arg)))
1482
1483 #+END_SRC
1484
1485 *** hydra misc
1486 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1487   (defhydra sd/hydra-misc (:color red :columns nil)
1488     "Misc"
1489     ("e" eshell "eshell" :exit t)
1490     ("p" (lambda ()
1491            (interactive)
1492            (if (not (eq nil (get-buffer "*Packages*")))
1493                (switch-to-buffer "*Packages*")
1494              (package-list-packages)))
1495      "list-package" :exit t)
1496     ("g" magit-status "git-status" :exit t)
1497     ("'" mode-line-other-buffer "last buffer" :exit t)
1498     ("C-'" mode-line-other-buffer "last buffer" :exit t)
1499     ("m" man "man" :exit t)
1500     ("d" dired-jump "dired" :exit t)
1501     ("b" ibuffer "ibuffer" :exit t)
1502     ("q" nil "quit")
1503     ("f" nil "quit"))
1504
1505   ;; (global-set-key (kbd "C-'") 'sd/hydra-misc/body)
1506
1507   (defun sd/exchange-win-layout ()
1508     "Change the windos layout."
1509     (interactive)
1510     (when (equal (length (window-list)) 2)
1511       (let ((current-layout (if (or (window-in-direction 'right) (window-in-direction 'left))
1512                                 'v
1513                               'h))
1514             (other-buf (window-buffer (or (window-in-direction 'right)
1515                                           (window-in-direction 'left)
1516                                           (window-in-direction 'below)
1517                                           (window-in-direction 'above)))))
1518         (delete-other-windows)
1519         (if (eq current-layout 'v)
1520             (split-window-below)
1521           (split-window-right))
1522         (other-window 1)
1523         (switch-to-buffer other-buf))))
1524
1525   (defhydra sd/hydra-window-layout (:color red :colums nil)
1526     "Window Layout"
1527     ("m" sd/toggle-max-windows "Max-win" :exit t)
1528     ("s" ace-swap-window "Swap" :exit t)
1529     ("d" ace-delete-window "Delete"  :exit t)
1530     ("x" sd/exchange-win-layout "eXchange"  :exit t)
1531     ("u" winner-undo "window-Undo"  :exit t)
1532     ("r" winner-redo "window-Redo"  :exit t))
1533
1534   (defhydra sd/hydra-gtags (:color red :colums nil)
1535     "ggtags - global"
1536     ("d" sd/ggtags-find-definition "Definition" :exit t)
1537     ("r" ggtags-find-reference "Reference" :exit t)
1538     ("s" sd/ggtags-find-symbol "Symbol" :exit t))
1539
1540   (defhydra sd/hydra-projectile (:color red :column nil)
1541     "Projectile: "
1542     ("s" projectile-switch-open-project "Switch" :exit t)
1543     ("f" projectile-find-file "File" :exit t)
1544     ("b" projectile-switch-to-buffer "Buffer" :exit t))
1545
1546
1547
1548 #+END_SRC
1549
1550 *** hydra launcher
1551 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1552   (defhydra sd/hydra-launcher (:color blue :columns 2)
1553     "Launch"
1554     ("e" emms "emms" :exit t)
1555     ("q" nil "cancel"))
1556 #+END_SRC
1557
1558 ** Line Number
1559 Enable linum mode on programming modes
1560 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1561   (add-hook 'prog-mode-hook 'linum-mode)
1562 #+END_SRC
1563
1564 Fix the font size of line number
1565 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1566   (defun fix-linum-size ()
1567     (interactive)
1568     (set-face-attribute 'linum nil :height 110))
1569
1570   (add-hook 'linum-mode-hook 'fix-linum-size)
1571 #+END_SRC
1572
1573 I like [[https://github.com/coldnew/linum-relative][linum-relative]], just like the =set relativenumber= on =vim=
1574 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1575   (use-package linum-relative
1576     :ensure t
1577     :init
1578     (setq linum-relative-current-symbol "")
1579     :config
1580     (defun linum-new-mode ()
1581       "If line numbers aren't displayed, then display them.
1582   Otherwise, toggle between absolute and relative numbers."
1583       (interactive)
1584       (if linum-mode
1585           (linum-relative-toggle)
1586         (linum-mode 1)))
1587
1588     :bind
1589     ("A-k" . linum-new-mode))
1590
1591   ;; auto enable linum-new-mode in programming modes
1592   (add-hook 'prog-mode-hook 'linum-relative-mode)
1593 #+END_SRC
1594
1595 ** Save File Position
1596 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1597   (require 'saveplace)
1598   (setq save-place-file "~/.emacs.d/temp/saveplace")
1599   (setq-default save-place t)
1600   (setq save-place-forget-unreadable-files t)
1601   (setq save-place-skip-check-regexp "\\`/\\(?:cdrom\\|floppy\\|mnt\\|/[0-9]\\|\\(?:[^@/:]*@\\)?[^@/:]*[^@/:.]:\\)")
1602 #+END_SRC
1603
1604 ** Multi-term
1605 define =multi-term= mapping to disable some mapping which is used globally.
1606 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1607   (use-package multi-term
1608     :ensure t)
1609
1610   (defun sd/term-mode-mapping ()
1611     (mapcar #'(lambda (map)
1612               (define-key map (kbd "C-o") nil)
1613               (define-key map (kbd "C-g") nil))
1614             (list term-mode-map
1615                   term-raw-map)))
1616
1617   (with-eval-after-load 'multi-term
1618     (sd/term-mode-mapping))
1619 #+END_SRC
1620
1621 ** ace-link
1622 [[https://github.com/abo-abo/ace-link][ace-link]] is a package written by [[https://github.com/abo-abo][Oleh Krehel]]. It is convenient to jump to link in help mode, info-mode, etc
1623 Type =o= to go to the link
1624 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1625   (use-package ace-link
1626     :ensure t
1627     :init
1628     (ace-link-setup-default))
1629 #+END_SRC
1630
1631 ** Smart Parens
1632 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1633   ;; (use-package smartparens
1634   ;;   :ensure t
1635   ;;   :config
1636   ;;   (progn
1637   ;;     (require 'smartparens-config)
1638   ;;     (add-hook 'prog-mode-hook 'smartparens-mode)))
1639 #+END_SRC
1640
1641 ** Ace-Windows
1642 [[https://github.com/abo-abo/ace-window][ace-window]] 
1643 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1644   (use-package ace-window
1645     :ensure t
1646     :defer t
1647                                           ;  :init
1648                                           ;  (global-set-key (kbd "M-o") 'ace-window)
1649     :config
1650     (setq aw-keys '(?a ?s ?d ?f ?j ?k ?l)))
1651 #+END_SRC
1652
1653 ** Which key
1654 [[https://github.com/justbur/emacs-which-key][which-key]] show the key bindings 
1655 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1656   ;; (use-package which-key
1657   ;;   :ensure t
1658   ;;   :config
1659   ;;   (which-key-mode))
1660 #+END_SRC
1661
1662 ** View only for some directory
1663 When see function by =C-h f=, and visit the source code, I would like the buffer is read only. See [[http://emacs.stackexchange.com/questions/3676/how-to-enter-view-only-mode-when-browsing-emacs-source-code-from-help/3681#3681][here]]
1664 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1665   (dir-locals-set-class-variables
1666    'emacs
1667    '((nil . ((buffer-read-only . t)
1668              (show-trailing-whitespace . nil)
1669              (tab-width . 8)
1670              (eval . (whitespace-mode -1))
1671              ;; (eval . (when buffer-file-name
1672              ;;           (setq-local view-no-disable-on-exit t)
1673              ;;           (view-mode-enter)))
1674              (projectile-enable-caching . nil)
1675              ))))
1676
1677   ;; (dir-locals-set-directory-class (expand-file-name "/usr/local/share/emacs") 'emacs)
1678   (dir-locals-set-directory-class "/usr/local/Cellar/emacs" 'emacs)
1679   ;; (dir-locals-set-directory-class "~/.emacs.d/elpa" 'emacs)
1680   (dir-locals-set-directory-class "~/dotfiles/emacs.d/elpa" 'emacs)
1681   (dir-locals-set-directory-class "~/dotfiles/emacs.d/el-get" 'emacs)
1682
1683   ;; temp-mode.el
1684   ;; Temporary minor mode
1685   ;; Main use is to enable it only in specific buffers to achieve the goal of
1686   ;; buffer-specific keymaps
1687
1688   ;; (defvar sd/temp-mode-map (make-sparse-keymap)
1689   ;;   "Keymap while temp-mode is active.")
1690
1691   ;; ;;;###autoload
1692   ;; (define-minor-mode sd/temp-mode
1693   ;;   "A temporary minor mode to be activated only specific to a buffer."
1694   ;;   nil
1695   ;;   :lighter " Temp"
1696   ;;   sd/temp-mode-map)
1697
1698   ;; (defun sd/temp-hook ()
1699   ;;   (if sd/temp-mode
1700   ;;       (progn
1701   ;;      (define-key sd/temp-mode-map (kbd "q") 'quit-window))))
1702
1703   ;; (add-hook 'lispy-mode-hook (lambda ()
1704   ;;                           (sd/temp-hook)))
1705 #+END_SRC
1706
1707 ** Info plus
1708 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1709   (el-get-bundle info+
1710     :url "https://raw.githubusercontent.com/emacsmirror/emacswiki.org/master/info+.el"
1711     ;; (require 'info+)
1712     )
1713
1714   (with-eval-after-load 'info
1715     (require 'info+))
1716 #+END_SRC
1717
1718 ** advice info
1719 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1720   (defun sd/info-mode ()
1721     (interactive)
1722     (unless (equal major-mode 'Info-mode)
1723       (unless (> (length (window-list)) 1)
1724         (split-window-right))
1725       (other-window 1)))
1726
1727   ;; open Info buffer in other window instead of current window
1728   (defadvice info (before my-info (&optional file buf) activate)
1729     (sd/info-mode))
1730
1731   (defadvice Info-exit (after my-info-exit activate)
1732     (sd/delete-current-window))
1733 #+END_SRC
1734
1735 ** Demo It
1736 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1737   (use-package org-tree-slide
1738     :ensure t)
1739 #+END_SRC
1740
1741 ** Presentation
1742 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1743   (use-package org-tree-slide
1744     :ensure
1745     :config
1746     ;; (define-key org-mode-map "\C-ccp" 'org-tree-slide-mode)
1747     (define-key org-tree-slide-mode-map (kbd "<ESC>") 'org-tree-slide-content)
1748     (define-key org-tree-slide-mode-map (kbd "<SPACE>") 'org-tree-slide-move-next-tree)
1749     (define-key org-tree-slide-mode-map [escape] 'org-tree-slide-move-previous-tree))
1750 #+END_SRC
1751
1752 ** pdf-tools
1753 #+BEGIN_SRC sh
1754   #brew install poppler
1755 #+END_SRC
1756
1757 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1758   ;(use-package pdf-tools
1759   ;  :ensure t
1760   ;  :init
1761   ;  ;; run to complete the installation
1762   ;  (pdf-tools-install)
1763   ;  :config
1764   ;  (add-to-list 'auto-mode-alist '("\.pdf$" . pdf-view-mode))
1765   ;  (add-hook 'pdf-outline-buffer-mode-hook #'sd/pdf-outline-map))
1766
1767   ;(defun sd/pdf-outline-map ()
1768   ;  "My keybindings in pdf-outline-map"
1769   ;  (interactive)
1770   ;  (define-key pdf-outline-buffer-mode-map (kbd "C-o") nil)
1771   ;  (define-key pdf-outline-buffer-mode-map (kbd "i") 'outline-toggle-children)
1772   ;  (define-key pdf-outline-buffer-mode-map (kbd "j") 'next-line)
1773    ; (define-key pdf-outline-buffer-mode-map (kbd "k") 'previous-line))
1774 #+END_SRC
1775
1776 ** help-mode
1777 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1778   (defun sd/help-mode-hook ()
1779     "Mapping for help mode"
1780     (define-key help-mode-map "j" 'next-line)
1781     (define-key help-mode-map "k" 'previous-line)
1782     (define-key help-mode-map "h" 'forward-char)
1783     (define-key help-mode-map "l" 'forward-char)
1784     (define-key help-mode-map "H" 'describe-mode)
1785     (define-key help-mode-map "v" 'recenter-top-bottom)
1786     (define-key help-mode-map "i" 'forward-button)
1787     (define-key help-mode-map "I" 'backward-button)
1788     (define-key help-mode-map "o" 'ace-link-help))
1789
1790   (add-hook 'help-mode-hook 'sd/help-mode-hook)
1791 #+END_SRC
1792
1793 Wiki [[http://stackoverflow.com/questions/3480173/show-keys-in-emacs-keymap-value][show-keys-in-emacs-keymap-value]], Helpplus mode can show keymap as human-readable, use ~describe-keymap~ or =C-h M-k=
1794
1795 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1796   (el-get-bundle help-macro+
1797     :url "https://raw.githubusercontent.com/emacsmirror/emacswiki.org/master/help-macro+.el"
1798     :features help-macro+)
1799   (el-get-bundle help+
1800     :url "https://raw.githubusercontent.com/emacsmirror/emacswiki.org/master/help+.el"
1801     :features help+)
1802   (el-get-bundle help-fns+
1803     :url "https://raw.githubusercontent.com/emacsmirror/emacswiki.org/master/help-fns+.el"
1804     :features help-fns+)
1805   (el-get-bundle help-mode+
1806     :url "https://raw.githubusercontent.com/emacsmirror/emacswiki.org/master/help-mode+.el"
1807     :features help-mode+)
1808 #+END_SRC
1809
1810 ** goto-last-change
1811 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1812   ;; (use-package goto-last-change
1813   ;;   :ensure t)
1814 #+END_SRC
1815
1816 ** Ag
1817 install =ag=, =the-silver-searcher= by homebrew on mac
1818 #+BEGIN_SRC sh
1819 brew install the-silver-searcher
1820 #+END_SRC
1821
1822 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1823   (use-package ag
1824     :ensure t)
1825 #+END_SRC
1826
1827 ** Local Variable hooks
1828 [[https://www.emacswiki.org/emacs/LocalVariables][LocalVariables]], use =hack-local-variables-hook=, run a hook to set local variable in mode hook
1829 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1830   ;; make Emacs run a new "local variables hook" for each major mode
1831   (add-hook 'hack-local-variables-hook 'run-local-vars-mode-hook)
1832
1833   (defun run-local-vars-mode-hook ()
1834     "Run a hook for the major-mode after the local variables have been processed."
1835     (run-hooks (intern (concat (symbol-name major-mode) "-local-vars-hook"))))
1836
1837   ;;   (add-hook 'c++-mode-local-vars-hook #'sd/c++-mode-local-vars)
1838 #+END_SRC
1839
1840 ** Table
1841 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1842   (add-hook 'text-mode-hook 'table-recognize)
1843 #+END_SRC
1844
1845 ** url-download
1846 To download file in =elisp=, best is =url-copy-file=, here refer [[http://stackoverflow.com/questions/4448055/download-a-file-with-emacs-lisp][download-a-file-with-emacs-lisp]] using =url-retrieve-synchronously= wrapping
1847 as a http download client tool
1848 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1849   (defun sd/download-file (&optional url download-dir download-name)
1850     (interactive)
1851     (let ((url (or url
1852                    (read-string "Enter download URL: ")))
1853           (download-dir (read-directory-name "Save to (~/Downloads): " "~/Downloads" "~/Downloads" 'confirm' nil)))
1854       (let ((download-buffer (url-retrieve-synchronously url)))
1855         (save-excursion
1856           (set-buffer download-buffer)
1857           ;; we may have to trim the http response
1858           (goto-char (point-min))
1859           (re-search-forward "^$" nil 'move)
1860           (forward-char)
1861           (delete-region (point-min) (point))
1862           (write-file (concat (or download-dir
1863                                   "~/Downloads/")
1864                               (or download-name
1865                                   (car (last (split-string url "/" t))))))))))
1866 #+END_SRC
1867
1868 * Dired
1869 ** Dired basic
1870 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1871   (setq dired-dwim-target t)
1872
1873   (use-package dired-details
1874     :ensure t
1875     :config
1876     (setq-default dired-details-hidden-string "--- ")
1877     (dired-details-install))
1878 #+END_SRC
1879
1880 ** Dired functions
1881 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1882   (defun sd/dired-next-line (count)
1883     "Move to next line, and always focus on the file name."
1884     (interactive "p")
1885     (dired-next-line count)
1886     (dired-move-to-filename))
1887
1888   (defun sd/dired-previous-line (count)
1889     "Move to previous line, and always focus on the file name."
1890     (interactive "p")
1891     (dired-previous-line count)
1892     (dired-move-to-filename))
1893
1894   (defun sd/dired-up-directory ()
1895     "Go to up directory"
1896     (interactive)
1897     (let ((old (current-buffer)))
1898       (dired-up-directory)
1899       (kill-buffer old)))
1900 #+END_SRC
1901
1902 ** Dired bindings
1903 =C-o= is defined as a global key for window operation, here unset it in dired mode
1904 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1905   (defun sd/dired-key-map ()
1906     "My keybindings for dired"
1907     (interactive)
1908     ;; these two prefix are used globally
1909     (define-key dired-mode-map (kbd "C-o") nil)
1910     (define-key dired-mode-map (kbd "M-s") nil)
1911     ;; toggle hidden files
1912     (define-key dired-mode-map (kbd "H") 'dired-omit-mode)
1913     ;; scroll 
1914     (define-key dired-mode-map (kbd "SPC") 'scroll-up-command)
1915     (define-key dired-mode-map (kbd "DEL") 'scroll-down-command)
1916     (define-key dired-mode-map (kbd "j") 'diredp-next-line)
1917     (define-key dired-mode-map (kbd "k") 'diredp-previous-line)
1918     (define-key dired-mode-map (kbd "g") 'dired-goto-file)
1919     ;; (define-key dired-mode-map (kbd "S-SPC") 'scroll-down-command)
1920     ;; jump to fil/dirs
1921     (define-key dired-mode-map (kbd "f") 'dired-isearch-filenames)
1922     ;; subdir
1923     ;; i dired-maybe-insert-subdir
1924     ;; o dired-find-file-other-window (switch to other window)
1925     ;; O dired-display-file
1926     (define-key dired-mode-map (kbd "G") 'ido-dired)
1927     (define-key dired-mode-map (kbd "c") 'sd/dired-new-file)
1928     (define-key dired-mode-map (kbd "h") 'dired-summary)
1929     (define-key dired-mode-map (kbd "r") 'revert-buffer)
1930     (define-key dired-mode-map (kbd "l") 'dired-display-file)
1931     (define-key dired-mode-map [C-backspace] 'dired-up-directory)
1932     (define-key dired-mode-map (kbd "?") 'describe-mode)
1933     (define-key dired-mode-map (kbd "z") #'sd/dired-get-size)
1934     (define-key dired-mode-map (kbd "C-d") 'dired-kill-subdir)
1935     (define-key dired-mode-map (kbd "M-d") 'dired-kill-subdir)
1936     (define-key dired-mode-map (kbd "J") 'diredp-next-subdir)
1937     (define-key dired-mode-map (kbd "TAB") 'diredp-next-subdir)
1938     (define-key dired-mode-map (kbd "K") 'diredp-prev-subdir)
1939     (define-key dired-mode-map (kbd "O") 'dired-display-file)
1940     (define-key dired-mode-map (kbd "I") 'other-window)
1941     (define-key dired-mode-map (kbd "o") 'other-window)) 
1942
1943   (use-package dired
1944     :config
1945     (require 'dired-x)
1946     ;; also load dired+
1947     (use-package dired+
1948       :ensure t
1949       :init (setq diredp-hide-details-initially-flag nil))
1950     
1951     (setq dired-omit-mode t)
1952     (setq dired-omit-files (concat dired-omit-files "\\|^\\..+$"))
1953     (add-hook 'dired-mode-hook (lambda ()
1954                                  (sd/dired-key-map)
1955                                  (dired-omit-mode))))
1956
1957   (defadvice dired-summary (around sd/dired-summary activate)
1958     "Revisied dired summary."
1959     (interactive)
1960     (dired-why)
1961     (message
1962      "Δ: d-delete, u-ndelete, x-punge, f-ind, o-ther window, R-ename, C-opy, c-create, +new dir, r-evert, /-filter, v-iew, l-ist, z-Size, h-summary, ?-help"))
1963
1964   (defun sd/dired-high-level-dir ()
1965     "Go to higher level directory"
1966     (interactive)
1967     (find-alternate-file ".."))
1968 #+END_SRC
1969
1970 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1971   (defun sd/dired-new-file-and-open ()
1972     "Create a new file in dired mode"
1973     (interactive)
1974     (call-interactively 'find-file))
1975
1976   (defun sd/dired-new-file (file)
1977     "Create a new file called FILE.
1978   If FILE already exists, signal an error."
1979     (interactive
1980      (list (read-file-name "Create file: " (dired-current-directory))))
1981     (let* ((expanded (expand-file-name file)))
1982       (if (file-exists-p expanded)
1983           (error "Cannot create file %s: file exists" expanded))
1984       (write-region "" nil expanded t)
1985       (when expanded
1986         (dired-add-file expanded)
1987         (dired-move-to-filename))))
1988
1989   ;; copied from abo-abo's config
1990   (defun sd/dired-get-size ()
1991     (interactive)
1992     (let ((files (dired-get-marked-files)))
1993       (with-temp-buffer
1994         (apply 'call-process "/usr/bin/du" nil t nil "-sch" files)
1995         (message
1996          "Size of all marked files: %s"
1997          (progn
1998            (re-search-backward "\\(^[ 0-9.,]+[A-Za-z]+\\).*total$")
1999            (match-string 1))))))
2000 #+END_SRC
2001
2002 ** disable ido when dired new file
2003 When create a new directory, I want to disalbe =ido= completion. see [[http://stackoverflow.com/questions/7479565/emacs-ido-mode-and-creating-new-files-in-directories-it-keeps-changing-the-dire][here]]. Thhis code snippets copied
2004 from [[https://emacs.stackexchange.com/questions/13713/how-to-disable-ido-in-dired-create-directory/13795#13795?newreg%3Ddb17c20f7af3490fb11cf15f1d888e9e][How to disable IDO in ‘dired-create-directory’]]
2005 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2006   (defun mk-anti-ido-advice (func &rest args)
2007     "Temporarily disable IDO and call function FUNC with arguments ARGS."
2008     (interactive)
2009     (let ((read-file-name-function #'read-file-name-default)
2010           (completing-read-function #'completing-read-default))
2011       (if (called-interactively-p 'any)
2012           (call-interactively func)
2013         (apply func args))))
2014
2015   (defun mk-disable-ido (command)
2016     "Disable IDO when command COMMAND is called."
2017     (advice-add command :around #'mk-anti-ido-advice))
2018
2019   (defun mk-anti-ido-no-completing-advice (func &rest args)
2020     "Temporarily disable IDO and call function FUNC with arguments ARGS."
2021     (interactive)
2022     (let ((read-file-name-function #'read-file-name-default)
2023           ;; (completing-read-function #'completing-read-default)
2024           )
2025       (if (called-interactively-p 'any)
2026           (call-interactively func)
2027         (apply func args))))
2028
2029   (defun mk-disable-ido-no-completing (command)
2030     "Disable IDO when command COMMAND is called."
2031     (advice-add command :around #'mk-anti-ido-no-completing-advice))
2032 #+END_SRC
2033
2034 Disalble =ido= when new a directory or file in =dired= mode
2035 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2036   ;; call the function which you want to disable ido
2037   (mk-disable-ido 'dired-create-directory)
2038   (mk-disable-ido 'sd/dired-new-file-and-open)
2039   (mk-disable-ido 'sd/dired-new-file)
2040   (mk-disable-ido-no-completing 'dired-goto-file)
2041 #+END_SRC
2042
2043 ** Dired open with
2044 =!= =dired-do-shell-command=
2045 =&= =dired-do-async-shell-command=
2046 here on Mac, just use "open" commands to pen =.pdf=,  =.html= and image files
2047 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2048   (setq dired-guess-shell-alist-user
2049         '(("\\.pdf\\'" "open" "okular")
2050           ("\\.\\(?:djvu\\|eps\\)\\'" "evince")
2051           ("\\.\\(?:jpg\\|jpeg\\|png\\|gif\\|xpm\\)\\'" "open")
2052           ("\\.\\(?:xcf\\)\\'" "gimp")
2053           ("\\.csv\\'" "libreoffice")
2054           ("\\.tex\\'" "pdflatex" "latex")
2055           ("\\.\\(?:mp4\\|mkv\\|avi\\|rmvb\\|flv\\|ogv\\)\\(?:\\.part\\)?\\'" "mplayer")
2056           ("\\.\\(?:mp3\\|flac\\|wav\\)\\'" "mplayer")
2057           ("\\.html?\\'" "open")
2058           ("\\.dmg\\'" "open")
2059           ("\\.cue?\\'" "audacious")))
2060
2061
2062   (defun sd/dired-start-process (cmd &optional file-list)
2063     (interactive
2064      (let ((files (dired-get-marked-files t current-prefix-arg)))
2065        (list
2066         (dired-read-shell-command "& on %s: " current-prefix-arg files)
2067         files)))
2068     
2069     ;; (let (list-switch))
2070     (start-process
2071      cmd nil shell-file-name
2072      shell-command-switch
2073      (format
2074       "nohup 1>/dev/null 2>/dev/null %s \"%s\""
2075       cmd
2076       ;; (if (and (> (length file-list) 1)
2077       ;;          (setq list-switch
2078       ;;                (cadr (assoc cmd ora-dired-filelist-cmd))))
2079       ;;     (format "%s %s" cmd list-switch)
2080       ;;   cmd)
2081       (mapconcat #'expand-file-name file-list "\" \""))))
2082
2083
2084
2085 #+END_SRC
2086
2087 ** dired-hacks
2088 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2089   (use-package dired-hacks-utils
2090     :ensure t
2091     :defer t)
2092 #+END_SRC
2093
2094 ** dired-narrow
2095 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2096   ;;narrow dired to match filter
2097   (use-package dired-narrow
2098     :ensure t
2099     :commands (dired-narrow)
2100     :bind (:map dired-mode-map
2101                 ("/" . dired-narrow)))
2102 #+END_SRC
2103
2104 * Ibuffer
2105 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2106   (global-set-key (kbd "s-b") 'ibuffer)
2107
2108   (with-eval-after-load 'ibuffer
2109     (define-key ibuffer-mode-map (kbd "C-o") nil)
2110     (define-key ibuffer-mode-map (kbd "j") 'ibuffer-forward-line)
2111     (define-key ibuffer-mode-map (kbd "k") 'ibuffer-backward-line)
2112     (define-key ibuffer-mode-map (kbd "r") 'ibuffer-update)
2113     (define-key ibuffer-mode-map (kbd "g") 'ibuffer-jump-to-buffer)
2114     (define-key ibuffer-mode-map (kbd "h") 'sd/ibuffer-summary))
2115
2116   (defun sd/ibuffer-summary ()
2117     "Show summary of keybindings in ibuffer mode"
2118     (interactive)
2119     (message
2120      "Β: m|u - (un)mark, /-filter, //-remove filter, t, RET, g, k, S, D, Q; q to quit; h for help"))
2121 #+END_SRC
2122
2123 * Completion
2124 ** company mode and company-statistics
2125 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2126   (use-package company
2127     :ensure t
2128     :diminish company-mode
2129     :init (setq company-idle-delay 0.1)
2130     (setq company-selection-wrap-around t)
2131     :config
2132     (define-key company-active-map (kbd "M-n") nil)
2133     (define-key company-active-map (kbd "M-p") nil)
2134     (define-key company-active-map (kbd "SPC") #'sd/company-stop-input-space)
2135     (define-key company-active-map (kbd "C-n") #'company-select-next)
2136     (define-key company-active-map (kbd "C-p") #'company-select-previous)
2137     ;; should map both (kbd "TAB") and [tab],https://github.com/company-mode/company-mode/issues/75
2138     (define-key company-active-map (kbd "TAB") #'company-complete-selection)
2139     (define-key company-active-map [tab] #'company-complete-selection)
2140     (define-key company-active-map (kbd "C-w") nil)
2141     (define-key company-active-map (kbd "C-h") nil)
2142     (global-company-mode)
2143     ;; magig-commit is text-modeh
2144     (setq company-global-modes '(not org-mode magit-status-mode text-mode eshell-mode gfm-mode markdown-mode)))
2145
2146   (use-package company-statistics
2147     :ensure t
2148     :init
2149     (setq company-statistics-file (concat MY-EMACS-TMP "/company-statistics-cache.el"))
2150     :config
2151     (company-statistics-mode))
2152
2153   (defun sd/company-stop-input-space ()
2154     "Stop completing and input a space,a workaround of a semantic issue `https://github.com/company-mode/company-mode/issues/614'"
2155     (interactive)
2156     (company-abort)
2157     (insert " "))
2158 #+END_SRC
2159
2160 ** YASnippet
2161 *** yasnippet
2162 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2163   (use-package yasnippet
2164     :ensure t
2165     :defer t
2166     :init
2167     (add-hook 'prog-mode-hook #'yas-minor-mode)
2168     :config
2169     (yas-reload-all))
2170 #+END_SRC
2171
2172 ** YouCompleteMe
2173 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2174   (use-package ycmd
2175     :ensure t
2176     :init
2177     (use-package company-ycmd
2178       :ensure t
2179       :init
2180       (setq company-ycmd-enable-fuzzy-matching nil)
2181       :config
2182       (company-ycmd-setup))
2183     (setq ycmd-force-semantic-completion t)
2184     (add-hook 'c++-mode-hook 'ycmd-mode)
2185     (add-hook 'c-mode-hook 'ycmd-mode)
2186     (set-variable 'ycmd-server-command '("python" "/Users/peng/project/ycmd/ycmd"))
2187     (set-variable 'ycmd-global-config "/Users/peng/project/ycmd/cpp/ycm/.ycm_extra_conf.py"))
2188 #+END_SRC
2189
2190
2191 ** company and yasnippet
2192 Add yasnippet as the company candidates
2193 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2194   ;Add yasnippet support for all company backends
2195   ;https://github.com/syl20bnr/spacemacs/pull/179
2196   (defvar company-mode/enable-yas t
2197     "Enable yasnippet for all backends.")
2198
2199   (defun company-mode/backend-with-yas (backend)
2200     (if (or (not company-mode/enable-yas) (and (listp backend) (member 'company-yasnippet backend)))
2201         backend
2202       (append (if (consp backend) backend (list backend))
2203               '(:with company-yasnippet))))
2204
2205   (setq company-backends (mapcar #'company-mode/backend-with-yas company-backends))
2206 #+END_SRC
2207
2208 Refer, [[http://emacs.stackexchange.com/questions/7908/how-to-make-yasnippet-and-company-work-nicer][how-to-make-yasnippet-and-company-work-nicer]]
2209 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2210   (defun check-expansion ()
2211     (save-excursion
2212       (if (looking-at "\\_>") t
2213         (backward-char 1)
2214         (if (looking-at "\\.") t
2215           (backward-char 1)
2216           (if (looking-at "->") t nil)))))
2217
2218   (defun do-yas-expand ()
2219     (let ((yas/fallback-behavior 'return-nil))
2220       (yas/expand)))
2221
2222   (defun tab-indent-or-complete ()
2223     (interactive)
2224     (cond
2225      ((minibufferp)
2226       (minibuffer-complete))
2227      (t
2228       (indent-for-tab-command)
2229       (if (or (not yas/minor-mode)
2230               (null (do-yas-expand)))
2231           (if (check-expansion)
2232               (progn
2233                 (company-manual-begin)
2234                 (if (null company-candidates)
2235                     (progn
2236                       (company-abort)
2237                       (indent-for-tab-command)))))))))
2238
2239   (defun tab-complete-or-next-field ()
2240     (interactive)
2241     (if (or (not yas/minor-mode)
2242             (null (do-yas-expand)))
2243         (if company-candidates
2244             (company-complete-selection)
2245           (if (check-expansion)
2246               (progn
2247                 (company-manual-begin)
2248                 (if (null company-candidates)
2249                     (progn
2250                       (company-abort)
2251                       (yas-next-field))))
2252             (yas-next-field)))))
2253
2254   (defun expand-snippet-or-complete-selection ()
2255     (interactive)
2256     (if (or (not yas/minor-mode)
2257             (null (do-yas-expand))
2258             (company-abort))
2259         (company-complete-selection)))
2260
2261   (defun abort-company-or-yas ()
2262     (interactive)
2263     (if (null company-candidates)
2264         (yas-abort-snippet)
2265       (company-abort)))
2266
2267   '
2268   ;; (require 'company)
2269   ;; (require 'yasnippet)
2270
2271
2272   ;; (global-set-key [tab] 'tab-indent-or-complete)
2273   ;; (global-set-key (kbd "TAB") 'tab-indent-or-complete)
2274   ;; (global-set-key [(control return)] 'company-complete-common)
2275
2276   ;; (define-key company-active-map [tab] 'expand-snippet-or-complete-selection)
2277   ;; (define-key company-active-map (kbd "TAB") 'expand-snippet-or-complete-selection)
2278
2279   ;; (define-key yas-minor-mode-map [tab] nil)
2280   ;; (define-key yas-minor-mode-map (kbd "TAB") nil)
2281
2282   ;; (define-key yas-keymap [tab] 'tab-complete-or-next-field)
2283   ;; (define-key yas-keymap (kbd "TAB") 'tab-complete-or-next-field)
2284   ;; (define-key yas-keymap [(control tab)] 'yas-next-field)
2285   ;; (define-key yas-keymap (kbd "C-g") 'abort-company-or-yas)
2286 #+END_SRC
2287
2288 * Libs
2289 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2290   (use-package s
2291     :ensure t)
2292 #+END_SRC
2293
2294 * Programming Language
2295 ** Color identiifiers mode
2296 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2297   (use-package color-identifiers-mode
2298     :ensure t
2299     :init
2300     (dolist (mode '(emacs-lisp-mode-hook
2301                     c-mode-hook
2302                     c++-mode-hook))
2303       (add-hook mode #'color-identifiers-mode))
2304     :diminish color-identifiers-mode)
2305
2306   (global-prettify-symbols-mode t)
2307 #+END_SRC
2308 ** Font lock face
2309
2310 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2311   (set-face-attribute 'font-lock-keyword-face nil :foreground "#F92672"  :weight 'bold)
2312   (set-face-attribute 'font-lock-builtin-face nil :weight 'bold)
2313   (set-face-attribute 'font-lock-function-name-face nil :foreground "#A6E22E" :weight 'normal :slant 'normal)
2314   (set-face-attribute 'font-lock-variable-name-face nil :foreground "#00FF00")
2315
2316   (dolist (mode '(c-mode
2317                   c++-mode))
2318     (font-lock-add-keywords mode
2319                             ;; highlight %s \n
2320                             '(("\\([%\\][a-zA-Z]\\)" (1  font-lock-keyword-face prepend))
2321                               ("[^[:alpha:]]\\([[:digit:]]*\\)[^[:alpha:]]" (1 font-lock-constant-face append))
2322                               ;; hex number
2323                               ("[^[:alpha:]]\\(0[x\\|X][0-9a-fA-F]*\\)[^[:alpha:]]" (1 font-lock-constant-face append))
2324                               ;; hightlight the function call
2325                               ("\\s\"?\\(\\(\\sw\\|\\s_\\)+\\(<-\\)?\\)\\s\"?*\\s-*(" (1 font-lock-function-name-face))) t))
2326
2327   (font-lock-add-keywords 'c++-mode
2328                           '(
2329                             ("[\s\\|::]\\(cin\\|cout\\|endl\\)[^[:alpha:][:digit:]]" (1 font-lock-constant-face append))
2330                             ) t)
2331 #+END_SRC
2332
2333 ** Emacs Lisp
2334 In Lisp Mode, =M-o= is defined, but I use this for global hydra window. So here disable this key
2335 bindings in =lispy-mode-map= after loaded. see [[http://stackoverflow.com/questions/298048/how-to-handle-conflicting-keybindings][here]]
2336 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2337   (use-package lispy
2338     :ensure t
2339     :init
2340     (setq lispy-delete-backward-recenter 0)
2341     (with-eval-after-load "lispy"
2342       (define-key lispy-mode-map (kbd "M-o") nil)
2343       (define-key lispy-mode-map (kbd "g") 'special-lispy-goto-local)
2344       (define-key lispy-mode-map (kbd "G") 'special-lispy-goto)
2345       (define-key lispy-mode-map (kbd "M-m") 'back-to-indentation))
2346     :config
2347     (add-hook 'emacs-lisp-mode-hook (apply-partially #'lispy-mode 1)))
2348 #+END_SRC
2349
2350 ** Perl
2351 *** CPerl mode
2352 [[https://www.emacswiki.org/emacs/CPerlMode][CPerl mode]] has more features than =PerlMode= for perl programming. Alias this to =CPerlMode=
2353 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2354   (defalias 'perl-mode 'cperl-mode)
2355
2356   ;; (setq cperl-hairy t)
2357   ;; Turns on most of the CPerlMode options
2358   (setq cperl-auto-newline t)
2359   (setq cperl-highlight-variables-indiscriminately t)
2360   ;(setq cperl-indent-level 4)
2361   ;(setq cperl-continued-statement-offset 4)
2362   (setq cperl-close-paren-offset -4)
2363   (setq cperl-indent-parents-as-block t)
2364   (setq cperl-tab-always-indent t)
2365   ;(setq cperl-brace-offset  0)
2366
2367   (add-hook 'cperl-mode-hook (apply-partially #'cperl-set-style "C++"))
2368
2369   (defalias 'perldoc 'cperl-perldoc)
2370 #+END_SRC
2371
2372 *** Perl template
2373 Refer [[https://www.emacswiki.org/emacs/AutoInsertMode][AutoInsertMode]] Wiki
2374 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2375   (eval-after-load 'autoinsert
2376     '(define-auto-insert '("\\.pl\\'" . "Perl skeleton")
2377        '(
2378          "Empty"
2379          "#!/usr/bin/perl -w" \n
2380          \n
2381          "use strict;" >  \n \n
2382          > _
2383          )))
2384 #+END_SRC
2385
2386 *** Perl Keywords
2387 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2388   (font-lock-add-keywords 'cperl-mode
2389                           '(("\\(say\\)" . cperl-nonoverridable-face)
2390                             ("\\([0-9.]\\)*" . font-lock-constant-face)
2391                             ("\".*\\(\\\n\\).*\"" 1 font-lock-constant-face prepend)
2392                             ("\n" 0 font-lock-constant-face prepend)
2393                             ;; ("[%\\][[:alpha:]]" . font-lock-constant-face)
2394                             ("\\(^#!.*\\)$" .  cperl-nonoverridable-face)))
2395 #+END_SRC
2396
2397 ** C & C++
2398 C/C++ ide tools
2399 1. completion (file name, function name, variable name)
2400 2. template yasnippet (keywords, if, function)
2401 3. tags jump
2402 *** c/c++ style
2403 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2404   ;; (setq c-default-style "stroustrup"
2405   ;;       c-basic-offset 4)
2406
2407   ;; ;; "C-M-j" is my global binding for avy goto line below
2408   ;; ;; disable it in c mode
2409   ;; (mapcar #'(lambda (map)
2410   ;;            (define-key map (kbd "C-M-j") nil))
2411   ;;         (list c-mode-map
2412   ;;               c++-mode-map
2413   ;;               objc-mode-map))
2414
2415   ;; objective c
2416   (add-to-list 'auto-mode-alist '("\\.mm\\'" . objc-mode))
2417
2418   (setq-default c-hungry-delete-key t)
2419
2420
2421   ;; Looks `c-hanging-braces-alist' doesn't work as expected when  `electric-pair-mode' is enabled.
2422   (electric-pair-mode 1)
2423
2424   (defconst sd/c-style
2425     '("stroustrup"
2426       (c-tab-always-indent . t)
2427       (c-basic-offset . 4)
2428       (c-hanging-braces-alist . ((substatement-open before)
2429                                  (statement-block-intro before)))
2430       (c-hanging-colons-alist . ())
2431       (c-echo-syntactic-information-p . nil)
2432       (c-hanging-semi&comma-criteria . ()))
2433     "My C programming style")
2434
2435   (c-add-style "sd-c-style" sd/c-style)
2436
2437   (setq c-default-style "sd-c-style")
2438
2439   (add-hook 'c-mode-hook '(lambda ()
2440                             (c-toggle-auto-newline 1)
2441                             (c-set-style "sd-c-style")))
2442
2443   ;; (advice-add 'c-electric-brace :after (lambda (arg) "Add new line after insert {}" (newline-and-indent)))
2444 #+END_SRC
2445 *** irony
2446 **** install irony server
2447 Install clang, on mac, it has =libclang.dylib=, but no develop headers. Install by =brew=
2448 #+BEGIN_SRC sh
2449   brew install llvm --with-clang
2450 #+END_SRC
2451
2452 then install irony searver, and =LIBCLANG_LIBRARY= and =LIBCLANG_INCLUDE_DIR= accordingly
2453 #+BEGIN_SRC emacs-lisp :tangle no :results silent
2454   (irony-install-server)
2455 #+END_SRC
2456
2457 #+BEGIN_SRC sh
2458   cmake -DLIBCLANG_LIBRARY\=/usr/local/Cellar/llvm/4.0.1/lib/libclang.dylib \
2459         -DLIBCLANG_INCLUDE_DIR=/usr/local/Cellar/llvm/4.0.1/include \
2460         -DCMAKE_INSTALL_PREFIX\=/Users/peng/.emacs.d/irony/ \
2461         /Users/peng/.emacs.d/elpa/irony-20160713.1245/server && cmake --build . --use-stderr --config Release --target install 
2462 #+END_SRC
2463
2464 **** irony config
2465 irony-mode-hook, copied from [[https://github.com/Sarcasm/irony-mode][irony-mode]] github
2466 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2467   ;; (use-package irony
2468   ;;   :ensure t
2469   ;;   :init
2470   ;;   (add-hook 'c++-mode-hook 'irony-mode)
2471   ;;   (add-hook 'c-mode-hook 'irony-mode)
2472   ;;   (add-hook 'objc-mode-hook 'irony-mode))
2473
2474   ;; replace the `completion-at-point' and `complete-symbol' bindings in
2475   ;; irony-mode's buffers by irony-mode's function
2476
2477   (defun my-irony-mode-hook ()
2478     (define-key irony-mode-map [remap completion-at-point]
2479       'irony-completion-at-point-async)
2480     (define-key irony-mode-map [remap complete-symbol]
2481       'irony-completion-at-point-async))
2482
2483   ;; (add-hook 'irony-mode-hook 'my-irony-mode-hook)
2484   ;; (add-hook 'irony-mode-hook 'irony-cdb-autosetup-compile-options)
2485
2486   ;; (add-hook 'c++-mode-local-vars-hook #'sd/c++-mode-local-vars)
2487
2488   ;; add C++ completions, because by default c++ file can not complete
2489   ;; c++ std functions, another method is create .dir-local.el file, for p
2490   ;; for project see irony
2491   (defun sd/c++-mode-local-vars ()
2492     (setq irony--compile-options
2493         '("-std=c++11"
2494           "-stdlib=libc++"
2495           "-I/usr/include/c++/4.2.1")))
2496 #+END_SRC
2497
2498 irony-company
2499 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2500   ;; (use-package company-irony
2501   ;;   :ensure t)
2502
2503   ;; (use-package flycheck-irony
2504   ;;   :ensure t)
2505
2506   ;; (use-package company-c-headers
2507   ;;   :ensure t
2508   ;;   :config
2509   ;;   (add-to-list 'company-c-headers-path-system "/usr/include/c++/4.2.1/")
2510   ;;   (add-to-list 'company-c-headers-path-system "/usr/local/include/"))
2511
2512   ;; (with-eval-after-load 'company
2513   ;;   (add-to-list 'company-backends 'company-irony)
2514   ;;   (add-to-list 'company-backends 'company-c-headers))
2515
2516   ;; (with-eval-after-load 'company
2517   ;;   (push  '(company-irony :with company-yasnippet) company-backends)
2518   ;;   (push  '(company-c-headers :with company-yasnippet) company-backends))
2519
2520   ;; (with-eval-after-load 'flycheck
2521   ;;   (add-hook 'flycheck-mode-hook #'flycheck-irony-setup))
2522 #+END_SRC
2523
2524 *** flycheck
2525 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2526   (use-package flycheck
2527     :ensure t)
2528 #+END_SRC
2529
2530 *** gtags
2531 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2532   (use-package ggtags
2533     :ensure t
2534     :config
2535     (define-key ggtags-mode-map (kbd "M-g d") 'ggtags-find-definition)
2536     (define-key ggtags-mode-map (kbd "M-g r") 'ggtags-find-reference)
2537     (define-key ggtags-mode-map (kbd "M-g r") 'ggtags-find-reference)
2538     (define-key ggtags-mode-map (kbd "C-c g s") 'ggtags-find-other-symbol)
2539     (define-key ggtags-mode-map (kbd "C-c g h") 'ggtags-view-tag-history)
2540     (define-key ggtags-mode-map (kbd "C-c g r") 'ggtags-find-reference)
2541     (define-key ggtags-mode-map (kbd "C-c g f") 'ggtags-find-file)
2542     (define-key ggtags-mode-map (kbd "C-c g c") 'ggtags-create-tags)
2543     (define-key ggtags-mode-map (kbd "C-c g u") 'ggtags-update-tags))
2544
2545   (add-hook 'c-mode-common-hook
2546             (lambda ()
2547               (when (derived-mode-p 'c-mode 'c++-mode 'java-mode)
2548                 (ggtags-mode 1))))
2549
2550   (defun sd/ggtags-find-definition ()
2551     "Find the definition with current name completing."
2552     (interactive)
2553     (setq current-prefix-arg '(4))
2554     (call-interactively 'ggtags-find-definition))
2555
2556   (defun sd/ggtags-find-symbol ()
2557     "Find symbol"
2558     (interactive)
2559     (setq current-prefix-arg '(4))
2560     (call-interactively 'ggtags-find-other-symbol))
2561
2562   (require 'cc-mode)
2563   (require 'semantic)
2564   (setq semanticdb-default-save-directory (concat MY-EMACS-TMP "/semantic/"))
2565   (unless (file-exists-p semanticdb-default-save-directory)
2566     (make-directory semanticdb-default-save-directory))
2567
2568   (global-semanticdb-minor-mode 1)
2569   (global-semantic-idle-scheduler-mode 1)
2570
2571   (semantic-mode 1)
2572 #+END_SRC
2573
2574 *** google C style
2575 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2576   ;; (use-package google-c-style
2577   ;;   :ensure t
2578   ;;   :config
2579   ;;   (add-hook 'c-mode-hook 'google-set-c-style)
2580   ;;   (add-hook 'c++-mode-hook 'google-set-c-style))
2581 #+END_SRC
2582
2583 *** Compile and Run the C file
2584 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2585   (defun my-cpp-hook ()
2586     (let* ((current-file-name)
2587            (out-file-name))
2588       (when buffer-file-name
2589         (setq current-file-name (shell-quote-argument buffer-file-name))
2590         (setq out-file-name (shell-quote-argument (concat (file-name-sans-extension buffer-file-name) ".out"))))
2591       (setq-local compilation-read-command t)
2592       (set (make-local-variable 'compile-command)
2593            (concat "g++ -Wall -std=c++11 "
2594                    current-file-name
2595                    " -o "
2596                    out-file-name
2597                    " && "
2598                    out-file-name
2599                    ))
2600       (local-set-key (kbd "s-r") 'compile)))
2601
2602   (add-hook 'c-mode-hook 'my-cpp-hook)
2603   (add-hook 'c++-mode-hook 'my-cpp-hook)
2604 #+END_SRC
2605
2606 ** Lua
2607 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2608   (use-package lua-mode
2609     :ensure t)
2610 #+END_SRC
2611
2612 ** Scheme
2613 Install =guile=, =guile= is an implementation of =Scheme= programming language.
2614 #+BEGIN_SRC sh
2615   brew install guile
2616 #+END_SRC
2617
2618 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2619   (setq geiser-scheme-implementation 'guile)
2620 #+END_SRC
2621
2622 #+BEGIN_SRC scheme
2623   (define a "3")
2624   a
2625 #+END_SRC
2626
2627 #+RESULTS:
2628 : 3
2629
2630 ** Racket
2631 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2632   (use-package racket-mode
2633     :ensure t
2634     :config
2635     (define-key racket-mode-map (kbd "s-r") 'racket-run)
2636     (add-to-list 'racket-mode-hook (lambda () (lispy-mode 1))))
2637
2638   ;; set racket path
2639   (setenv "PATH" (concat (getenv "PATH")
2640                          ":" "/Applications/Racket v6.10.1/bin"))
2641   (setenv "MANPATH" (concat (getenv "MANPATH")
2642                             ":" "/Applications/Racket v6.10.1/man"))
2643   (setq exec-path (append exec-path '("/Applications/Racket v6.10.1/bin")))
2644
2645   (add-to-list 'auto-mode-alist '("\\.rkt\\'" . racket-mode))
2646 #+END_SRC
2647 * Compile
2648 Set the environments vairables in compilation mode
2649 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2650   (use-package compile
2651     :commands compile
2652     :config
2653     (setq compilation-environment (cons "LC_ALL=C" compilation-environment))
2654     (setq compilation-auto-jump-to-first-error t)
2655     (setq compilation-auto-jump-to-next t)
2656     (setq compilation-scroll-output 'first-error)
2657     ;; this will save all the modified buffers before compile
2658     (setq compilation-ask-about-save nil)
2659     (setq compilation-window-height (/ (window-total-height) 3)))
2660
2661   ;; super-r to compile
2662   (with-eval-after-load "compile"
2663     (define-key compilation-mode-map (kbd "C-o") nil)
2664     (define-key compilation-mode-map (kbd "n") 'compilation-next-error)
2665     (define-key compilation-mode-map (kbd "p") 'compilation-previous-error)
2666     (define-key compilation-mode-map (kbd "q") (lambda () (interactive) (quit-window t)))
2667     (define-key compilation-mode-map (kbd "r") #'recompile))
2668
2669   ;; here note dynamic binding the value of vv, otherwise it will resport error when run the hook.
2670   ;; https://emacs.stackexchange.com/questions/10394/scope-in-lambda
2671   (dolist (vv '(
2672                 (cperl-mode-hook . "perl")
2673                 (lua-mode-hook . "lua")
2674                 (python-mode-hook . "python")
2675                 (shell-mode-hook . "sh")))
2676     (add-hook (car vv) `(lambda ()
2677                           (unless (or (file-exists-p "makefile")
2678                                       (file-exists-p "Makefile"))
2679                             (set (make-local-variable 'compile-command)
2680                                  (concat (cdr ',vv)
2681                                          " "
2682                                          (if buffer-file-name
2683                                              (shell-quote-argument buffer-file-name))))))))
2684
2685   (global-set-key (kbd "s-r") 'compile)
2686 #+END_SRC
2687
2688 * Auto-Insert
2689 ** Enable auto-insert mode
2690 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2691   (auto-insert-mode t)
2692   (setq auto-insert-query nil)
2693 #+END_SRC
2694
2695 ** C++ Auto Insert
2696 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2697   (eval-after-load 'autoinsert
2698     '(define-auto-insert '("\\.cpp\\|.cc\\'" . "C++ skeleton")
2699        '(
2700          "Short description:"
2701          "/*"
2702          "\n * " (file-name-nondirectory (buffer-file-name))
2703          "\n */" > \n \n
2704          "#include <iostream>" \n
2705          "//#include \""
2706          (file-name-sans-extension
2707           (file-name-nondirectory (buffer-file-name)))
2708          ".hpp\"" \n \n
2709          "using namespace std;" \n \n
2710          "int main (int argc, char *argv[])"
2711          "\n{" \n 
2712          > _ \n
2713          "return 0;"
2714          "\n}" > \n
2715          )))
2716
2717   (eval-after-load 'autoinsert
2718     '(define-auto-insert '("\\.c\\'" . "C skeleton")
2719        '(
2720          "Short description:"
2721          "/*\n"
2722          " * " (file-name-nondirectory (buffer-file-name)) "\n"
2723          " */" > \n \n
2724          "#include <stdio.h>" \n
2725          "//#include \""
2726          (file-name-sans-extension
2727           (file-name-nondirectory (buffer-file-name)))
2728          ".h\"" \n \n
2729          "int main (int argc, char *argv[])\n"
2730          "{" \n
2731          > _ \n
2732          "return 0;\n"
2733          "}" > \n
2734          )))
2735
2736   (eval-after-load 'autoinsert
2737     '(define-auto-insert '("\\.h\\|.hpp\\'" . "c/c++ header")
2738        '((s-upcase (s-snake-case (file-name-nondirectory buffer-file-name)))
2739          "#ifndef " str n "#define " str "\n\n" _ "\n\n#endif  // " str)))
2740 #+END_SRC
2741
2742 ** Python template
2743 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2744   (eval-after-load 'autoinsert
2745     '(define-auto-insert '("\\.\\(py\\)\\'" . "Python skeleton")
2746        '(
2747          "Empty"
2748          "#import os,sys" \n
2749          \n \n
2750          )))
2751 #+END_SRC
2752
2753 ** Elisp 
2754 Emacs lisp auto-insert, based on the default module in =autoinsert.el=, but replace =completing-read= as 
2755 =completing-read-ido-ubiquitous= to fix the edge case of that =ido= cannot handle.
2756 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2757   (eval-after-load 'autoinsert
2758     '(define-auto-insert '("\\.el\\'" . "my Emacs Lisp header")
2759        '(
2760          "Short description: "
2761          ";;; " (file-name-nondirectory (buffer-file-name)) " --- " str
2762          (make-string (max 2 (- 80 (current-column) 27)) ?\s)
2763          "-*- lexical-binding: t; -*-" '(setq lexical-binding t)
2764          "\n
2765   ;; Copyright (C) " (format-time-string "%Y") "  "
2766          (getenv "ORGANIZATION") | (progn user-full-name) "
2767
2768   ;; Author: " (user-full-name)
2769          '(if (search-backward "&" (line-beginning-position) t)
2770               (replace-match (capitalize (user-login-name)) t t))
2771          '(end-of-line 1) " <" (progn user-mail-address) ">
2772   ;; Keywords: "
2773          '(require 'finder)
2774          ;;'(setq v1 (apply 'vector (mapcar 'car finder-known-keywords)))
2775          '(setq v1 (mapcar (lambda (x) (list (symbol-name (car x))))
2776                            finder-known-keywords)
2777                 v2 (mapconcat (lambda (x) (format "%12s:  %s" (car x) (cdr x)))
2778                               finder-known-keywords
2779                               "\n"))
2780          ((let ((minibuffer-help-form v2))
2781             (completing-read-ido-ubiquitous "Keyword, C-h: " v1 nil t))
2782           str ", ") & -2 "
2783
2784   \;; This program is free software; you can redistribute it and/or modify
2785   \;; it under the terms of the GNU General Public License as published by
2786   \;; the Free Software Foundation, either version 3 of the License, or
2787   \;; (at your option) any later version.
2788
2789   \;; This program is distributed in the hope that it will be useful,
2790   \;; but WITHOUT ANY WARRANTY; without even the implied warranty of
2791   \;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
2792   \;; GNU General Public License for more details.
2793
2794   \;; You should have received a copy of the GNU General Public License
2795   \;; along with this program.  If not, see <http://www.gnu.org/licenses/>.
2796
2797   \;;; Commentary:
2798
2799   \;; " _ "
2800
2801   \;;; Code:
2802
2803
2804   \(provide '"
2805          (file-name-base)
2806          ")
2807   \;;; " (file-name-nondirectory (buffer-file-name)) " ends here\n")))
2808 #+END_SRC
2809
2810 ** Org file template
2811 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2812   ;; (eval-after-load 'autoinsert
2813   ;;   '(define-auto-insert '("\\.\\(org\\)\\'" . "Org-mode skeleton")
2814   ;;      '(
2815   ;;        "title: "
2816   ;;        "#+TITLE: " str (make-string 30 ?\s) > \n
2817   ;;        "#+AUTHOR: Peng Li\n"
2818   ;;        "#+EMAIL: seudut@gmail.com\n"
2819   ;;        "#+DATE: " (shell-command-to-string "echo -n $(date +%Y-%m-%d)") > \n
2820   ;;        > \n
2821   ;;        > _)))
2822 #+END_SRC
2823
2824 * Markdown mode
2825 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2826   (use-package markdown-mode
2827     :ensure t
2828     :commands (markdown-mode gfm-mode)
2829     :mode (("README\\.md\\'" . gfm-mode)
2830            ("\\.md\\'" . markdown-mode)
2831            ("\\.markdown\\'" . markdown-mode))
2832     :init (setq markdown-command "multimarkdown"))
2833
2834   ;; (add-hook 'gfm-mode-hook (lambda ()
2835   ;;                            (set-face-attribute 'markdown-inline-code-face nil :inherit 'fixed-pitch)
2836   ;;                            (set-face-attribute 'markdown-pre-face nil :inherit 'fixed-pitch)))
2837   ;; (with-eval-after-load "gfm-mode"
2838   ;;   (set-face-attribute 'markdown-inline-code-face nil :inherit 'fixed-pitch)
2839   ;;   (set-face-attribute 'markdown-pre-face nil :inherit 'fixed-pitch))
2840 #+END_SRC
2841
2842 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2843   (use-package markdown-preview-eww
2844     :ensure t)
2845 #+END_SRC
2846
2847 * Iedit
2848 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2849   (use-package iedit
2850     :ensure t
2851     :init
2852     (global-set-key (kbd "C-;") #'iedit-mode))
2853 #+END_SRC
2854 * Gnus
2855 ** Gmail setting 
2856 Refer [[https://www.emacswiki.org/emacs/GnusGmail][GnusGmail]]
2857 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2858   (setq user-mail-address "seudut@gmail.com"
2859         user-full-name "Peng Li")
2860
2861   (setq gnus-select-method
2862         '(nnimap "gmail"
2863                  (nnimap-address "imap.gmail.com")
2864                  (nnimap-server-port "imaps")
2865                  (nnimap-stream ssl)))
2866
2867   (setq smtpmail-smtp-service 587
2868         gnus-ignored-newsgroups "^to\\.\\|^[0-9. ]+\\( \\|$\\)\\|^[\"]\"[#'()]")
2869
2870   ;; Use gmail sending mail
2871   (setq message-send-mail-function 'smtpmail-send-it
2872         smtpmail-starttls-credentials '(("smtp.gmail.com" 587 nil nil))
2873         smtpmail-auth-credentials '(("smtp.gmail.com" 587 "seudut@gmail.com" nil))
2874         smtpmail-default-smtp-server "smtp.gmail.com"
2875         smtpmail-smtp-server "smtp.gmail.com"
2876         smtpmail-smtp-service 587
2877         starttls-use-gnutls t)
2878 #+END_SRC
2879
2880 And put the following in =~/.authinfo= file, replacing =<USE>= with your email address
2881 and =<PASSWORD>= with the password
2882 #+BEGIN_EXAMPLE
2883   machine imap.gmail.com login <USER> password <PASSWORD> port imaps
2884   machine smtp.gmail.com login <USER> password <PASSWORD> port 587
2885 #+END_EXAMPLE
2886
2887 Then Run =M-x gnus=
2888
2889 ** Group buffer
2890 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2891   ;; (use-package gnus
2892   ;;   :init
2893   ;;   (setq gnus-permanently-visible-groups "\.*")
2894   ;;   :config
2895   ;;   (cond (window-system
2896   ;;          (setq custom-background-mode 'light)
2897   ;;          (defface my-group-face-1
2898   ;;            '((t (:foreground "Red" :bold t))) "First group face")
2899   ;;          (defface my-group-face-2
2900   ;;            '((t (:foreground "DarkSeaGreen4" :bold t)))
2901   ;;            "Second group face")
2902   ;;          (defface my-group-face-3
2903   ;;            '((t (:foreground "Green4" :bold t))) "Third group face")
2904   ;;          (defface my-group-face-4
2905   ;;            '((t (:foreground "SteelBlue" :bold t))) "Fourth group face")
2906   ;;          (defface my-group-face-5
2907   ;;            '((t (:foreground "Blue" :bold t))) "Fifth group face")))
2908   ;;   (setq gnus-group-highlight
2909   ;;         '(((> unread 200) . my-group-face-1)
2910   ;;           ((and (< level 3) (zerop unread)) . my-group-face-2)
2911   ;;           ((< level 3) . my-group-face-3)
2912   ;;           ((zerop unread) . my-group-face-4)
2913   ;;           (t . my-group-face-5))))
2914
2915
2916   ;; ;; key-
2917   ;; (add-hook 'gnus-group-mode-hook (lambda ()
2918   ;;                                   (define-key gnus-group-mode-map "k" 'gnus-group-prev-group)
2919   ;;                                   (define-key gnus-group-mode-map "j" 'gnus-group-next-group)
2920   ;;                                   (define-key gnus-group-mode-map "g" 'gnus-group-jump-to-group)
2921   ;;                                   (define-key gnus-group-mode-map "v" (lambda () (interactive) (gnus-group-select-group t)))))
2922 #+END_SRC
2923
2924 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2925   (setq gnus-fetch-old-headers 't)
2926
2927
2928
2929   (setq gnus-extract-address-components
2930         'mail-extract-address-components)
2931   ;; summary buffer 
2932   (setq gnus-summary-line-format "%U%R%z%I%(%[%-20,20f%]%)  %s%-80=   %11&user-date;\n")
2933   (setq gnus-user-date-format-alist '(((gnus-seconds-today) . "%H:%M")
2934                                       ((+ 86400 (gnus-seconds-today)) . "%a %H:%M")
2935                                       (604800 . "%a, %b %-d")
2936                                       (15778476 . "%b %-d")
2937                                       (t . "%Y-%m-%d")))
2938
2939   (setq gnus-thread-sort-functions '((not gnus-thread-sort-by-number)))
2940   (setq gnus-unread-mark ?\.)
2941   (setq gnus-use-correct-string-widths t)
2942
2943   ;; thread
2944   (setq gnus-thread-hide-subtree t)
2945
2946   ;; (with-eval-after-load 'gnus-summary-mode
2947   ;;   (define-key gnus-summary-mode-map (kbd "C-o") 'sd/hydra-window/body))
2948
2949   ;; (add-hook 'gnus-summary-mode-hook (lambda ()
2950   ;;                                     (define-key gnus-summary-mode-map (kbd "C-o") nil)))
2951   ;(add-hook 'gnus-summary-mode-hook (apply-partially #'define-key gnus-summary-mode-map (kbd "C-o") nil))
2952
2953
2954 #+END_SRC
2955
2956 ** Windows layout
2957 See [[https://www.emacswiki.org/emacs/GnusWindowLayout][GnusWindowLayout]]
2958 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2959   (gnus-add-configuration
2960    '(summary
2961      (horizontal 1.0
2962                  (vertical 35
2963                            (group 1.0))
2964                  (vertical 1.0
2965                            (summary 1.0 poine)))))
2966
2967   (gnus-add-configuration
2968    '(article
2969      (horizontal 1.0
2970                  (vertical 35
2971                            (group 1.0))
2972                  (vertical 1.0
2973                            (summary 0.50 point)
2974                            (article 1.0)))))
2975
2976   (with-eval-after-load 'gnus-group-mode
2977     (gnus-group-select-group "INBOX"))
2978   ;; (add-hook 'gnus-group-mode-map (lambda ()
2979   ;;                               (gnus-group-select-group "INBOX")))
2980 #+END_SRC
2981
2982 * Mu4e
2983 Refer [[http://www.kirang.in/2014/11/13/emacs-as-email-client-with-offlineimap-and-mu4e-on-osx][emacs-as-email-client-with-offlineimap-and-mu4e-on-osx]]
2984
2985 ** OfflineImap - download all mails from IMAP into local directory, and keep in sync
2986 #+BEGIN_SRC sh :results output replace
2987   # offline-imap
2988   brew install offline-imap
2989
2990   cp /usr/local/etc/offlineimap.conf ~/.offlineimapr
2991
2992   #For the =offlineimap= config on mac, using =sslcacertfile= instead of =cert_fingerpring=. On Mac
2993   sslcacertfile = /usr/local/etc/openssl/cert.pem 
2994 #+END_SRC
2995
2996 #+BEGIN_SRC conf 
2997   [general]
2998   ui=TTYUI
2999   accounts = Gmail
3000   autorefresh = 5
3001
3002   [Account Gmail]
3003   localrepository = Gmail-Local
3004   remoterepository = Gmail-Remote
3005
3006   [Repository Gmail-Local]
3007   type = Maildir
3008   localfolders = ~/.Mail/seudut@gmail.com
3009
3010   [Repository Gmail-Remote]
3011   type = Gmail
3012   remotehost = imap.gmail.com
3013   remoteuser = seudut@gmail.com
3014   remotepass = xxxxxxxx
3015   realdelete = no
3016   ssl = yes
3017   #cert_fingerprint = <insert gmail server fingerprint here>
3018   sslcacertfile = /usr/local/etc/openssl/cert.pem
3019   maxconnections = 1
3020   folderfilter = lambda folder: folder not in ['[Gmail]/Trash',
3021                                                '[Gmail]/Spam',
3022                                                '[Gmail]/All Mail',
3023                                                ]
3024 #+END_SRC
3025
3026 Then, run =offlineimap= to sync the mail
3027
3028 ** Mu - fast search, view mails and extract attachments.
3029 #+BEGIN_SRC sh
3030   EMACS=/usr/local/bin/emacs brew install mu --with-emacs
3031 #+END_SRC
3032
3033 Then, run =mu index --maildir=~/.Mail=
3034
3035 ** Mu4e - Emacs frontend of Mu
3036 config from [[http://www.kirang.in/2014/11/13/emacs-as-email-client-with-offlineimap-and-mu4e-on-osx/][emacs-as-email-client-with-offlineimap-and-mu4e-on-osx]]
3037 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3038   (if (require 'mu4e nil 'noerror)
3039       (progn
3040         (setq mu4e-maildir "~/.Mail")
3041         (setq mu4e-drafts-folder "/[Gmail].Drafts")
3042         (setq mu4e-sent-folder   "/[Gmail].Sent Mail")
3043         ;; don't save message to Sent Messages, Gmail/IMAP takes care of this
3044         (setq mu4e-sent-messages-behavior 'delete)
3045         ;; allow for updating mail using 'U' in the main view:
3046         (setq mu4e-get-mail-command "offlineimap")
3047
3048         ;; shortcuts
3049         (setq mu4e-maildir-shortcuts
3050               '( ("/INBOX"               . ?i)
3051                  ("/[Gmail].Sent Mail"   . ?s)))
3052
3053         ;; something about ourselves
3054         (setq
3055          user-mail-address "seudut@gmail.com"
3056          user-full-name  "Peng Li"
3057          mu4e-compose-signature
3058          (concat
3059           "Thanks,\n"
3060           "Peng\n"))
3061
3062         ;; show images
3063         (setq mu4e-show-images t)
3064
3065         ;; use imagemagick, if available
3066         (when (fboundp 'imagemagick-register-types)
3067           (imagemagick-register-types))
3068
3069         ;; convert html emails properly
3070         ;; Possible options:
3071         ;;   - html2text -utf8 -width 72
3072         ;;   - textutil -stdin -format html -convert txt -stdout
3073         ;;   - html2markdown | grep -v '&nbsp_place_holder;' (Requires html2text pypi)
3074         ;;   - w3m -dump -cols 80 -T text/html
3075         ;;   - view in browser (provided below)
3076         (setq mu4e-html2text-command "textutil -stdin -format html -convert txt -stdout")
3077
3078         ;; spell check
3079         (add-hook 'mu4e-compose-mode-hook
3080                   (defun my-do-compose-stuff ()
3081                     "My settings for message composition."
3082                     (set-fill-column 72)
3083                     (flyspell-mode)))
3084
3085         ;; add option to view html message in a browser
3086         ;; `aV` in view to activate
3087         (add-to-list 'mu4e-view-actions
3088                      '("ViewInBrowser" . mu4e-action-view-in-browser) t)
3089
3090         ;; fetch mail every 10 mins
3091         (setq mu4e-update-interval 600)
3092
3093         ;; mu4e view
3094         (setq-default mu4e-headers-fields '((:flags . 6)
3095                                             (:from-or-to . 22)
3096                                             (:mailing-list . 20)
3097                                             (:thread-subject . 70)
3098                                             (:human-date . 16))))
3099     (message "seudut:mu4e not installed, it won't work."))
3100 #+END_SRC
3101
3102 ** Smtp - send mail
3103 - =gnutls=, depends on =gnutls=, first confirm this is installed, otherwise, =brew install gnutls=
3104 - =~/.authinfo=
3105 #+BEGIN_SRC fundamental 
3106   machine smtp.gmail.com login <gmail username> password <gmail password>
3107 #+END_SRC
3108 - OPTIONAL, encrypt the =~/.authinfo= file
3109 #+BEGIN_SRC sh :results output replace
3110   gpg --output ~/.authinfo.gpg --symmetric ~/.authinfo
3111 #+END_SRC
3112
3113 * Ediff
3114 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3115   (with-eval-after-load 'ediff
3116     (setq ediff-split-window-function 'split-window-horizontally)
3117     (setq ediff-window-setup-function 'ediff-setup-windows-plain)
3118     (add-hook 'ediff-startup-hook 'ediff-toggle-wide-display)
3119     (add-hook 'ediff-cleanup-hook 'ediff-toggle-wide-display)
3120     (add-hook 'ediff-suspend-hook 'ediff-toggle-wide-display))
3121 #+END_SRC
3122
3123 * Modes
3124 ** Yaml-mode
3125 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3126   (use-package yaml-mode
3127     :ensure t
3128     :init
3129     (add-to-list 'auto-mode-alist '("\\.yml\\'" . yaml-mode)))
3130 #+END_SRC
3131
3132 * Entertainment
3133 ** GnuGo
3134 Play Go in Emacs, gnugo xpm refert [[https://github.com/okanotor/dotemacs/blob/f95b774cb292d1169748bc0a62ba647bbd8c0652/etc/my-inits/my-inits-gnugo.el][to here]]. start at image display mode and grid mode
3135 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3136   (use-package gnugo
3137     :ensure t
3138     :defer t
3139     :init
3140     (require 'gnugo-imgen)
3141     (setq gnugo-xpms 'gnugo-imgen-create-xpms)
3142     (add-hook 'gnugo-start-game-hook '(lambda ()
3143                                         (gnugo-image-display-mode)
3144                                         (gnugo-grid-mode)))
3145     :config
3146     (add-to-list 'gnugo-option-history (format "--boardsize 19 --color black --level 1")))
3147 #+END_SRC
3148
3149 ** Emms
3150 We can use [[https://www.gnu.org/software/emms/quickstart.html][Emms]] for multimedia in Emacs
3151 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3152   (use-package emms
3153     :ensure t
3154     :init
3155     (setq emms-directory (concat sd-temp-directory "emms"))
3156     (setq emms-source-file-default-directory "~/Music/")
3157     :config
3158     (emms-standard)
3159     (emms-default-players)
3160     (define-emms-simple-player mplayer '(file url)
3161       (regexp-opt '(".ogg" ".mp3" ".mgp" ".wav" ".wmv" ".wma" ".ape"
3162                     ".mov" ".avi" ".ogm" ".asf" ".mkv" ".divx" ".mpeg"
3163                     "http://" "mms://" ".rm" ".rmvb" ".mp4" ".flac" ".vob"
3164                     ".m4a" ".flv" ".ogv" ".pls"))
3165       "mplayer" "-slave" "-quiet" "-really-quiet" "-fullscreen")
3166     (emms-history-load))
3167 #+END_SRC
3168
3169 * Dictionary
3170 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3171   (use-package bing-dict
3172     :ensure t
3173     :init
3174     (global-set-key (kbd "s-d") 'bing-dict-brief)
3175     :commands (bing-dict-brief))
3176 #+END_SRC
3177
3178 * Key Bindings
3179 Here are some global key bindings for basic editting
3180 ** Global key bingding
3181 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3182   (global-set-key (kbd "C-h") 'delete-backward-char)
3183   (global-set-key (kbd "s-m") 'man)
3184 #+END_SRC
3185
3186 Refer [[https://github.com/fnwiya/dotfiles/blob/c9ca79f1b22c919d9f4c3a0f944ba8281255a594/setup/.emacs.d/loader-init/_90-kill-region-or-backward-kill-word.el][kill-region-or-backward-kill-word]]
3187
3188 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3189   (require 'utilities)
3190   (global-set-key (kbd "C-w") 'sd/kill-region-or-backward-kill-word)
3191 #+END_SRC
3192
3193
3194 ** Esc in minibuffer
3195 Use =ESC= to exit minibuffer. Also I map =Super-h= the same as =C-g=
3196 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3197   (define-key minibuffer-local-map [escape] 'keyboard-escape-quit)
3198   (define-key minibuffer-local-map [escape]  'keyboard-escape-quit)
3199   (define-key minibuffer-local-ns-map [escape]  'keyboard-escape-quit)
3200   (define-key minibuffer-local-isearch-map [escape]  'keyboard-escape-quit)
3201   (define-key minibuffer-local-completion-map [escape]  'keyboard-escape-quit)
3202   (define-key minibuffer-local-must-match-map [escape]  'keyboard-escape-quit)
3203   (define-key minibuffer-local-must-match-filename-map [escape]  'keyboard-escape-quit)
3204   (define-key minibuffer-local-filename-completion-map [escape]  'keyboard-escape-quit)
3205   (define-key minibuffer-local-filename-must-match-map [escape]  'keyboard-escape-quit)
3206
3207   ;; Also map s-h same as C-g
3208   (define-key minibuffer-local-map (kbd "s-h") 'keyboard-escape-quit)
3209 #+END_SRC
3210
3211 ** Project operations - =super=
3212 *** Projectile
3213 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3214   (use-package projectile
3215     :ensure t
3216     :init
3217     (setq projectile-enable-caching t)
3218     (setq projectile-switch-project-action (lambda ()
3219                                              (projectile-dired)
3220                                              (sd/project-switch-action)))
3221     (setq projectile-cache-file (concat sd-temp-directory "projectile.cache"))
3222     :config
3223     (add-to-list 'projectile-globally-ignored-files "GTAGS")
3224     (projectile-global-mode t)
3225     (global-set-key (kbd "C-M-p") 'projectile-switch-project))
3226
3227   ;; change default-directory of scratch buffer to projectile-project-root 
3228   (defun sd/project-switch-action ()
3229     "Change default-directory of scratch buffer to current projectile-project-root directory"
3230     (interactive)
3231     (dolist (buffer (buffer-list))
3232       (if (string-match (concat "scratch.*" (projectile-project-name))
3233                         (buffer-name buffer))
3234           (let ((root (projectile-project-root)))
3235             (with-current-buffer buffer
3236               (cd root))))))
3237
3238
3239
3240   ;; https://emacs.stackexchange.com/questions/16497/how-to-exclude-files-from-projectile
3241   ;; (setq projectile-enable-caching t)
3242   (if (executable-find "rg")
3243       (progn
3244         (defconst modi/rg-arguments
3245           `("--line-number"               ; line numbers
3246             "--smart-case"
3247             "--follow"                    ; follow symlinks
3248             "--mmap")                     ; apply memory map optimization when possible
3249           "Default rg arguments used in the functions in `projectile' package.")
3250
3251         (defun modi/advice-projectile-use-rg ()
3252           "Always use `rg' for getting a list of all files in the project."
3253           (mapconcat 'identity
3254                      (append '("\\rg")    ; used unaliased version of `rg': \rg
3255                              modi/rg-arguments
3256                              '("--null"   ; output null separated results,
3257                                "--files")) ; get file names matching the regex '' (all files)
3258                      " "))
3259
3260         (advice-add 'projectile-get-ext-command :override #'modi/advice-projectile-use-rg))
3261     (message "rg is not found"))
3262 #+END_SRC
3263
3264 *** project config =super= keybindings
3265 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3266   ;; (global-set-key (kbd "s-h") 'keyboard-quit)
3267   ;; (global-set-key (kbd "s-j") 'ido-switch-buffer)
3268   ;; (global-set-key (kbd "s-k") 'ido-find-file)
3269   ;; (global-set-key (kbd "s-l") 'sd/delete-current-window)
3270   ;; s-l  -->  goto-line
3271   ;; (global-set-key (kbd "s-/") 'swiper)
3272   ;; s-;  -->
3273   ;; s-'  -->  'next-multiframe-window
3274   (global-set-key (kbd "<s-return>") 'toggle-frame-fullscreen)
3275
3276   (global-set-key (kbd "s-f") 'projectile-find-file)
3277   ;; (global-set-key (kbd "s-`") 'mode-line-other-buffer)
3278
3279   ;; (global-set-key (kbd "s-n") 'persp-next)
3280   ;; (global-set-key (kbd "s-p") 'persp-prev)
3281   ;; (global-set-key (kbd "s-;") 'persp-switch-last)
3282
3283   (global-set-key (kbd "s-=") 'text-scale-increase)
3284   (global-set-key (kbd "s--") 'text-scale-decrease)
3285
3286   ;; (global-set-key (kbd "s-u") 'undo-tree-visualize)
3287 #+END_SRC
3288
3289 ** Windown & Buffer - =C-o=
3290 Defind a =hydra= function for windows, buffer & bookmark operations. And map it to =C-o= globally.
3291 Most use =C-o C-o= to switch buffers; =C-o x, v= to split window; =C-o o= to delete other windows
3292 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3293   (winner-mode 1)
3294
3295   (require 'utilities)
3296   (defhydra sd/hydra-window (:color red :columns nil)
3297     "C-o"
3298     ;; windows switch
3299     ("h" windmove-left nil :exit t)
3300     ("j" windmove-down nil :exit t)
3301     ("k" windmove-up nil :exit t)
3302     ("l" windmove-right nil :exit t)
3303     ("C-o" other-window nil :exit t)
3304     ;; window resize
3305     ("H" hydra-move-splitter-left nil)
3306     ("J" hydra-move-splitter-down nil)
3307     ("K" hydra-move-splitter-up nil)
3308     ("L" hydra-move-splitter-right nil)
3309     ;; windows split
3310     ("v" (lambda ()
3311            (interactive)
3312            (split-window-right)
3313            (windmove-right))
3314      nil :exit t)
3315     ("x" (lambda ()
3316            (interactive)
3317            (split-window-below)
3318            (windmove-down))
3319      nil :exit t)
3320     ;; buffer / windows switch
3321     ("o" sd/toggle-max-windows nil :exit t)
3322     ("C-k" sd/delete-current-window nil :exit t)
3323     ("C-d" (lambda ()
3324              (interactive)
3325              (kill-buffer)
3326              (sd/delete-current-window))
3327      nil :exit t)
3328
3329     ;; ace-window
3330     ;; ("'" other-window "other" :exit t)
3331     ;; ("a" ace-window "ace")
3332     ("s" ace-swap-window nil)
3333     ("D" ace-delete-window nil :exit t)
3334     ;; ("i" ace-maximize-window "ace-one" :exit t)
3335     ;; Windows undo - redo
3336     ("u" (progn (winner-undo) (setq this-command 'winner-undo)) nil)
3337     ("r" (progn (winner-redo) (setq this-command 'winner-redo)) nil)
3338
3339     ;; ibuffer, dired, eshell, bookmarks
3340     ;; ("C-i" other-window nil :exit t)
3341     ("C-b" ido-switch-buffer nil :exit t)
3342     ("C-f" projectile-find-file nil :exit t)
3343     ("C-r" ivy-recentf nil :exit t)
3344     ;; ("C-p" persp-switch nil :exit t)
3345     ;; ("C-t" projectile-persp-switch-project nil :exit t)
3346
3347     ;; other special buffers
3348     ("d" sd/project-or-dired-jump nil :exit t)
3349     ("b" ibuffer nil :exit t)
3350     ("t" multi-term nil :exit t)
3351     ("e" sd/toggle-project-eshell nil :exit t)
3352     ("m" bookmark-jump-other-window nil :exit t)
3353     ("M" bookmark-set nil :exit t)
3354     ("g" magit-status nil :exit t)
3355     ;; ("p" paradox-list-packages nil :exit t)
3356
3357     ;; quit
3358     ("q" nil nil)
3359     ("<ESC>" nil nil)
3360     ("C-h" windmove-left nil :exit t)
3361     ("C-j" windmove-down nil :exit t)
3362     ("C-k" windmove-up nil :exit t)
3363     ("C-l" windmove-right nil :exit t)
3364     ("C-;" nil nil :exit t)
3365     ("n" nil nil :exit t)
3366     ("[" nil nil :exit t)
3367     ("]" nil nil :exit t)
3368     ("f" nil nil))
3369
3370   (global-unset-key (kbd "C-o"))
3371   (global-set-key (kbd "C-o") 'sd/hydra-window/body)
3372
3373   (defun sd/project-or-dired-jump ()
3374     "If under project, jump to the root directory, otherwise
3375   jump to dired of current file"
3376     (interactive)
3377     (if (projectile-project-p)
3378         (projectile-dired)
3379       (dired-jump)))
3380 #+END_SRC
3381
3382 Kill the help window and buffer when quit.
3383 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3384   (with-eval-after-load "help-mode"
3385     (define-key help-mode-map (kbd "q") (lambda ()
3386                                           (interactive)
3387                                           (quit-window t))))
3388
3389   (with-eval-after-load 'man
3390     (set-face-attribute 'Man-overstrike nil :inherit 'bold :foreground "orange red")
3391     (set-face-attribute 'Man-underline nil :inherit 'underline :foreground "forest green")
3392     (define-key Man-mode-map (kbd "q") (lambda ()
3393                                          (interactive)
3394                                          (Man-kill))))
3395
3396
3397   ;; (advice-add 'man :after (lambda (man-args) (other-window 1)))
3398   (advice-add 'man :after (apply-partially 'other-window 1))
3399
3400
3401   (require 'shell-command-output-mode)
3402
3403   (defun my/shell-command-after (command &optional output-buffer error-buffer)
3404     (let* ((buffer (get-buffer "*Shell Command Output*"))
3405            (window (get-buffer-window buffer)))
3406       (if buffer (with-current-buffer buffer
3407                    (shell-command-output-mode)))
3408       (if window
3409           (select-window window))))
3410
3411   (advice-add 'shell-command :after 'my/shell-command-after)
3412 #+END_SRC
3413
3414 ** Motion
3415 - =C-M-=
3416 [[https://www.masteringemacs.org/article/effective-editing-movement][effective-editing-movement]]
3417 *** Command Arguments, numeric argumens
3418 =C-u 4= same as =C-4=, =M-4=
3419 *** Basic movement
3420 moving by line / word / 
3421 =C-f=, =C-b=, =C-p=, =C-n=, =M-f=, =M-b=
3422 =C-a=, =C-e=
3423 =M-m= (move first non-whitespace on this line) 
3424 =M-}=, =M-{=, Move forward end of paragraph
3425 =M-a=, =M-e=,  beginning / end of sentence
3426 =C-M-a=, =C-M-e=, move begining of defun
3427 =C-x ]=, =C-x [=, forward/backward one page
3428 =C-v=, =M-v=, =C-M-v=, =C-M-S-v= scroll down/up
3429 =M-<=, =M->=, beginning/end of buffer
3430 =M-r=, Repositiong point
3431
3432 *** Moving by S-expression / List
3433 *** Marks
3434 =C-<SPC>= set marks toggle the region
3435 =C-u C-<SPC>= Jump to the mark, repeated calls go further back the mark ring
3436 =C-x C-x= Exchanges the point and mark.
3437
3438 Stolen [[https://www.masteringemacs.org/article/fixing-mark-commands-transient-mark-mode][fixing-mark-commands-transient-mark-mode]]
3439 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3440   (defun push-mark-no-activate ()
3441     "Pushes `point' to `mark-ring' and does not activate the region
3442      Equivalent to \\[set-mark-command] when \\[transient-mark-mode] is disabled"
3443     (interactive)
3444     (push-mark (point) t nil)
3445     (message "Pushed mark to ring"))
3446
3447   ;; (global-set-key (kbd "C-`") 'push-mark-no-activate)
3448
3449   (defun jump-to-mark ()
3450     "Jumps to the local mark, respecting the `mark-ring' order.
3451     This is the same as using \\[set-mark-command] with the prefix argument."
3452     (interactive)
3453     (set-mark-command 1))
3454
3455   ;; (global-set-key (kbd "M-`") 'jump-to-mark)
3456
3457   (defun exchange-point-and-mark-no-activate ()
3458     "Identical to \\[exchange-point-and-mark] but will not activate the region."
3459     (interactive)
3460     (exchange-point-and-mark)
3461     (deactivate-mark nil))
3462
3463   ;; (define-key global-map [remap exchange-point-and-mark] 'exchange-point-and-mark-no-activate)
3464 #+END_SRC
3465
3466 Show the mark ring using =helm-mark-ring=, also mapping =M-`= to quit minibuffer. so that =M-`= can 
3467 toggle the mark ring. the best way is add a new action and mapping to =helm-source-mark-ring=,  but 
3468 since there is no map such as =helm-mark-ring=map=, so I cannot binding a key to the quit action.
3469 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3470   (setq mark-ring-max 50)
3471
3472   (use-package helm
3473     :ensure t
3474     :init
3475     (global-set-key (kbd "M-`") #'helm-mark-ring))
3476
3477   (define-key minibuffer-local-map (kbd "M-`") 'keyboard-escape-quit)
3478 #+END_SRC
3479
3480 =M-h= marks the next paragraph
3481 =C-x h= marks the whole buffer
3482 =C-M-h= marks the next defun
3483 =C-x C-p= marks the next page
3484 *** Registers
3485 Registers can save text, position, rectangles, file and configuration and other things.
3486 Here for movement, we can use register to save/jump position
3487 =C-x r SPC= store point in register
3488 =C-x r j= jump to register
3489 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3490   (use-package list-register
3491     :ensure t)
3492 #+END_SRC
3493
3494 *** Bookmarks
3495 As I would like use bookmakr for different buffer/files. to help to swith
3496 different buffer/file quickly. this setting is in Windows/buffer node
3497 =C-x r m= set a bookmarks
3498 =C-x r l= list bookmarks
3499 =C-x r b= jump to bookmarks
3500
3501 *** Search
3502 Search, replace and hightlight will in later paragraph
3503 *** =Avy= for easy motion
3504 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3505   (use-package avy
3506     :ensure t
3507     :config
3508     (avy-setup-default))
3509
3510   ;; (global-set-key (kbd "C-M-j") 'avy-goto-line-below)
3511   ;; (global-set-key (kbd "C-M-n") 'avy-goto-line-below)
3512   ;; (global-set-key (kbd "C-M-k") 'avy-goto-line-above)
3513   ;; (global-set-key (kbd "C-M-p") 'avy-goto-line-above)
3514
3515   ;; (global-set-key (kbd "C-M-f") 'avy-goto-word-1-below)
3516   ;; (global-set-key (kbd "C-M-b") 'avy-goto-word-1-above)
3517
3518   ;; (global-set-key (kbd "M-g e") 'avy-goto-word-0)
3519   ;; (global-set-key (kbd "C-M-w") 'avy-goto-char-timer)
3520   ;; (global-set-key (kbd "C-M-l") 'avy-goto-char-in-line)
3521
3522   ;; ;; will delete above 
3523   ;; (global-set-key (kbd "M-g j") 'avy-goto-line-below)
3524   ;; (global-set-key (kbd "M-g k") 'avy-goto-line-above)
3525   ;; (global-set-key (kbd "M-g w") 'avy-goto-word-1-below)
3526   ;; (global-set-key (kbd "M-g b") 'avy-goto-word-1-above)
3527   ;; (global-set-key (kbd "M-g e") 'avy-goto-word-0)
3528   ;; (global-set-key (kbd "M-g f") 'avy-goto-char-timer)
3529   ;; (global-set-key (kbd "M-g c") 'avy-goto-char-in-line)
3530 #+END_SRC
3531
3532 *** =Imenu= goto tag
3533 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3534   (global-set-key (kbd "M-i") #'counsel-imenu)
3535   ;; (global-set-key (kbd "M-i") #'imenu)
3536
3537   ;; define M-[ as C-M-a
3538   ;; http://ergoemacs.org/emacs/emacs_key-translation-map.html
3539   (define-key key-translation-map (kbd "M-[") (kbd "C-M-a"))
3540   (define-key key-translation-map (kbd "M-]") (kbd "C-M-e"))
3541 #+END_SRC
3542
3543 *** Go-to line
3544 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3545   (global-set-key (kbd "M-l") 'goto-line)
3546 #+END_SRC
3547
3548 ** Edit
3549 *** basic editting
3550 - cut, yank, =C-w=, =C-y=
3551 - save, revert
3552 - undo, redo - undo-tree
3553 - select, expand-region
3554 - spell check, flyspell
3555
3556 *** Kill ring
3557 =helm-show-kill-ring=
3558 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3559   (setq kill-ring-max 100)                ; default is 60p
3560
3561   (use-package helm
3562     :ensure t
3563     :init
3564     (global-set-key (kbd "M-y") #'helm-show-kill-ring))
3565 #+END_SRC
3566
3567 *** undo-tree
3568 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3569   (use-package undo-tree
3570     :ensure t
3571     :config
3572     (define-key undo-tree-visualizer-mode-map "j" 'undo-tree-visualize-redo)
3573     (define-key undo-tree-visualizer-mode-map "k" 'undo-tree-visualize-undo)
3574     (define-key undo-tree-visualizer-mode-map "h" 'undo-tree-visualize-switch-branch-left)
3575     (define-key undo-tree-visualizer-mode-map "l" 'undo-tree-visualize-switch-branch-right)
3576     (global-undo-tree-mode 1))
3577
3578   (global-set-key (kbd "s-u") 'undo-tree-visualize)
3579 #+END_SRC
3580
3581 *** flyspell
3582 Stolen from [[https://github.com/redguardtoo/emacs.d/blob/master/lisp/init-spelling.el][here]], hunspell will search dictionary in =DICPATH=
3583 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3584   (setenv "DICPATH" "/usr/local/share/hunspell")
3585
3586   (when (executable-find "hunspell")
3587     (setq-default ispell-program-name "hunspell")
3588     (setq ispell-really-hunspell t))
3589
3590   ;; (defun text-mode-hook-setup ()
3591   ;;   ;; Turn off RUN-TOGETHER option when spell check text-mode
3592   ;;   (setq-local ispell-extra-args (flyspell-detect-ispell-args)))
3593   ;; (add-hook 'text-mode-hook 'text-mode-hook-setup)
3594   ;; (add-hook 'text-mode-hook 'flyspell-mode)
3595
3596   ;; enable flyspell check on comments and strings in progmamming modes
3597   ;; (add-hook 'prog-mode-hook 'flyspell-prog-mode)
3598
3599   ;; I don't use the default mappings
3600   (with-eval-after-load 'flyspell
3601     (define-key flyspell-mode-map (kbd "C-;") nil)
3602     (define-key flyspell-mode-map (kbd "C-,") nil)
3603     (define-key flyspell-mode-map (kbd "C-.") nil))
3604 #+END_SRC
3605
3606 Make flyspell enabled for org-mode, see [[http://emacs.stackexchange.com/questions/9333/how-does-one-use-flyspell-in-org-buffers-without-flyspell-triggering-on-tangled][here]]
3607 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3608   ;; NO spell check for embedded snippets
3609   (defadvice org-mode-flyspell-verify (after org-mode-flyspell-verify-hack activate)
3610     (let ((rlt ad-return-value)
3611           (begin-regexp "^[ \t]*#\\+begin_\\(src\\|html\\|latex\\)")
3612           (end-regexp "^[ \t]*#\\+end_\\(src\\|html\\|latex\\)")
3613           old-flag
3614           b e)
3615       (when ad-return-value
3616         (save-excursion
3617           (setq old-flag case-fold-search)
3618           (setq case-fold-search t)
3619           (setq b (re-search-backward begin-regexp nil t))
3620           (if b (setq e (re-search-forward end-regexp nil t)))
3621           (setq case-fold-search old-flag))
3622         (if (and b e (< (point) e)) (setq rlt nil)))
3623       (setq ad-return-value rlt)))
3624 #+END_SRC
3625
3626 ** Search & Replace / hightlight =M-s=
3627 *** isearch
3628 =C-s=, =C-r=, 
3629 =C-w= add word at point to search string, 
3630 =M-%= query replace
3631 =C-M-y= add character at point to search string
3632 =M-s C-e= add reset of line at point
3633 =C-y= yank from clipboard to search string
3634 =M-n=, =M-p=, history
3635 =C-M-i= complete search string
3636 set the isearch history size, the default is only =16=
3637 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3638   (setq history-length 5000)
3639   (setq regexp-search-ring-max 1000)
3640   (setq search-ring-max 1000)
3641
3642   ;; when search a word or a symbol , also add the word into regexp-search-ring
3643   (defadvice isearch-update-ring (after sd/isearch-update-ring (string &optional regexp) activate)
3644     "Add search-ring to regexp-search-ring"
3645     (unless regexp
3646       (add-to-history 'regexp-search-ring string regexp-search-ring-max)))
3647 #+END_SRC
3648
3649 *** =M-s= prefix
3650 use the prefix =M-s= for searching in buffers
3651 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3652   (defun sd/make-keymap (key bindings)
3653     (setq keymap (make-sparse-keymap))
3654     (dolist (binding bindings)
3655       (define-key keymap (car binding) (cdr binding)))
3656     (global-set-key key keymap))
3657
3658   ;; (sd/make-keymap "\M-s"
3659   ;;                 '(("w" . save-buffer)
3660   ;;                   ;; ("\M-w" . save-buffer)
3661   ;;                   ("e" . revert-buffer)
3662   ;;                   ("s" . isearch-forward-regexp)
3663   ;;                   ("\M-s" . isearch-forward-regexp)
3664   ;;                   ("r" . isearch-backward-regexp)
3665   ;;                   ("." . isearch-forward-symbol-at-point)
3666   ;;                   ("o" . occur)
3667   ;;                   ;; ("h" . highlight-symbol-at-point)
3668   ;;                   ("h" . highlight-symbol)
3669   ;;                   ("m" . highlight-regexp)
3670   ;;                   ("l" . highlight-lines-matching-regexp)
3671   ;;                   ("M" . unhighlight-regexp)
3672   ;;                   ("f" . keyboard-quit)
3673   ;;                   ("q" . keyboard-quit)))
3674 #+END_SRC
3675
3676 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3677   (use-package highlight-symbol
3678     :ensure t)
3679
3680   (defhydra sd/search-replace (:color red :columns nil)
3681     "Search"
3682     ("w" save-buffer "save" :exit t)
3683     ("e" revert-buffer "revert" :exit t)
3684     ("u" undo-tree-visualize "undo" :exit t)
3685     ("s" isearch-forward-regexp "s-search" :exit t)
3686     ("M-s" isearch-forward-regexp "s-search" :exit t)
3687     ("r" isearch-backward-regexp "r-search" :exit t)
3688     ("." isearch-forward-symbol-at-point "search point" :exit t)
3689     ("/" swiper "swiper" :exit t)
3690     ("o" occur "occur" :exit t)
3691     ("h" highlight-symbol "higlight" :exit t)
3692     ("l" highlight-lines-matching-regexp "higlight line" :exit t)
3693     ("m" highlight-regexp "higlight" :exit t)
3694     ("M" unhighlight-regexp "unhiglight" :exit t)
3695     ("q" nil "quit")
3696     ("f" nil))
3697
3698   (global-unset-key (kbd "M-s"))
3699   (global-set-key (kbd "M-s") 'sd/search-replace/body)
3700
3701
3702   ;; search and replace and highlight
3703   (define-key isearch-mode-map (kbd "M-s") 'isearch-repeat-forward)
3704   (define-key isearch-mode-map (kbd "M-r") 'isearch-repeat-backward)
3705   (global-set-key (kbd "s-[") 'highlight-symbol-next)
3706   (global-set-key (kbd "s-]") 'highlight-symbol-prev)
3707   (global-set-key (kbd "s-\\") 'highlight-symbol-query-replace)
3708 #+END_SRC
3709
3710 *** Occur
3711 Occur search key bindings
3712 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3713   (defun sd/occur-keys ()
3714     "My key bindings in occur-mode"
3715     (interactive)
3716     (switch-to-buffer-other-window "*Occur*")
3717     (define-key occur-mode-map (kbd "C-o") nil)
3718     (define-key occur-mode-map (kbd "C-n") (lambda ()
3719                                              (interactive)
3720                                              (occur-next)
3721                                              (occur-mode-goto-occurrence-other-window)
3722                                              (recenter)
3723                                              (other-window 1)))
3724     (define-key occur-mode-map (kbd "C-p") (lambda ()
3725                                              (interactive)
3726                                              (occur-prev)
3727                                              (occur-mode-goto-occurrence-other-window)
3728                                              (recenter)
3729                                              (other-window 1))))
3730
3731   (add-hook 'occur-hook #'sd/occur-keys)
3732
3733   (use-package color-moccur
3734     :ensure t
3735     :commands (isearch-moccur isearch-all)
3736     :init
3737     (setq isearch-lazy-highlight t)
3738     :config
3739     (use-package moccur-edit))
3740 #+END_SRC
3741
3742
3743 ** Expand region map
3744 *** Install =expand-region=
3745 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3746   (use-package expand-region
3747     :ensure t
3748     :config
3749     ;; (global-set-key (kbd "C-=") 'er/expand-region)
3750     )
3751 #+END_SRC
3752
3753 *** Add a =hydra= map for =expand-region= operations
3754 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3755   (defun sd/mark-line ()
3756     "Mark current line without whitespace beginning"
3757     (interactive)
3758     (back-to-indentation)
3759     (set-mark (line-end-position)))
3760
3761   (defhydra sd/expand-selected (:color red :columns nil
3762                                        :post (deactivate-mark)
3763                                        )
3764     "Selected"
3765     ;; select
3766     ;; ("e"  er/expand-region "+")
3767     ("SPC" er/expand-region "+")
3768     ;; ("c"  er/contract-region "-")
3769     ("S-SPC" er/contract-region "-")
3770     ("r" (lambda ()
3771            (interactive)
3772            (er/contract-region 0))
3773      "reset")
3774
3775     ("i'" er/mark-inside-quotes "in")
3776     ("i\"" er/mark-inside-quotes nil)
3777     ("o'" er/mark-outside-quotes "out")
3778     ("o\"" er/mark-outside-quotes nil)
3779
3780     ("i{" er/mark-inside-pairs nil)
3781     ("i(" er/mark-inside-pairs nil)
3782     ("o{" er/mark-inside-pairs nil)
3783     ("o(" er/mark-inside-pairs nil)
3784
3785     ("p" er/mark-paragraph "paragraph")
3786
3787     ("l" sd/mark-line "line")
3788     ("u" er/mark-url "url")
3789     ("f" er/mark-defun "fun")
3790     ("n" er/mark-next-accessor "next")
3791
3792     ("x" exchange-point-and-mark "exchange")
3793
3794     ;; Search
3795     ;; higlight
3796
3797     ;; exit
3798     ("d" kill-region "delete" :exit t)
3799
3800     ("y" kill-ring-save "yank" :exit t)
3801     ("M-SPC" nil "quit" :exit t)
3802     ;; ("C-SPC" "quit" :exit t)
3803     ("q" deactivate-mark "quit" :exit t))
3804
3805   (global-set-key (kbd "M-SPC") (lambda ()
3806                                   (interactive)
3807                                   (set-mark-command nil)
3808                                   ;; (er/expand-region 1)
3809                                   (er/mark-word)
3810                                   (sd/expand-selected/body)))
3811 #+END_SRC
3812
3813 *** TODO make expand-region hydra work with lispy selected
3814
3815 * Developing
3816 ** perspeen
3817 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3818   ;; (use-package perspeen
3819   ;;   :ensure t
3820   ;;   :init
3821   ;;   (setq perspeen-use-tab nil)
3822   ;;   :config
3823   ;;   (perspeen-mode))
3824
3825   (el-get-bundle seudut/perspeen
3826     :features perspeen
3827     (setq perspeen-use-tab nil)
3828     (perspeen-mode))
3829
3830   ;; super-i to switch to ith workspace
3831
3832   (defmacro sd/define-keys (map key func &rest args)
3833     "A macro to define multi keys "
3834     `(define-key ,map ,key (lambda () (interactive) (,func ,@args))))
3835
3836
3837   (with-eval-after-load "perspeen"
3838     (dotimes (ii 9)
3839       (sd/define-keys perspeen-mode-map (kbd (concat "s-" (number-to-string (+ ii 1))))
3840                       perspeen-goto-ws (+ ii 1)))
3841     (define-key perspeen-mode-map (kbd "s-c") 'perspeen-create-ws)
3842     (define-key perspeen-mode-map (kbd "s-n") 'perspeen-next-ws)
3843     (define-key perspeen-mode-map (kbd "s-p") 'perspeen-previous-ws)
3844     (define-key perspeen-mode-map (kbd "s-'") 'perspeen-last-ws)
3845     (define-key perspeen-mode-map (kbd "s-t") 'perspeen-tab-create-tab)
3846     (define-key perspeen-mode-map (kbd "s-t") 'perspeen-tab-create-tab))
3847 #+END_SRC
3848 * Evil Mode
3849 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3850   (org-babel-load-file "~/.emacs.d/emacs-evil.org")
3851 #+END_SRC
3852 * Note
3853 ** Check if emacs is in terminal of graphic mode
3854 Use =display-graphic-p= instead of =window-system=
3855 [[info:elisp#Window%20Systems][Window Systems]]
3856 ** =Interactive= 
3857 ** List operation
3858 *** add a element to list
3859 - ~add-to-list~ functions, append
3860 - ~push~ macro
3861 - ~(setcdr (last aa) (list element))~
3862 blog with modify list
3863
3864 draw one line top of the windows
3865 * test
3866 This is a test.
3867 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
3868   ;; test local mode line
3869   ;; (add-to-list 'load-path "~/.emacs.d/elisp")
3870   ;; (require 'my-mode-line)
3871 #+END_SRC