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