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