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