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