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