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