emacs - tidy up code and fix ido history bug
[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
12 Set system PATH and emacs exec path
13
14 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
15
16   (setenv "PATH" (concat (getenv "PATH")
17                          ":" "/usr/local/bin"
18                          ":" "/Library/TeX/texbin"))
19   (setq exec-path (append exec-path '("/usr/local/bin")))
20   (setq exec-path (append exec-path '("/Library/TeX/texbin/")))
21
22 #+END_SRC
23
24 Set the emacs load path
25
26 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
27   ;; (add-to-list 'load-path "~/.emacs.d/elisp")
28 #+END_SRC
29
30 ** Package Initialization
31
32 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
33
34   (require 'package)
35
36   (setq package-archives '(("mepla" . "http://melpa.milkbox.net/packages/")
37                            ("gnu" . "http://elpa.gnu.org/packages/")
38                            ("org" . "http://orgmode.org/elpa/")))
39
40   (package-initialize)
41
42 #+END_SRC       
43
44 ** General Setting
45 *** scroll bar, tool-bar and menu-bar
46 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
47   (scroll-bar-mode 0)
48   (tool-bar-mode 0)
49   (menu-bar-mode 1)
50
51   ;; (setq debug-on-error t)
52   (setq inhibit-startup-message t)
53
54   (defalias 'yes-or-no-p 'y-or-n-p)
55   (show-paren-mode 1)
56   ;; don't backupf
57   (setq make-backup-files nil)
58 #+END_SRC
59
60 *** Custom file 
61 #+BEGIN_SRC emacs-lisp :tangle yes :results silent 
62   (setq custom-file "~/.emacs.d/custom.el")
63   (if (file-exists-p custom-file)
64       (load custom-file))
65 #+END_SRC
66
67 *** Switch the focus to help window when it appears
68 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
69   (setq help-window-select t)
70 #+END_SRC
71
72 *** Set default window size
73 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
74   (setq initial-frame-alist
75         '((width . 120)
76           (height . 50)))
77
78   ;; (setq-default indicate-empty-lines t)
79 #+END_SRC
80
81 *** Stop auto save
82 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
83   (setq auto-save-default nil)
84
85   ;; restore last session
86   ;; (desktop-save-mode t)
87 #+END_SRC
88
89 *** temp folder
90 Make a temp directory for all cache/history files
91 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
92   (defconst sd-temp-directory
93     (file-name-as-directory "~/.emacs.d/temp"))
94
95   (unless (file-exists-p sd-temp-directory)
96     (mkdir sd-temp-directory))
97 #+END_SRC
98
99 *** Save minibuffer history
100 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
101   (setq savehist-file (concat sd-temp-directory "history"))
102   (setq history-length 1000)
103   (setq savehist-additional-variables '(kill-ring search-ring regexp-search-ring))
104   (savehist-mode 1)
105 #+END_SRC
106
107 * Package Management Tools
108
109 ** Use-package
110
111 Using [[https://github.com/jwiegley/use-package][use-package]] to manage emacs packages
112
113 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
114
115   (unless (package-installed-p 'use-package)
116     (package-refresh-contents)
117     (package-install 'use-package))
118
119   (require 'use-package)
120
121 #+END_SRC
122
123 ** El-get
124
125 [[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. 
126 Check out [[http://tapoueh.org/emacs/el-get.html][el-get]].
127
128 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
129
130   (use-package el-get
131     :ensure t
132     :init
133     (add-to-list 'load-path "~/.emacs.d/el-get"))
134
135 #+END_SRC
136
137 * Color and Fonts Settings
138
139 ** highlight current line
140
141 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
142
143   (global-hl-line-mode)
144
145 #+END_SRC
146
147 ** Smart Comments
148
149 [[https://github.com/paldepind/smart-comment][smart-comments]]
150
151 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
152
153   (use-package smart-comment
154     :ensure t
155     :bind ("M-;" . smart-conmment))
156
157 #+END_SRC
158
159 ** Font Setting
160
161 syntax highlighting
162
163 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
164
165   (global-font-lock-mode 1)
166
167 #+END_SRC
168
169 [[https://github.com/i-tu/Hasklig][Hasklig]] and Source Code Pro, defined fonts family
170
171 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
172
173   (if window-system
174       (defvar sd/fixed-font-family
175         (cond ((x-list-fonts "Hasklig")         "Hasklig")
176               ((x-list-fonts "Source Code Pro") "Source Code Pro:weight:light")
177               ((x-list-fonts "Anonymous Pro")   "Anonymous Pro")
178               ((x-list-fonts "M+ 1mn")          "M+ 1mn"))
179         "The fixed width font based on what is installed, `nil' if not defined."))
180
181 #+END_SRC
182
183 Setting the fonts 
184
185 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
186
187   (if window-system
188       (when sd/fixed-font-family
189         (set-frame-font sd/fixed-font-family)
190         (set-face-attribute 'default nil :font sd/fixed-font-family :height 130)
191         (set-face-font 'default sd/fixed-font-family)))
192
193 #+END_SRC
194
195 ** Color Theme
196
197 Loading theme should be after all required loaded, refere [[https://github.com/jwiegley/use-package][:defer]] in =use-package=
198
199 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
200
201   (setq vc-follow-symlinks t)
202
203   (use-package color-theme
204     :ensure t
205     :init (require 'color-theme)
206     :config (use-package color-theme-sanityinc-tomorrow
207               :ensure t
208               :no-require t
209               :config
210               (load-theme 'sanityinc-tomorrow-bright t)))
211
212   ;(eval-after-load 'color-theme
213   ;  (load-theme 'sanityinc-tomorrow-bright t))
214
215 #+END_SRC
216
217 Change the Org-mode colors 
218
219 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
220
221   (defun org-src-color-blocks-light ()
222     "Colors the block headers and footers to make them stand out more for lighter themes"
223     (interactive)
224     (custom-set-faces
225      '(org-block-begin-line
226       ((t (:underline "#A7A6AA" :foreground "#008ED1" :background "#EAEAFF"))))
227      '(org-block-background
228        ((t (:background "#FFFFEA"))))
229      '(org-block
230        ((t (:background "#FFFFEA"))))
231      '(org-block-end-line
232        ((t (:overline "#A7A6AA" :foreground "#008ED1" :background "#EAEAFF"))))
233
234      '(mode-line-buffer-id ((t (:foreground "#005000" :bold t))))
235      '(which-func ((t (:foreground "#008000"))))))
236
237   (defun org-src-color-blocks-dark ()
238     "Colors the block headers and footers to make them stand out more for dark themes"
239     (interactive)
240     (custom-set-faces
241      '(org-block-begin-line
242        ((t (:foreground "#008ED1" :background "#002E41"))))
243      '(org-block-background
244        ((t (:background "#000000"))))
245      '(org-block
246        ((t (:background "#000000"))))
247      '(org-block-end-line
248        ((t (:foreground "#008ED1" :background "#002E41"))))
249
250      '(mode-line-buffer-id ((t (:foreground "black" :bold t))))
251      '(which-func ((t (:foreground "green"))))))
252
253   (org-src-color-blocks-dark)
254
255 #+END_SRC
256
257 improve color for org-mode
258 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
259   (deftheme ha/org-theme "Sub-theme to beautify org mode")
260
261   (if window-system
262       (defvar sd/variable-font-tuple
263         (cond ((x-list-fonts "Source Sans Pro") '(:font "Source Sans Pro"))
264               ((x-list-fonts "Lucida Grande")   '(:font "Lucida Grande"))
265               ((x-list-fonts "Verdana")         '(:font "Verdana"))
266               ((x-family-fonts "Sans Serif")    '(:family "Sans Serif"))
267               (nil (warn "Cannot find a Sans Serif Font.  Install Source Sans Pro.")))
268         "My variable width font available to org-mode files and whatnot."))
269
270   (defun sd/org-color ()
271     (let* ((sd/fixed-font-tuple (list :font sd/fixed-font-family))
272            (base-font-color     (face-foreground 'default nil 'default))
273            (background-color    (face-background 'default nil 'default))
274            (primary-color       (face-foreground 'mode-line nil))
275            (secondary-color     (face-background 'secondary-selection nil 'region))
276            (base-height         (face-attribute 'default :height))
277            (headline           `(:inherit default :weight bold :foreground ,base-font-color)))
278       (custom-theme-set-faces 'ha/org-theme
279                               `(org-agenda-structure ((t (:inherit default :height 2.0 :underline nil))))
280                               `(org-verbatim ((t (:inherit 'fixed-pitched :foreground "#aef"))))
281                               `(org-table ((t (:inherit 'fixed-pitched))))
282                               `(org-block ((t (:inherit 'fixed-pitched))))
283                               `(org-block-background ((t (:inherit 'fixed-pitched))))
284                               `(org-block-begin-line ((t (:inherit 'fixed-pitched))))
285                               `(org-block-end-line ((t (:inherit 'fixed-pitched))))
286                               `(org-level-8 ((t (,@headline ,@sd/variable-font-tuple))))
287                               `(org-level-7 ((t (,@headline ,@sd/variable-font-tuple))))
288                               `(org-level-6 ((t (,@headline ,@sd/variable-font-tuple))))
289                               `(org-level-5 ((t (,@headline ,@sd/variable-font-tuple))))
290                               `(org-level-4 ((t (,@headline ,@sd/variable-font-tuple
291                                                             :height ,(round (* 1.1 base-height))))))
292                               `(org-level-3 ((t (,@headline ,@sd/variable-font-tuple
293                                                             :height ,(round (* 1.25 base-height))))))
294                               `(org-level-2 ((t (,@headline ,@sd/variable-font-tuple
295                                                             :height ,(round (* 1.5 base-height))))))
296                               `(org-level-1 ((t (,@headline ,@sd/variable-font-tuple
297                                                             :height ,(round (* 1.75 base-height))))))
298                               `(org-document-title ((t (,@headline ,@sd/variable-font-tuple :height 1.5 :underline nil)))))))
299
300
301 #+END_SRC
302
303 ** Rainbow-delimiter
304
305 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
306
307   (use-package rainbow-delimiters
308     :ensure t
309     :init
310     (add-hook 'prog-mode-hook #'rainbow-delimiters-mode))
311
312 #+END_SRC
313
314 ** page-break-lines
315
316 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
317
318   (use-package page-break-lines
319     :ensure t
320     :config
321     (turn-on-page-break-lines-mode))
322
323 #+END_SRC
324
325 ** rainbow-mode
326
327 Enable rainbow mode in emacs lisp mode
328
329 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
330   (use-package rainbow-mode
331     :ensure t
332   ;  :init
333   ;  (add-hook emacs-lisp-mode-hook 'rainbow-mode)
334     )
335
336 #+END_SRC
337
338 * Mode-line
339
340 ** clean mode line
341
342 clean mode line, Refer to [[https://www.masteringemacs.org/article/hiding-replacing-modeline-strings][Marstering Emacs]]
343
344 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
345   (defvar mode-line-cleaner-alist
346     `((auto-complete-mode . " Î±")
347       (yas/minor-mode . " Ï…")
348       (paredit-mode . " Ï€")
349       (eldoc-mode . "")
350       (abbrev-mode . "")
351       (projectile-mode . "")
352       (ivy-mode . "")
353       (undo-tree-mode . "")
354       ;; default is WK
355       (which-key-mode . "")
356       ;; default is SP
357       (smartparens-mode . "")
358       ;; default is LR
359       (linum-relative-mode . "")
360       ;; default is ARev
361       (auto-revert-mode . "")
362       ;; default is Ind
363       (org-indent-mode . "")
364       ;; default is  Fly
365       (flyspell-mode . "")
366       ;; Major modes
367       (lisp-interaction-mode . "λ")
368       (hi-lock-mode . "")
369       (python-mode . "Py")
370       (emacs-lisp-mode . "EL")
371       (eshell-mode . "ε")
372       (nxhtml-mode . "nx"))
373     "Alist for `clean-mode-line'.
374
375   When you add a new element to the alist, keep in mind that you
376   must pass the correct minor/major mode symbol and a string you
377   want to use in the modeline *in lieu of* the original.")
378
379
380   (defun clean-mode-line ()
381     (interactive)
382     (loop for cleaner in mode-line-cleaner-alist
383           do (let* ((mode (car cleaner))
384                    (mode-str (cdr cleaner))
385                    (old-mode-str (cdr (assq mode minor-mode-alist))))
386                (when old-mode-str
387                    (setcar old-mode-str mode-str))
388                  ;; major mode
389                (when (eq mode major-mode)
390                  (setq mode-name mode-str)))))
391
392
393   (add-hook 'after-change-major-mode-hook 'clean-mode-line)
394 #+END_SRC
395
396 ** Powerline mode
397
398 Install powerline mode [[https://github.com/milkypostman/powerline][powerline]]
399
400 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
401   (use-package powerline
402     :ensure t
403     :config
404     ;; (powerline-center-theme)
405     )
406
407   ;; (use-package smart-mode-line
408   ;;   :ensure t)
409   ;; (use-package smart-mode-line-powerline-theme
410   ;;   :ensure t)
411 #+END_SRC
412
413 Revised powerline-center-theme
414 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
415   (defun sd/powerline-simpler-vc (s)
416     (if s
417         (replace-regexp-in-string "Git[:-]" "" s)
418       s))
419
420   (defface sd/powerline-active1 '((t (:background "yellow" :foreground "black" :inherit mode-line)))
421     "My Powerline face 1 based on powerline-active1."
422     :group 'powerline)
423
424   (defface sd/buffer-modified-active1 '((t (:background "red" :foreground "black" :inherit mode-line)))
425     "My Powerline face 1 based on powerline-active1."
426     :group 'powerline)
427
428   (defface sd/buffer-view-active1 '((t (:background "green" :foreground "black" :inherit mode-line)))
429     "My Powerline face 1 based on powerline-active1."
430     :group 'powerline)
431
432   (defface sd/mode-line-buffer-id
433     '((t (:background "yellow" :foreground "black" :inherit mode-line-buffer-id)))
434     "My powerline mode-line face, based on mode-line-buffer-id"
435     :group 'powerline)
436
437   ;; Don't show buffer modified for scratch and eshell mode
438   (defun sd/buffer-show-modified ()
439     "Dot not show modified indicator for buffers"
440     (interactive)
441     (unless (or (string-match "*scratch*" (buffer-name))
442                 (equal major-mode 'eshell-mode))
443       t))
444
445   (defun sd/powerline-center-theme_revised ()
446     "Setup a mode-line with major and minor modes centered."
447     (interactive)
448     (setq-default mode-line-format
449                   '("%e"
450                     (:eval
451                      (let* ((active (powerline-selected-window-active))
452                             (mode-line-buffer-id (if active 'sd/mode-line-buffer-id 'mode-line-buffer-id-inactive))
453                             (mode-line (if active 'mode-line 'mode-line-inactive))
454                             (my-face1 (if active 'sd/powerline-active1 'powerline-inactive1))
455                             (my-face-buffer-modified (if (and (sd/buffer-show-modified) (buffer-modified-p)) 
456                                                          'sd/buffer-modified-active1
457                                                        (if buffer-read-only 'sd/buffer-view-active1
458                                                          my-face1)))
459                             (face1 (if active 'powerline-active1 'powerline-inactive1))
460                             (face2 (if active 'powerline-active2 'powerline-inactive2))
461                             (separator-left (intern (format "powerline-%s-%s"
462                                                             (powerline-current-separator)
463                                                             (car powerline-default-separator-dir))))
464                             (separator-right (intern (format "powerline-%s-%s"
465                                                              (powerline-current-separator)
466                                                              (cdr powerline-default-separator-dir))))
467                             (lhs (list (powerline-raw "%* " my-face-buffer-modified 'l)
468                                        ;; (powerline-buffer-size mode-line 'l)
469                                        (powerline-buffer-id mode-line-buffer-id 'l)
470                                        (powerline-raw " " my-face1)
471                                        (funcall separator-left my-face1 face1)
472                                        (powerline-narrow face1 'l)
473                                        ;; (powerline-vc face1)
474                                        (sd/powerline-simpler-vc (powerline-vc face1))))
475                             (rhs (list (powerline-raw global-mode-string face1 'r)
476                                        (powerline-raw "%4l" face1 'r)
477                                        (powerline-raw ":" face1)     
478                                        (powerline-raw "%3c" face1 'r)
479                                        (funcall separator-right face1 my-face1)
480                                        ;; (powerline-raw " " my-face1)
481                                        (powerline-raw (format-time-string " %I:%M %p  ") my-face1 'r)
482                                        ;; (powerline-raw "%6p" my-face1 'r)
483                                        ;; (powerline-hud my-face1 face1 )
484                                        ))
485                             (center (list (powerline-raw " " face1)
486                                           (funcall separator-left face1 face2)
487                                           (when (and (boundp 'erc-track-minor-mode) erc-track-minor-mode)
488                                             (powerline-raw erc-modified-channels-object face2 'l))
489                                           (powerline-major-mode face2 'l)
490                                           (powerline-process face2)
491                                           (powerline-raw " :" face2)
492                                           (powerline-minor-modes face2 'l)
493                                           (powerline-raw " " face2)
494                                           (funcall separator-right face2 face1))))
495                        (concat (powerline-render lhs)
496                                (powerline-fill-center face1 (/ (powerline-width center) 2.0))
497                                (powerline-render center)
498                                (powerline-fill face1 (powerline-width rhs))
499                                (powerline-render rhs)))))))
500
501   (sd/powerline-center-theme_revised)
502 #+END_SRC
503
504 Fix the issue in mode line when showing triangle 
505 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
506   (setq ns-use-srgb-colorspace nil)
507 #+END_SRC
508
509 set height in mode line
510 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
511   (set-variable 'powerline-height 14)
512   (set-variable 'powerline-text-scale-factor (/ (float 100) 140))
513   ;; (custom-set-variables
514   ;;  '(powerline-height 14)
515   ;;  '(powerline-text-scale-factor (/ (float 100) 140)))
516   ;; 100/140;0.8
517   (set-face-attribute 'mode-line nil :height 100)
518 #+END_SRC
519
520 * IDO & SMEX
521 ** IDO
522 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
523   (use-package ido
524     :ensure t
525     :init (setq ido-enable-flex-matching t
526                 ido-ignore-extensions t
527                 ido-use-virtual-buffers t
528                 ido-everywhere t)
529     (setq ido-save-directory-list-file (concat sd-temp-directory "ido.last"))
530     :config
531     (ido-mode 1)
532     (ido-everywhere 1)
533     (add-to-list 'completion-ignored-extensions ".pyc"))
534
535   (icomplete-mode t)
536 #+END_SRC
537
538 ** FLX
539 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
540   (use-package flx-ido
541     :ensure t
542     :init (setq ido-enable-flex-matching t
543                 ido-use-faces nil)
544     :config (flx-ido-mode 1))
545 #+END_SRC
546
547 ** IDO-vertically
548 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
549   (use-package ido-vertical-mode
550     :ensure t
551     :init
552     (setq ido-vertical-define-keys 'C-n-C-p-up-and-down)
553     :config
554     (ido-vertical-mode 1))
555 #+END_SRC
556
557 ** SMEX
558 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
559   (use-package smex
560     :ensure t
561     :init
562     (setq smex-save-file (concat sd-temp-directory "smex-items"))
563     (smex-initialize)
564     :bind
565     ("M-x" . smex)
566     ("M-X" . smex-major-mode-commands))
567 #+END_SRC
568
569 ** Ido-ubiquitous
570 Use [[https://github.com/DarwinAwardWinner/ido-ubiquitous][ido-ubiquitous]] for ido everywhere. It makes =describe-function= can also use ido
571 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
572   (use-package ido-ubiquitous
573     :ensure t
574     :init
575     (setq magit-completing-read-function 'magit-ido-completing-read)
576     (setq gnus-completing-read-function 'gnus-ido-completing-read)
577     :config
578     (ido-ubiquitous-mode 1))
579 #+END_SRC
580
581 ** Ido-exit-target
582 [[https://github.com/waymondo/ido-exit-target][ido-exit-target]] let you open file/buffer on =other-windows= when call =ido-switch-buffer=
583 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
584   (use-package ido-exit-target
585     :ensure t
586     :init
587     (mapcar (lambda (map)
588               (define-key map (kbd "C-j") #'ido-exit-target-split-window-right)
589               (define-key map (kbd "C-k") #'ido-exit-target-split-window-below))
590             (list ido-buffer-completion-map
591                   ;; ido-common-completion-map
592                   ido-file-completion-map
593                   ido-file-dir-completion-map)))
594 #+END_SRC
595
596 ** Counsel
597 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
598   (use-package counsel
599     :ensure t
600     :defer t
601     :init
602     ;; (global-set-key (kbd "M-x") 'counsel-M-x)
603     (global-set-key (kbd "C-h f") 'counsel-describe-function)
604     (global-set-key (kbd "C-h v") 'counsel-describe-variable)
605     ;; (set-face-attribute 'ivy-current-match nil :background "Orange" :foreground "black")
606     (define-key read-expression-map (kbd "C-r") 'counsel-expression-history)
607     (global-set-key (kbd "C-c C-r") 'ivy-resume))
608
609
610
611   ;; (global-set-key "\C-s" 'swiper)
612   ;; (global-set-key (kbd "<f6>") 'ivy-resume)
613   ;; ;; (global-set-key (kbd "C-x C-f") 'counsel-find-file)
614   ;; (global-set-key (kbd "<f1> l") 'counsel-load-library)
615   ;; (global-set-key (kbd "<f2> i") 'counsel-info-lookup-symbol)
616   ;; (global-set-key (kbd "<f2> u") 'counsel-unicode-char)
617   ;; (global-set-key (kbd "C-c g") 'counsel-git)
618   ;; (global-set-key (kbd "C-c j") 'counsel-git-grep)
619   ;; (global-set-key (kbd "C-c k") 'counsel-ag)
620   ;; (global-set-key (kbd "C-x l") 'counsel-locate)
621   ;; (global-set-key (kbd "C-S-o") 'counsel-rhythmbox)
622
623   ;; (set-face-attribute
624   ;;  'ivy-current-match nil
625   ;;  :background "Orange"
626   ;;  :foreground "black")
627
628   ;; ivy-resume
629   ;; (define-key swiper-map (kbd "M-%") 'swiper-aa-replace)
630 #+END_SRC
631
632 ** helm
633 let helm windows split inside current window
634 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
635   (with-eval-after-load 'helm
636     (setq helm-split-window-in-side-p t))
637 #+END_SRC
638
639 * Org-mode Settings
640
641 ** Org-mode Basic setting
642
643 Always indents header, and hide header leading starts so that no need type =#+STATUP: indent= 
644
645 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
646   (use-package org
647     :ensure t
648     :init
649     (setq org-startup-indented t)
650     (setq org-hide-leading-starts t)
651     (setq org-src-fontify-natively t)
652     (setq org-src-tab-acts-natively t)
653     (setq org-confirm-babel-evaluate nil)
654     (setq org-use-speed-commands t)
655     (setq org-completion-use-ido t))
656
657   (org-babel-do-load-languages
658    'org-babel-load-languages
659    '((python . t)
660      (C . t)
661      (perl . t)
662      (calc . t)
663      (latex . t)
664      (java . t)
665      (ruby . t)
666      (lisp . t)
667      (scheme . t)
668      (sh . t)
669      (sqlite . t)
670      (js . t)
671      (gnuplot . t)
672      (ditaa . t)))
673
674   ;; use current window for org source buffer editting
675   (setq org-src-window-setup 'current-window )
676
677   (define-key org-mode-map (kbd "C-'") nil)
678   ;; C-M-i is mapped to imenu globally
679   (define-key org-mode-map (kbd "C-M-i") nil)
680
681   ;; set the ditta.jar path
682   (setq org-ditaa-jar-path "/usr/local/Cellar/ditaa/0.9/libexec/ditaa0_9.jar")
683   (unless 
684       (file-exists-p org-ditaa-jar-path)
685     (error "seudut: ditaa.jar not found at %s " org-ditaa-jar-path))
686 #+END_SRC
687
688 ** Org-bullets
689
690 use [[https://github.com/sabof/org-bullets][org-bullets]] package to show utf-8 charactes
691
692 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
693   (use-package org-bullets
694     :ensure t
695     :init
696     (add-hook 'org-mode-hook
697               (lambda ()
698                 (org-bullets-mode t))))
699
700   (setq org-bullets-bullet-list '("⦿" "✪" "â—‰" "â—‹" "â–º" "â—†"))
701
702   ;; increase font size when enter org-src-mode
703   (add-hook 'org-src-mode-hook (lambda () (text-scale-increase 2)))
704 #+END_SRC
705
706 ** Worf Mode
707
708 [[https://github.com/abo-abo/worf][worf]] mode is an extension of vi-like binding for org-mode. 
709 In =worf-mode=, it is mapping =[=, =]= as =worf-backward= and =worf-forward= in global, wich
710 cause we cannot input =[= and =]=, so here I unset this mappings. And redifined this two to
711 =M-[= and =M-]=. see this [[https://github.com/abo-abo/worf/issues/19#issuecomment-223756599][issue]]
712
713 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
714
715   (use-package worf
716     :ensure t
717     :commands worf-mode
718     :init (add-hook 'org-mode-hook 'worf-mode)
719     ;; :config
720     ;; (define-key worf-mode-map "[" nil)
721     ;; (define-key worf-mode-map "]" nil)
722     ;; (define-key worf-mode-map (kbd "M-[") 'worf-backward)
723     ;; (define-key worf-mode-map (kbd "M-]") 'worf-forward)
724     )
725
726 #+END_SRC
727
728 ** Get Things Done
729
730 Refer to [[http://doc.norang.ca/org-mode.html][Organize Your Life in Plain Text]]
731 *** basic setup
732
733 standard key binding
734
735 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
736   (global-set-key "\C-cl" 'org-store-link)
737   (global-set-key "\C-ca" 'org-agenda)
738   (global-set-key "\C-cb" 'org-iswitchb)
739 #+END_SRC
740
741 *** Plain List 
742
743 Replace the list bullet =-=, =+=,  with =•=, a litter change based [[https://github.com/howardabrams/dot-files/blob/master/emacs-org.org][here]]
744
745 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
746   ;; (use-package org-mode
747   ;;   :init
748   ;;   (font-lock-add-keywords 'org-mode
749   ;;    '(("^ *\\([-+]\\) "
750   ;;           (0 (prog1 () (compose-region (match-beginning 1) (match-end 1) "•")))))))
751 #+END_SRC
752  
753 *** Todo Keywords
754
755 refer to [[http://coldnew.github.io/coldnew-emacs/#orgheadline94][fancy todo states]], 
756
757 To track TODO state changes, the =!= is to insert a timetamp, =@= is to insert a note with
758 timestamp for the state change.
759
760 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
761     ;; (setq org-todo-keywords
762     ;;        '((sequence "☛ TODO(t)" "|" "✔ DONE(d)")
763     ;;          (sequence "âš‘ WAITING(w)" "|")
764     ;;          (sequence "|" "✘ CANCELLED(c)")))
765   ; (setq org-todo-keyword-faces
766   ;        (quote ("TODO" .  (:foreground "red" :weight bold))
767   ;               ("NEXT" .  (:foreground "blue" :weight bold))
768   ;               ("WAITING" . (:foreground "forest green" :weight bold))
769   ;               ("DONE" .  (:foreground "magenta" :weight bold))
770   ;               ("CANCELLED" . (:foreground "forest green" :weight bold))))
771
772
773   (setq org-todo-keywords
774         (quote ((sequence "TODO(t)" "NEXT(n)" "|" "DONE(d!)")
775                 ;; (sequence "WAITING(w@/!)" "HOLD(h@/!)" "|" "CANCELLED(c@/!)" "PHONE" "MEETING")
776                 (sequence "WAITING(w@/!)" "HOLD(h@/!)" "|" "CANCELLED(c@/!)" ))))
777
778   (setq org-todo-keyword-faces
779         (quote (("TODO" :foreground "red" :weight bold)
780                 ("NEXT" :foreground "blue" :weight bold)
781                 ("DONE" :foreground "forest green" :weight bold)
782                 ("WAITING" :foreground "orange" :weight bold)
783                 ("HOLD" :foreground "magenta" :weight bold)
784                 ("CANCELLED" :foreground "forest green" :weight bold)
785                 ;; ("MEETING" :foreground "forest green" :weight bold)
786                 ;; ("PHONE" :foreground "forest green" :weight bold)
787                 )))
788 #+END_SRC
789
790 Fast todo selections
791
792 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
793   (setq org-use-fast-todo-selection t)
794   (setq org-treat-S-cursor-todo-selection-as-state-change nil)
795 #+END_SRC
796
797 TODO state triggers and tags, [[http://doc.norang.ca/org-mode.html][Organize Your Life in Plain Text]]
798
799 - Moving a task to =CANCELLED=, adds a =CANCELLED= tag
800 - Moving a task to =WAITING=, adds a =WAITING= tag
801 - Moving a task to =HOLD=, add =HOLD= tags
802 - Moving a task to =DONE=, remove =WAITING=, =HOLD= tag
803 - Moving a task to =NEXT=, remove all waiting/hold/cancelled tags
804
805 This tags are used to filter tasks in agenda views
806 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
807   (setq org-todo-state-tags-triggers
808         (quote (("CANCELLED" ("CANCELLED" . t))
809                 ("WAITING" ("WAITING" . t))
810                 ("HOLD" ("WAITING") ("HOLD" . t))
811                 (done ("WAITING") ("HOLD"))
812                 ("TODO" ("WAITING") ("CANCELLED") ("HOLD"))
813                 ("NEXT" ("WAITING") ("CANCELLED") ("HOLD"))
814                 ("DONE" ("WAITING") ("CANCELLED") ("HOLD")))))
815 #+END_SRC
816
817 Logging Stuff 
818 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
819   ;; log time when task done
820   ;; (setq org-log-done (quote time))
821   ;; save clocking into to LOGBOOK
822   (setq org-clock-into-drawer t)
823   ;; save state change notes and time stamp into LOGBOOK drawer
824   (setq org-log-into-drawer t)
825   (setq org-clock-into-drawer "CLOCK")
826 #+END_SRC
827
828 *** Tags
829 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
830   (setq org-tag-alist (quote ((:startgroup)
831                               ("@office" . ?e)
832                               ("@home" . ?h)
833                               (:endgroup)
834                               ("WAITING" . ?w)
835                               ("HOLD" . ?h)
836                               ("CANCELLED" . ?c))))
837
838   ;; Allow setting single tags without the menu
839   (setq org-fast-tag-selection-single-key (quote expert))
840 #+END_SRC
841
842 *** Capture - Refile - Archive
843
844 Capture lets you quickly store notes with little interruption of your work flow.
845
846 **** Capture Templates
847
848 When a new taks needs to be added, categorize it as 
849
850 All captured file which need next actions are stored in =refile.org=, 
851 - A new task / note (t) =refile.org=
852 - A work task in office =office.org=
853 - A jourenl =diary.org=
854 - A new habit (h) =refile.org=
855
856 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
857   (setq org-directory "~/org")
858   (setq org-default-notes-file "~/org/refile.org")
859   (setq sd/org-diary-file "~/org/diary.org")
860
861   (global-set-key (kbd "C-c c") 'org-capture)
862
863   (setq org-capture-templates
864         (quote (("t" "Todo" entry (file org-default-notes-file)
865                  "* TODO %?\n:LOGBOOK:\n- Added: %U\t\tAt: %a\n:END:")
866                 ("n" "Note" entry (file org-default-notes-file)
867                  "* %? :NOTE:\n:LOGBOOK:\n- Added: %U\t\tAt: %a\n:END:")
868                 ("j" "Journal" entry (file+datetree sd/org-diary-file)
869                  "* %?\n:LOGBOOK:\n:END:" :clock-in t :clock-resume t)
870                 ("h" "Habit" entry (file org-default-notes-file)
871                  "* 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 "))))
872 #+END_SRC
873
874 **** Refiling Tasks
875
876 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
877   (setq org-refile-targets (quote (;; (nil :maxlevel . 9)
878                                    (org-agenda-files :maxlevel . 9))))
879
880   (setq org-refile-use-outline-path t)
881
882   (setq org-refile-allow-creating-parent-nodes (quote confirm))
883 #+END_SRC
884
885 *** Agenda Setup
886 Setting agenda files and the agenda view
887 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
888   (setq org-agenda-files (quote ("~/org/gtd.org"
889                                  "~/org/work.org")))
890
891   ;; only show today's tasks in agenda view
892   (setq org-agenda-span 'day)
893   ;; Use current windows for agenda view
894   (setq org-agenda-window-setup 'current-window)
895
896   ;; show all feature entries for repeating tasks,
897   ;; this is already setting by default
898   (setq org-agenda-repeating-timestamp-show-all t)
899
900   ;; Show all agenda dates - even if they are empty
901   (setq org-agenda-show-all-dates t)
902 #+END_SRC
903
904 ** Export PDF
905
906 Install MacTex-basic and some tex packages
907
908 #+BEGIN_SRC bash 
909
910   sudo tlmgr update --self
911
912   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
913
914 #+END_SRC
915
916 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
917   ;; ;; allow for export=>beamer by placing
918
919   ;; http://emacs-fu.blogspot.com/2011/04/nice-looking-pdfs-with-org-mode-and.html
920   ;; #+LaTeX_CLASS: beamer in org files
921   (unless (boundp 'org-export-latex-classes)
922     (setq org-export-latex-classes nil))
923   (add-to-list 'org-export-latex-classes
924     ;; beamer class, for presentations
925     '("beamer"
926        "\\documentclass[11pt]{beamer}\n
927         \\mode<{{{beamermode}}}>\n
928         \\usetheme{{{{beamertheme}}}}\n
929         \\usecolortheme{{{{beamercolortheme}}}}\n
930         \\beamertemplateballitem\n
931         \\setbeameroption{show notes}
932         \\usepackage[utf8]{inputenc}\n
933         \\usepackage[T1]{fontenc}\n
934         \\usepackage{hyperref}\n
935         \\usepackage{color}
936         \\usepackage{listings}
937         \\lstset{numbers=none,language=[ISO]C++,tabsize=4,
938     frame=single,
939     basicstyle=\\small,
940     showspaces=false,showstringspaces=false,
941     showtabs=false,
942     keywordstyle=\\color{blue}\\bfseries,
943     commentstyle=\\color{red},
944     }\n
945         \\usepackage{verbatim}\n
946         \\institute{{{{beamerinstitute}}}}\n          
947          \\subject{{{{beamersubject}}}}\n"
948
949        ("\\section{%s}" . "\\section*{%s}")
950  
951        ("\\begin{frame}[fragile]\\frametitle{%s}"
952          "\\end{frame}"
953          "\\begin{frame}[fragile]\\frametitle{%s}"
954          "\\end{frame}")))
955
956     ;; letter class, for formal letters
957
958     (add-to-list 'org-export-latex-classes
959
960     '("letter"
961        "\\documentclass[11pt]{letter}\n
962         \\usepackage[utf8]{inputenc}\n
963         \\usepackage[T1]{fontenc}\n
964         \\usepackage{color}"
965  
966        ("\\section{%s}" . "\\section*{%s}")
967        ("\\subsection{%s}" . "\\subsection*{%s}")
968        ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
969        ("\\paragraph{%s}" . "\\paragraph*{%s}")
970        ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
971
972
973   (require 'ox-md)
974   (require 'ox-beamer)
975
976   (setq org-latex-pdf-process
977         '("pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
978           "pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
979           "pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"))
980
981   (setq TeX-parse-self t)
982
983   (setq TeX-PDF-mode t)
984   (add-hook 'LaTeX-mode-hook
985             (lambda ()
986               (LaTeX-math-mode)
987               (setq TeX-master t)))
988
989 #+END_SRC
990
991 ** others
992
993 extend org-mode's easy templates, refer to [[http://coldnew.github.io/coldnew-emacs/#orgheadline94][Extend org-modes' esay templates]]
994
995 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
996
997   (add-to-list 'org-structure-template-alist
998                '("E" "#+BEGIN_SRC emacs-lisp :tangle yes :results silent\n?\n#+END_SRC"))
999   (add-to-list 'org-structure-template-alist
1000                '("S" "#+BEGIN_SRC sh\n?\n#+END_SRC"))
1001   (add-to-list 'org-structure-template-alist
1002                '("p" "#+BEGIN_SRC plantuml :file uml.png \n?\n#+END_SRC"))
1003
1004 #+END_SRC
1005
1006 * Magit
1007 [[https://github.com/magit/magit][Magit]] is a very cool git interface on Emacs.
1008 and Defined keys, using vi keybindings, Refer abo-abo's setting [[https://github.com/abo-abo/oremacs/blob/c5cafdcebc88afe9e73cc8bd40c49b70675509c7/modes/ora-nextmagit.el][here]]
1009 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1010   (use-package magit
1011     :ensure t
1012     :init
1013     ;; don't ask me to confirm the unsaved change 
1014     (setq magit-save-repository-buffers nil)
1015     :commands magit-status magit-blame
1016     :config
1017     (dolist (map (list magit-status-mode-map
1018                        magit-log-mode-map
1019                        magit-diff-mode-map
1020                        magit-staged-section-map))
1021       (define-key map "j" 'magit-section-forward)
1022       (define-key map "k" 'magit-section-backward)
1023       (define-key map "D" 'magit-discard)
1024       (define-key map "O" 'magit-discard-file)
1025       (define-key map "n" nil)
1026       (define-key map "p" nil)
1027       (define-key map "v" 'recenter-top-bottom)
1028       (define-key map "i" 'magit-section-toggle)))
1029 #+END_SRC
1030
1031 * Eshell
1032 *** Eshell alias
1033 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1034   (defalias 'e 'find-file)
1035   (defalias 'ff 'find-file)
1036   (defalias 'ee 'find-files)
1037 #+END_SRC
1038
1039 *** eshell temp directory
1040 set default eshell history folder
1041 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1042   (setq eshell-directory-name (concat  sd-temp-directory "eshell"))
1043 #+END_SRC
1044
1045 *** Eshell erase buffer
1046 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1047   (defun sd/eshell-clear-buffer ()
1048     "Clear eshell buffer"
1049     (interactive)
1050     (let ((inhibit-read-only t))
1051       (erase-buffer)
1052       (eshell-send-input)))
1053
1054    (add-hook 'eshell-mode-hook (lambda ()
1055                                 (local-set-key (kbd "C-l") 'sd/eshell-clear-buffer)))
1056 #+END_SRC
1057
1058 *** Toggle Eshell
1059 Toggle an eshell in split window below, refer [[http://www.howardism.org/Technical/Emacs/eshell-fun.html][eshell-here]]
1060 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1061   (defun sd/window-has-eshell ()
1062     "Check if current windows list has a eshell buffer, and return the window"
1063     (interactive)
1064     (let ((ret nil))
1065       (walk-windows (lambda (window)
1066                       (if (equal (with-current-buffer (window-buffer window) major-mode)
1067                                  'eshell-mode)
1068                           (setq ret window)))
1069                     nil nil)
1070       ret))
1071
1072   (defun sd/toggle-eshell-here ()
1073     "Toggle a eshell buffer vertically"
1074     (interactive)
1075     (if (sd/window-has-eshell)
1076         (if (equal major-mode 'eshell-mode)
1077             (progn
1078               (if (equal (length (window-list)) 1)
1079                   (mode-line-other-buffer)
1080                 (delete-window)))
1081           (select-window (sd/window-has-eshell)))
1082       (progn
1083         (let ((dir default-directory))
1084         
1085           (split-window-vertically (- (/ (window-total-height) 3)))
1086           (other-window 1)
1087           (unless (and (boundp 'eshell-buffer-name) (get-buffer eshell-buffer-name))
1088             (eshell))
1089           (switch-to-buffer eshell-buffer-name)
1090           (goto-char (point-max))
1091           (eshell-kill-input)
1092           (insert (format "cd %s" dir))
1093           (eshell-send-input)))))
1094
1095   ;; (global-unset-key (kbd "M-`"))
1096   (global-set-key (kbd "s-e") 'sd/toggle-eshell-here)
1097 #+END_SRC
1098
1099 *** TODO smart display
1100 * Misc Settings
1101
1102 ** [[https://github.com/abo-abo/hydra][Hydra]]
1103 *** hydra install
1104 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1105   (use-package hydra
1106     :ensure t)
1107   ;; disable new line in minibuffer when hint hydra
1108   (setq hydra-lv nil)
1109 #+END_SRC
1110
1111 *** Windmove Splitter
1112
1113 Refer [[https://github.com/abo-abo/hydra/blob/master/hydra-examples.el][hydra-example]], to enlarge or shrink the windows splitter
1114
1115 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1116
1117   (defun hydra-move-splitter-left (arg)
1118     "Move window splitter left."
1119     (interactive "p")
1120     (if (let ((windmove-wrap-around))
1121           (windmove-find-other-window 'right))
1122         (shrink-window-horizontally arg)
1123       (enlarge-window-horizontally arg)))
1124
1125   (defun hydra-move-splitter-right (arg)
1126     "Move window splitter right."
1127     (interactive "p")
1128     (if (let ((windmove-wrap-around))
1129           (windmove-find-other-window 'right))
1130         (enlarge-window-horizontally arg)
1131       (shrink-window-horizontally arg)))
1132
1133   (defun hydra-move-splitter-up (arg)
1134     "Move window splitter up."
1135     (interactive "p")
1136     (if (let ((windmove-wrap-around))
1137           (windmove-find-other-window 'up))
1138         (enlarge-window arg)
1139       (shrink-window arg)))
1140
1141   (defun hydra-move-splitter-down (arg)
1142     "Move window splitter down."
1143     (interactive "p")
1144     (if (let ((windmove-wrap-around))
1145           (windmove-find-other-window 'up))
1146         (shrink-window arg)
1147       (enlarge-window arg)))
1148
1149 #+END_SRC
1150
1151 *** hydra misc
1152 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1153   (defhydra sd/hydra-misc (:color red :columns nil)
1154     "Miscellaneous Commands"
1155     ("e" eshell "eshell" :exit t)
1156     ("p" (lambda ()
1157            (interactive)
1158            (if (not (eq nil (get-buffer "*Packages*")))
1159                (switch-to-buffer "*Packages*")
1160              (package-list-packages)))
1161      "list-package" :exit t)
1162     ("g" magit-status "git-status" :exit t)
1163     ("'" mode-line-other-buffer "last buffer" :exit t)
1164     ("C-'" mode-line-other-buffer "last buffer" :exit t)
1165     ("m" man "man" :exit t)
1166     ("d" dired-jump "dired" :exit t)
1167     ("b" ibuffer "ibuffer" :exit t)
1168     ("q" nil "quit")
1169     ("f" nil "quit"))
1170
1171   (global-set-key (kbd "C-'") 'sd/hydra-misc/body)
1172 #+END_SRC
1173
1174 *** hydra launcher
1175 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1176   (defhydra sd/hydra-launcher (:color blue :columns 2)
1177     "Launch"
1178     ("e" emms "emms" :exit t)
1179     ("q" nil "cancel"))
1180 #+END_SRC
1181
1182 ** Line Number
1183
1184 Enable linum mode on programming modes
1185
1186 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1187   (add-hook 'prog-mode-hook 'linum-mode)
1188   ;; (add-hook 'prog-mode-hook (lambda ()
1189   ;;                             (setq-default indicate-empty-lines t)))
1190 #+END_SRC
1191
1192 Fix the font size of line number
1193
1194 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1195
1196   (defun fix-linum-size ()
1197        (interactive)
1198        (set-face-attribute 'linum nil :height 110))
1199
1200   (add-hook 'linum-mode-hook 'fix-linum-size)
1201
1202 #+END_SRC
1203
1204 I like [[https://github.com/coldnew/linum-relative][linum-relative]], just like the =set relativenumber= on =vim=
1205
1206 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1207
1208   (use-package linum-relative
1209     :ensure t
1210     :config
1211     (defun linum-new-mode ()
1212       "If line numbers aren't displayed, then display them.
1213   Otherwise, toggle between absolute and relative numbers."
1214       (interactive)
1215       (if linum-mode
1216           (linum-relative-toggle)
1217         (linum-mode 1)))
1218
1219     :bind
1220     ("A-k" . linum-new-mode))
1221
1222   ;; auto enable linum-new-mode in programming modes
1223   (add-hook 'prog-mode-hook 'linum-relative-mode)
1224
1225 #+END_SRC
1226
1227 ** Save File Position
1228
1229 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1230
1231   (require 'saveplace)
1232   (setq-default save-place t)
1233   (setq save-place-forget-unreadable-files t)
1234   (setq save-place-skip-check-regexp "\\`/\\(?:cdrom\\|floppy\\|mnt\\|/[0-9]\\|\\(?:[^@/:]*@\\)?[^@/:]*[^@/:.]:\\)")
1235
1236 #+END_SRC
1237
1238 ** Multi-term
1239
1240 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1241
1242   (use-package multi-term
1243     :ensure t)
1244
1245 #+END_SRC
1246
1247 ** ace-link
1248
1249 [[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
1250 Type =o= to go to the link
1251
1252 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1253
1254   (use-package ace-link
1255     :ensure t
1256     :init
1257     (ace-link-setup-default))
1258
1259 #+END_SRC
1260
1261 ** Emux
1262
1263 [[https://github.com/re5et/emux][emux]] is 
1264
1265 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1266
1267   (el-get-bundle re5et/emux)
1268
1269 #+END_SRC
1270
1271 ** Smart Parens
1272
1273 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1274
1275   (use-package smartparens
1276     :ensure t
1277     :config
1278     (progn
1279       (require 'smartparens-config)
1280       (add-hook 'prog-mode-hook 'smartparens-mode)))
1281
1282 #+END_SRC
1283
1284 ** Ace-Windows
1285
1286 [[https://github.com/abo-abo/ace-window][ace-window]] 
1287
1288 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1289
1290   (use-package ace-window
1291     :ensure t
1292     :defer t
1293   ;  :init
1294   ;  (global-set-key (kbd "M-o") 'ace-window)
1295     :config
1296     (setq aw-keys '(?a ?s ?d ?f ?j ?k ?l)))
1297
1298 #+END_SRC
1299
1300 ** Which key
1301
1302 [[https://github.com/justbur/emacs-which-key][which-key]] show the key bindings 
1303
1304 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1305
1306   (use-package which-key
1307     :ensure t
1308     :config
1309     (which-key-mode))
1310
1311 #+END_SRC
1312
1313 ** Emms
1314 We can use [[https://www.gnu.org/software/emms/quickstart.html][Emms]] for multimedia in Emacs
1315 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1316   (use-package emms
1317     :ensure t
1318     :init
1319     (setq emms-directory (concat sd-temp-directory "emms"))
1320     (setq emms-source-file-default-directory "~/Music/")
1321     :config
1322     (emms-standard)
1323     (emms-default-players)
1324     (define-emms-simple-player mplayer '(file url)
1325       (regexp-opt '(".ogg" ".mp3" ".mgp" ".wav" ".wmv" ".wma" ".ape"
1326                     ".mov" ".avi" ".ogm" ".asf" ".mkv" ".divx" ".mpeg"
1327                     "http://" "mms://" ".rm" ".rmvb" ".mp4" ".flac" ".vob"
1328                     ".m4a" ".flv" ".ogv" ".pls"))
1329       "mplayer" "-slave" "-quiet" "-really-quiet" "-fullscreen")
1330     (emms-history-load))
1331 #+END_SRC
1332
1333 ** GnoGo
1334
1335 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
1336
1337 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1338
1339   (use-package gnugo
1340     :ensure t
1341     :defer t
1342     :init
1343     (require 'gnugo-imgen)
1344     (setq gnugo-xpms 'gnugo-imgen-create-xpms)
1345     (add-hook 'gnugo-start-game-hook '(lambda ()
1346                                         (gnugo-image-display-mode)
1347                                         (gnugo-grid-mode)))
1348       :config
1349     (add-to-list 'gnugo-option-history (format "--boardsize 19 --color black --level 1")))
1350
1351 #+END_SRC
1352
1353 ** Tabbar
1354
1355 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1356
1357   ;; (use-package tabbar-ruler
1358   ;;   :ensure t
1359   ;;   :init
1360   ;;   (setq tabbar-ruler-global-tabbar t)
1361   ;;   (setq tabbar-ruler-global-ruler t)
1362   ;;   (setq tabbar-ruler-popu-menu t)
1363   ;;   (setq tabbar-ruler-popu-toolbar t)
1364   ;;   (setq tabbar-use-images t)
1365   ;;   :config
1366   ;;   (tabbar-ruler-group-by-projectile-project)
1367   ;;   (global-set-key (kbd "s-1") 'tabbar-forward-group)
1368   ;;   (global-set-key (kbd "s-2") 'tabbar-ruler-forward))
1369
1370 #+END_SRC
1371
1372 ** View only for some directory
1373 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]]
1374 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1375   (dir-locals-set-class-variables
1376    'emacs
1377    '((nil . ((buffer-read-only . t)
1378              (show-trailing-whitespace . nil)
1379              (tab-width . 8)
1380              (eval . (whitespace-mode -1))))))
1381
1382   ;; (dir-locals-set-directory-class (expand-file-name "/usr/local/share/emacs") 'emacs)
1383   (dir-locals-set-directory-class "/usr/local/Cellar/emacs" 'emacs)
1384   ;; (dir-locals-set-directory-class "~/.emacs.d/elpa" 'emacs)
1385   (dir-locals-set-directory-class "~/dotfiles/emacs.d/elpa" 'emacs)
1386   (dir-locals-set-directory-class "~/dotfiles/emacs.d/el-get" 'emacs)
1387 #+END_SRC
1388
1389 ** Info plus
1390 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1391   (el-get-bundle info+
1392     :url "https://raw.githubusercontent.com/emacsmirror/emacswiki.org/master/info+.el"
1393     (require 'info+))
1394 #+END_SRC
1395
1396 ** TODO bookmark
1397
1398 ** TODO Calendar
1399 ** advice info
1400 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1401   (defun sd/info-mode ()
1402     (interactive)
1403     (unless (equal major-mode 'Info-mode)
1404       (unless (> (length (window-list)) 1)
1405         (split-window-right))
1406       (other-window 1)
1407       ;; (info)
1408       ))
1409
1410   ;; (global-set-key (kbd "C-h i") 'sd/info-mode)
1411
1412   ;; open Info buffer in other window instead of current window
1413   (defadvice info (before my-info (&optional file buf) activate)
1414     (sd/info-mode))
1415
1416   (defadvice Info-exit (after my-info-exit activate)
1417     (sd/delete-current-window))
1418 #+END_SRC
1419
1420 ** TODO Man mode
1421 Color for Man-mode
1422
1423 ** TODO swiper to occur
1424
1425 ** TODO UTF8
1426 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1427   ;; (set-language-environment "UTF-8")
1428   ;; (set-default-coding-systems 'utf-8)
1429 #+END_SRC
1430
1431 ** Demo It
1432 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1433   ;; (el-get-bundle howardabrams/demo-it)
1434
1435   (use-package org-tree-slide
1436     :ensure t)
1437
1438   ;; (use-package yasnippet
1439   ;;   :ensure t)
1440 #+END_SRC
1441
1442 ** Presentation
1443 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1444   (use-package org-tree-slide
1445     :ensure
1446     :config
1447     ;; (define-key org-mode-map "\C-ccp" 'org-tree-slide-mode)
1448     (define-key org-tree-slide-mode-map (kbd "<ESC>") 'org-tree-slide-content)
1449     (define-key org-tree-slide-mode-map (kbd "<SPACE>") 'org-tree-slide-move-next-tree)
1450     (define-key org-tree-slide-mode-map [escape] 'org-tree-slide-move-previous-tree))
1451 #+END_SRC
1452
1453 * dired
1454 =C-o= is defined as a global key for window operation, here unset it in dired mode
1455 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1456   (use-package dired
1457     :config
1458     (require 'dired-x)
1459     (setq dired-omit-mode t)
1460     (setq dired-omit-files (concat dired-omit-files "\\|^\\..+$"))
1461     (add-hook 'dired-mode-hook (lambda ()
1462                                  (define-key dired-mode-map (kbd "C-o") nil)
1463                                  (define-key dired-mode-map (kbd "H") 'dired-omit-mode)
1464                                  (define-key dired-mode-map (kbd "DEL") (lambda () (interactive) (find-alternate-file "..")))
1465                                  (dired-omit-mode))))
1466 #+END_SRC
1467
1468 Dired+
1469 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1470   (use-package dired+
1471     :ensure t
1472     :init
1473     (setq diredp-hide-details-initially-flag nil)
1474     :config
1475     (define-key dired-mode-map (kbd "j") 'diredp-next-line)
1476     (define-key dired-mode-map (kbd "k") 'diredp-previous-line)
1477     (define-key dired-mode-map (kbd "g") 'dired-goto-file))
1478 #+END_SRC
1479
1480 * Completion
1481 company mode and company-statistics
1482 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1483   (use-package company
1484     :ensure t
1485     :diminish company-mode
1486     :init (setq company-idle-delay 0.1)
1487     :config
1488     (global-company-mode))
1489
1490   (use-package company-statistics
1491     :ensure t
1492     :config
1493     (company-statistics-mode))
1494 #+END_SRC
1495
1496 * Programming Language
1497 ** Emacs Lisp
1498 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1499   (use-package color-identifiers-mode
1500     :ensure t
1501     :init
1502     (add-hook 'emacs-lisp-mode-hook 'color-identifiers-mode)
1503
1504     :diminish color-identifiers-mode)
1505
1506   (global-prettify-symbols-mode t)
1507 #+END_SRC
1508
1509 In Lisp Mode, =M-o= is defined, but I use this for global hydra window. So here disable this key
1510 bindings in =lispy-mode-map= after loaded. see [[http://stackoverflow.com/questions/298048/how-to-handle-conflicting-keybindings][here]]
1511 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1512   (use-package lispy
1513     :ensure t
1514     :init
1515     (eval-after-load "lispy"
1516       `(progn
1517          (define-key lispy-mode-map (kbd "M-o") nil)))
1518     :config
1519     (add-hook 'emacs-lisp-mode-hook (lambda () (lispy-mode 1))))
1520 #+END_SRC
1521
1522 ** Perl
1523 *** CPerl mode
1524 [[https://www.emacswiki.org/emacs/CPerlMode][CPerl mode]] has more features than =PerlMode= for perl programming. Alias this to =CPerlMode=
1525 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1526   (defalias 'perl-mode 'cperl-mode)
1527
1528   ;; (setq cperl-hairy t)
1529   ;; Turns on most of the CPerlMode options
1530   (setq cperl-auto-newline t)
1531   (setq cperl-highlight-variables-indiscriminately t)
1532   ;(setq cperl-indent-level 4)
1533   ;(setq cperl-continued-statement-offset 4)
1534   (setq cperl-close-paren-offset -4)
1535   (setq cperl-indent-parents-as-block t)
1536   (setq cperl-tab-always-indent t)
1537   ;(setq cperl-brace-offset  0)
1538
1539   (add-hook 'cperl-mode-hook
1540             '(lambda ()
1541                (cperl-set-style "C++")))
1542
1543   (defalias 'perldoc 'cperl-perldoc)
1544 #+END_SRC
1545
1546 *** Perl template
1547 Refer [[https://www.emacswiki.org/emacs/AutoInsertMode][AutoInsertMode]] Wiki
1548 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1549   (eval-after-load 'autoinsert
1550     '(define-auto-insert '("\\.pl\\'" . "Perl skeleton")
1551        '(
1552          "Empty"
1553          "#!/usr/bin/perl -w" \n
1554          \n
1555          "use strict;" >  \n \n
1556          > _
1557          )))
1558 #+END_SRC
1559
1560 *** Perl Keywords
1561 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1562   (font-lock-add-keywords 'cperl-mode
1563                           '(("\\(say\\)" . cperl-nonoverridable-face)
1564                             ("\\([0-9.]\\)*" . font-lock-constant-face)
1565                             ("\".*\\(\\\n\\).*\"" . font-lock-constant-face)
1566                             ("\n" . font-lock-constant-face)
1567                             ("\\(^#!.*\\)$" .  cperl-nonoverridable-face)))
1568
1569     ;; (font-lock-add-keywords 'Man-mode
1570     ;;                         '(("\\(NAME\\)" . font-lock-function-name-face)))
1571
1572 #+END_SRC
1573
1574 *** Run Perl
1575 Change the compile-command to set the default command run when call =compile=
1576 Mapping =s-r= (on Mac, it's =Command + R= to run the script. Here =current-prefix-arg= is set
1577 to call =compilation=  interactively.
1578 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1579   (defun my-perl-hook ()
1580     (progn
1581       (setq-local compilation-read-command nil)
1582       (set (make-local-variable 'compile-command)
1583            (concat "/usr/bin/perl "
1584                    (if buffer-file-name
1585                        (shell-quote-argument buffer-file-name))))
1586       (local-set-key (kbd "s-r")
1587                      (lambda ()
1588                        (interactive)
1589                                           ;                       (setq current-prefix-arg '(4)) ; C-u
1590                        (call-interactively 'compile)))))
1591
1592   (add-hook 'cperl-mode-hook 'my-perl-hook)
1593 #+END_SRC
1594
1595 ** C & C++
1596 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1597   (setq c-default-style "stroustrup"
1598         c-basic-offset 4)
1599 #+END_SRC
1600
1601 * Compile
1602 Set the environments vairables in compilation mode
1603 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1604   (use-package compile
1605     :commands compile
1606     :config
1607     (setq compilation-environment (cons "LC_ALL=C" compilation-environment))
1608     (setq compilation-auto-jump-to-first-error t)
1609     (setq compilation-auto-jump-to-next t)
1610     (setq compilation-scroll-output 'first-error))
1611
1612   ;; super-r to compile
1613   (with-eval-after-load "compile"
1614     (define-key compilation-mode-map (kbd "C-o") nil)
1615     (define-key compilation-mode-map (kbd "n") 'compilation-next-error)
1616     (define-key compilation-mode-map (kbd "p") 'compilation-previous-error)
1617     (define-key compilation-mode-map (kbd "r") #'recompile))
1618 #+END_SRC
1619
1620 * Auto-Insert
1621 ** Enable auto-insert mode
1622 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1623   (auto-insert-mode t)
1624   (setq auto-insert-query nil)
1625 #+END_SRC
1626
1627 ** C++ Auto Insert
1628 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1629   (eval-after-load 'autoinsert
1630     '(define-auto-insert '("\\.cpp\\'" . "C++ skeleton")
1631        '(
1632          "Short description:"
1633          "/*"
1634          "\n * " (file-name-nondirectory (buffer-file-name))
1635          "\n */" > \n \n
1636          "#include <iostream>" \n
1637          "#include \""
1638          (file-name-sans-extension
1639           (file-name-nondirectory (buffer-file-name)))
1640          ".hpp\"" \n \n
1641          "using namespace std;" \n \n
1642          "int main ()"
1643          "\n{" \n 
1644          > _ \n
1645          "return 1;"
1646          "\n}" > \n
1647          )))
1648
1649   (eval-after-load 'autoinsert
1650     '(define-auto-insert '("\\.c\\'" . "C skeleton")
1651        '(
1652          "Short description:"
1653          "/*\n"
1654          " * " (file-name-nondirectory (buffer-file-name)) "\n"
1655          " */" > \n \n
1656          "#include <stdio.h>" \n
1657          "#include \""
1658          (file-name-sans-extension
1659           (file-name-nondirectory (buffer-file-name)))
1660          ".h\"" \n \n
1661          "int main ()\n"
1662          "{" \n
1663          > _ \n
1664          "return 1;\n"
1665          "}" > \n
1666          )))
1667 #+END_SRC
1668
1669 ** Python template
1670 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1671   (eval-after-load 'autoinsert
1672     '(define-auto-insert '("\\.\\(py\\)\\'" . "Python skeleton")
1673        '(
1674          "Empty"
1675          "#import os,sys" \n
1676          \n \n
1677          )))
1678 #+END_SRC
1679
1680 ** Elisp 
1681 Emacs lisp auto-insert, based on the default module in =autoinsert.el=, but replace =completing-read= as 
1682 =completing-read-ido-ubiquitous= to fix the edge case of that =ido= cannot handle.
1683 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1684   (eval-after-load 'autoinsert
1685     '(define-auto-insert '("\\.el\\'" . "my Emacs Lisp header")
1686        '(
1687          "Short description: "
1688          ";;; " (file-name-nondirectory (buffer-file-name)) " --- " str
1689          (make-string (max 2 (- 80 (current-column) 27)) ?\s)
1690          "-*- lexical-binding: t; -*-" '(setq lexical-binding t)
1691          "\n
1692   ;; Copyright (C) " (format-time-string "%Y") "  "
1693          (getenv "ORGANIZATION") | (progn user-full-name) "
1694
1695   ;; Author: " (user-full-name)
1696          '(if (search-backward "&" (line-beginning-position) t)
1697               (replace-match (capitalize (user-login-name)) t t))
1698          '(end-of-line 1) " <" (progn user-mail-address) ">
1699   ;; Keywords: "
1700          '(require 'finder)
1701          ;;'(setq v1 (apply 'vector (mapcar 'car finder-known-keywords)))
1702          '(setq v1 (mapcar (lambda (x) (list (symbol-name (car x))))
1703                            finder-known-keywords)
1704                 v2 (mapconcat (lambda (x) (format "%12s:  %s" (car x) (cdr x)))
1705                               finder-known-keywords
1706                               "\n"))
1707          ((let ((minibuffer-help-form v2))
1708             (completing-read-ido-ubiquitous "Keyword, C-h: " v1 nil t))
1709           str ", ") & -2 "
1710
1711   \;; This program is free software; you can redistribute it and/or modify
1712   \;; it under the terms of the GNU General Public License as published by
1713   \;; the Free Software Foundation, either version 3 of the License, or
1714   \;; (at your option) any later version.
1715
1716   \;; This program is distributed in the hope that it will be useful,
1717   \;; but WITHOUT ANY WARRANTY; without even the implied warranty of
1718   \;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
1719   \;; GNU General Public License for more details.
1720
1721   \;; You should have received a copy of the GNU General Public License
1722   \;; along with this program.  If not, see <http://www.gnu.org/licenses/>.
1723
1724   \;;; Commentary:
1725
1726   \;; " _ "
1727
1728   \;;; Code:
1729
1730
1731   \(provide '"
1732          (file-name-base)
1733          ")
1734   \;;; " (file-name-nondirectory (buffer-file-name)) " ends here\n")))
1735 #+END_SRC
1736
1737 ** Org file template
1738 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1739   (eval-after-load 'autoinsert
1740     '(define-auto-insert '("\\.\\(org\\)\\'" . "Org-mode skeleton")
1741        '(
1742          "title: "
1743          "#+TITLE: " str (make-string 30 ?\s) > \n
1744          "#+AUTHOR: Peng Li\n"
1745          "#+EMAIL: seudut@gmail.com\n"
1746          "#+DATE: " (shell-command-to-string "echo -n $(date +%Y-%m-%d)") > \n
1747          > \n
1748          > _)))
1749 #+END_SRC
1750
1751 * Markdown mode
1752 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1753   (use-package markdown-mode
1754     :ensure t
1755     :commands (markdown-mode gfm-mode)
1756     :mode (("README\\.md\\'" . gfm-mode)
1757            ("\\.md\\'" . markdown-mode)
1758            ("\\.markdown\\'" . markdown-mode))
1759     :init (setq markdown-command "multimarkdown"))
1760 #+END_SRC
1761
1762 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1763   (use-package markdown-preview-eww
1764     :ensure t)
1765 #+END_SRC
1766
1767 * Gnus
1768 ** Gmail setting 
1769 Refer [[https://www.emacswiki.org/emacs/GnusGmail][GnusGmail]]
1770 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1771   (setq user-mail-address "seudut@gmail.com"
1772         user-full-name "Peng Li")
1773
1774   (setq gnus-select-method
1775         '(nnimap "gmail"
1776                  (nnimap-address "imap.gmail.com")
1777                  (nnimap-server-port "imaps")
1778                  (nnimap-stream ssl)))
1779
1780   (setq smtpmail-smtp-service 587
1781         gnus-ignored-newsgroups "^to\\.\\|^[0-9. ]+\\( \\|$\\)\\|^[\"]\"[#'()]")
1782
1783   ;; Use gmail sending mail
1784   (setq message-send-mail-function 'smtpmail-send-it
1785         smtpmail-starttls-credentials '(("smtp.gmail.com" 587 nil nil))
1786         smtpmail-auth-credentials '(("smtp.gmail.com" 587 "seudut@gmail.com" nil))
1787         smtpmail-default-smtp-server "smtp.gmail.com"
1788         smtpmail-smtp-server "smtp.gmail.com"
1789         smtpmail-smtp-service 587
1790         starttls-use-gnutls t)
1791 #+END_SRC
1792
1793 And put the following in =~/.authinfo= file, replacing =<USE>= with your email address
1794 and =<PASSWORD>= with the password
1795 #+BEGIN_EXAMPLE
1796   machine imap.gmail.com login <USER> password <PASSWORD> port imaps
1797   machine smtp.gmail.com login <USER> password <PASSWORD> port 587
1798 #+END_EXAMPLE
1799
1800 Then Run =M-x gnus=
1801
1802 ** Group buffer
1803 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1804   (use-package gnus
1805     :init
1806     (setq gnus-permanently-visible-groups "\.*")
1807     :config
1808     (cond (window-system
1809            (setq custom-background-mode 'light)
1810            (defface my-group-face-1
1811              '((t (:foreground "Red" :bold t))) "First group face")
1812            (defface my-group-face-2
1813              '((t (:foreground "DarkSeaGreen4" :bold t)))
1814              "Second group face")
1815            (defface my-group-face-3
1816              '((t (:foreground "Green4" :bold t))) "Third group face")
1817            (defface my-group-face-4
1818              '((t (:foreground "SteelBlue" :bold t))) "Fourth group face")
1819            (defface my-group-face-5
1820              '((t (:foreground "Blue" :bold t))) "Fifth group face")))
1821     (setq gnus-group-highlight
1822           '(((> unread 200) . my-group-face-1)
1823             ((and (< level 3) (zerop unread)) . my-group-face-2)
1824             ((< level 3) . my-group-face-3)
1825             ((zerop unread) . my-group-face-4)
1826             (t . my-group-face-5))))
1827
1828
1829   ;; key-
1830   (add-hook 'gnus-group-mode-hook (lambda ()
1831                                     (define-key gnus-group-mode-map "k" 'gnus-group-prev-group)
1832                                     (define-key gnus-group-mode-map "j" 'gnus-group-next-group)
1833                                     (define-key gnus-group-mode-map "g" 'gnus-group-jump-to-group)
1834                                     (define-key gnus-group-mode-map "v" (lambda () (interactive) (gnus-group-select-group t)))))
1835 #+END_SRC
1836
1837 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1838   (setq gnus-fetch-old-headers 't)
1839
1840
1841
1842   (setq gnus-extract-address-components
1843         'mail-extract-address-components)
1844   ;; summary buffer 
1845   (setq gnus-summary-line-format "%U%R%z%I%(%[%-20,20f%]%)  %s%-80=   %11&user-date;\n")
1846   (setq gnus-user-date-format-alist '(((gnus-seconds-today) . "%H:%M")
1847                                       ((+ 86400 (gnus-seconds-today)) . "%a %H:%M")
1848                                       (604800 . "%a, %b %-d")
1849                                       (15778476 . "%b %-d")
1850                                       (t . "%Y-%m-%d")))
1851
1852   (setq gnus-thread-sort-functions '((not gnus-thread-sort-by-number)))
1853   (setq gnus-unread-mark ?\.)
1854   (setq gnus-use-correct-string-widths t)
1855
1856   ;; thread
1857   (setq gnus-thread-hide-subtree t)
1858
1859   ;; (with-eval-after-load 'gnus-summary-mode
1860   ;;   (define-key gnus-summary-mode-map (kbd "C-o") 'sd/hydra-window/body))
1861
1862   (add-hook 'gnus-summary-mode-hook (lambda ()
1863                                       (define-key gnus-summary-mode-map (kbd "C-o") nil)))
1864
1865
1866 #+END_SRC
1867
1868 ** Windows layout
1869 See [[https://www.emacswiki.org/emacs/GnusWindowLayout][GnusWindowLayout]]
1870 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1871   (gnus-add-configuration
1872    '(summary
1873      (horizontal 1.0
1874                  (vertical 35
1875                            (group 1.0))
1876                  (vertical 1.0
1877                            (summary 1.0 poine)))))
1878
1879   (gnus-add-configuration
1880    '(article
1881      (horizontal 1.0
1882                  (vertical 35
1883                            (group 1.0))
1884                  (vertical 1.0
1885                            (summary 0.50 point)
1886                            (article 1.0)))))
1887
1888   (with-eval-after-load 'gnus-group-mode
1889     (gnus-group-select-group "INBOX"))
1890   ;; (add-hook 'gnus-group-mode-map (lambda ()
1891   ;;                               (gnus-group-select-group "INBOX")))
1892 #+END_SRC
1893
1894 * Gnu Plot
1895 To fix some issue that =toolbar-make-button-list= is void, see the [[https://github.com/bruceravel/gnuplot-mode/issues/31][issue]], here I set some variable as =nil=
1896 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1897   (use-package gnuplot
1898     :ensure
1899     :init
1900     (setq gnuplot-help-xpm nil)
1901     (setq gnuplot-line-xpm nil)
1902     (setq gnuplot-region-xpm nil)
1903     (setq gnuplot-buffer-xpm nil)
1904     (setq gnuplot-doc-xpm nil))
1905 #+END_SRC
1906
1907 Use =gnuplot= on =Org-mode= file, see [[http://orgmode.org/worg/org-contrib/babel/languages/ob-doc-gnuplot.html][ob-doc-gnuplot]]
1908 #+BEGIN_SRC gnuplot :exports code :file ./temp/file.png
1909   reset
1910
1911   set title "Putting it All Together"
1912
1913   set xlabel "X"
1914   set xrange [-8:8]
1915   set xtics -8,2,8
1916
1917
1918   set ylabel "Y"
1919   set yrange [-20:70]
1920   set ytics -20,10,70
1921
1922   f(x) = x**2
1923   g(x) = x**3
1924   h(x) = 10*sqrt(abs(x))
1925
1926   plot f(x) w lp lw 1, g(x) w p lw 2, h(x) w l lw 3
1927 #+END_SRC
1928
1929 #+RESULTS:
1930 [[file:./temp/file.png]]
1931 * Ediff
1932 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1933   (with-eval-after-load 'ediff
1934     (setq ediff-split-window-function 'split-window-horizontally)
1935     (setq ediff-window-setup-function 'ediff-setup-windows-plain)
1936     (add-hook 'ediff-startup-hook 'ediff-toggle-wide-display)
1937     (add-hook 'ediff-cleanup-hook 'ediff-toggle-wide-display)
1938     (add-hook 'ediff-suspend-hook 'ediff-toggle-wide-display))
1939 #+END_SRC
1940
1941 * Dictionary
1942 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1943   (use-package bing-dict
1944     :ensure t
1945     :init
1946     (global-set-key (kbd "s-d") 'bing-dict-brief)
1947     :commands (bing-dict-brief))
1948 #+END_SRC
1949
1950 * NEXT Key Bindings
1951 Here are some global key bindings for basic editting
1952 ** Esc in minibuffer
1953 Use =ESC= to exit minibuffer. Also I map =Super-h= the same as =C-g=
1954 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1955   (define-key minibuffer-local-map [escape] 'keyboard-escape-quit)
1956   (define-key minibuffer-local-map [escape]  'keyboard-escape-quit)
1957   (define-key minibuffer-local-ns-map [escape]  'keyboard-escape-quit)
1958   (define-key minibuffer-local-isearch-map [escape]  'keyboard-escape-quit)
1959   (define-key minibuffer-local-completion-map [escape]  'keyboard-escape-quit)
1960   (define-key minibuffer-local-must-match-map [escape]  'keyboard-escape-quit)
1961   (define-key minibuffer-local-must-match-filename-map [escape]  'keyboard-escape-quit)
1962   (define-key minibuffer-local-filename-completion-map [escape]  'keyboard-escape-quit)
1963   (define-key minibuffer-local-filename-must-match-map [escape]  'keyboard-escape-quit)
1964
1965   ;; Also map s-h same as C-g
1966   (define-key minibuffer-local-map (kbd "s-h") 'keyboard-escape-quit)
1967 #+END_SRC
1968
1969 ** Project operations - =super=
1970 *** Projectile
1971 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1972   (use-package projectile
1973     :ensure t
1974     :init
1975     (setq projectile-enable-caching t)
1976     (setq projectile-cache-file (concat sd-temp-directory "projectile.cache"))
1977     :config
1978     (projectile-global-mode t))
1979
1980   (use-package persp-projectile
1981     :ensure t
1982     :config
1983     (persp-mode)
1984     :bind
1985     (:map projectile-mode-map
1986           ("s-t" . projectile-persp-switch-project)))
1987
1988   ;; projectile-find-file
1989   ;; projectile-switch-buffer
1990   ;; projectile-find-file-other-window
1991 #+END_SRC
1992
1993 *** project config =super= keybindings
1994 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
1995   ;; (global-set-key (kbd "s-h") 'keyboard-quit)
1996   ;; (global-set-key (kbd "s-j") 'ido-switch-buffer)
1997   ;; (global-set-key (kbd "s-k") 'ido-find-file)
1998   ;; (global-set-key (kbd "s-l") 'sd/delete-current-window)
1999   ;; s-l  -->  goto-line
2000   ;; (global-set-key (kbd "s-/") 'swiper)
2001   ;; s-;  -->
2002   ;; s-'  -->  'next-multiframe-window
2003   (global-set-key (kbd "<s-return>") 'toggle-frame-fullscreen)
2004
2005   (global-set-key (kbd "s-f") 'projectile-find-file)
2006   (global-set-key (kbd "s-`") 'mode-line-other-buffer)
2007
2008   (global-set-key (kbd "s-n") 'persp-next)
2009   (global-set-key (kbd "s-p") 'persp-prev)
2010
2011   (global-set-key (kbd "s-=") 'text-scale-increase)
2012   (global-set-key (kbd "s--") 'text-scale-decrease)
2013
2014   ;; (global-set-key (kbd "s-u") 'undo-tree-visualize)
2015
2016
2017   ;; someothers default mapping on super (command) key
2018   ;; s-s save-buffer
2019   ;; s-k kill-this-buffer
2020
2021
2022   ;; s-h  -->  ns-do-hide-emacs
2023   ;; s-j  -->  ido-switch-buffer  +
2024   ;; s-k  -->  kill-this-buffer
2025   ;; s-l  -->  goto-line
2026   ;; s-;  -->  undefined
2027   ;; s-'  -->  next-multiframe-window
2028   ;; s-ret --> toggle-frame-fullscreen +
2029
2030   ;; s-y  -->  ns-paste-secondary
2031   ;; s-u  -->  revert-buffer
2032   ;; s-i  -->  undefined - but used for iterm globally
2033   ;; s-o  -->  used for emacs globally
2034   ;; s-p  -->  projectile-persp-switch-project  +  
2035   ;; s-[  -->  next-buffer  +    
2036   ;; s-]  -->  previous-buffer +
2037
2038   ;; s-0  -->  undefined
2039   ;; s-9  -->  undefined
2040   ;; s-8  -->  undefined
2041   ;; s-7  -->  undefined
2042   ;; s-6  -->  undefined
2043   ;; s--  -->  center-line
2044   ;; s-=  -->  undefined
2045
2046   ;; s-n  -->  make-frame
2047   ;; s-m  -->  iconify-frame
2048   ;; s-b  -->  undefined
2049   ;; s-,  -->  customize
2050   ;; s-.  -->  undefined
2051   ;; s-/  -->  undefined
2052
2053   ;; s-g  -->  isearch-repeat-forward
2054   ;; s-f  -->  projectile-find-file   +
2055   ;; s-d  -->  isearch-repeat-background
2056   ;; s-s  -->  save-buffer
2057   ;; s-a  -->  make-whole-buffer
2058
2059   ;; s-b  -->  undefined
2060   ;; s-v  -->  yank
2061   ;; s-c  -->  ns-copy-including-secondary
2062
2063   ;; s-t  -->  ns-popup-font-panel
2064   ;; s-r  -->  undefined
2065   ;; s-e  -->  isearch-yanqk-kill
2066   ;; s-w  -->  delete-frame
2067   ;; s-q  -->  same-buffers-kill-emacs
2068
2069   ;; s-`  -->  other-frame
2070 #+END_SRC
2071
2072 ** Windown & Buffer - =C-o=
2073 Defind a =hydra= function for windows, buffer & bookmark operations. And map it to =C-o= globally.
2074 Most use =C-o C-o= to switch buffers; =C-o x, v= to split window; =C-o o= to delete other windows
2075 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2076   (winner-mode 1)
2077
2078   (defun sd/delete-current-window ()
2079     (interactive)
2080     (if (> (length (window-list)) 1)
2081         (delete-window)
2082       (message "Only one Windows now!")))
2083
2084   (defun sd/toggle-max-windows ()
2085     "Set maximize current if there are multiple windows, if only
2086   one window, window undo"
2087     (interactive)
2088     (if (equal  (length (window-list)) 1)
2089         (winner-undo)
2090       (delete-other-windows)))
2091
2092   (defhydra sd/hydra-window (:color red :columns nil)
2093     "window"
2094     ("h" windmove-left nil :exit t)
2095     ("j" windmove-down nil :exit t)
2096     ("k" windmove-up nil :exit t)
2097     ("l" windmove-right nil :exit t)
2098     ("H" hydra-move-splitter-left nil)
2099     ("J" hydra-move-splitter-down nil)
2100     ("K" hydra-move-splitter-up nil)
2101     ("L" hydra-move-splitter-right nil)
2102     ("v" (lambda ()
2103            (interactive)
2104            (split-window-right)
2105            (windmove-right))
2106      "vert" :exit t)
2107     ("x" (lambda ()
2108            (interactive)
2109            (split-window-below)
2110            (windmove-down))
2111      "horz" :exit t)
2112     ;; ("o" delete-other-windows "one" :exit t)
2113     ("o" sd/toggle-max-windows "one" :exit t)
2114     ("C-o" ido-switch-buffer "buf" :exit t)
2115     ("C-k" sd/delete-current-window "del" :exit t)
2116     ("'" other-window "other" :exit t)
2117     ("a" ace-window "ace")
2118     ("s" ace-swap-window "swap")
2119     ("d" ace-delete-window "ace-one" :exit t)
2120     ("i" ace-maximize-window "ace-one" :exit t)
2121     ("b" ido-switch-buffer "buf" :exit t)
2122     ("C-b" ido-switch-buffer "buf" :exit t)
2123     ("m" bookmark-jump-other-window "open bmk" :exit t)
2124     ("M" bookmark-set "set bmk" :exit t)
2125     ("u" (progn (winner-undo) (setq this-command 'winner-undo)) "undo")
2126     ("r" (progn (winner-redo) (setq this-command 'winner-redo)) "redo")
2127     ("q" nil "cancel")
2128     ("<ESC>" nil)
2129     ("C-h" nil nil :exit t)
2130     ("C-j" nil nil :exit t)
2131     ;; ("C-k" nil :exit t)
2132     ("C-l" nil nil :exit t)
2133     ("C-;" nil nil :exit t)
2134     ("p" nil nil :exit t)
2135     ("n" nil nil :exit t)
2136     ("[" nil nil :exit t)
2137     ("]" nil nil :exit t)
2138     ("f" nil))
2139
2140   (global-unset-key (kbd "C-o"))
2141   (global-set-key (kbd "C-o") 'sd/hydra-window/body)
2142 #+END_SRC
2143
2144 ** Motion
2145 - =C-M-=
2146 [[https://www.masteringemacs.org/article/effective-editing-movement][effective-editing-movement]]
2147 *** Command Arguments, numeric argumens
2148 =C-u 4= same as =C-4=, =M-4=
2149 *** Basic movement
2150 moving by line / word / 
2151 =C-f=, =C-b=, =C-p=, =C-n=, =M-f=, =M-b=
2152 =C-a=, =C-e=
2153 =M-m= (move first non-whitespace on this line) 
2154 =M-}=, =M-{=, Move forward end of paragraph
2155 =M-a=, =M-e=,  beginning / end of sentence
2156 =C-M-a=, =C-M-e=, move begining of defun
2157 =C-x ]=, =C-x [=, forward/backward one page
2158 =C-v=, =M-v=, =C-M-v=, =C-M-S-v= scroll down/up
2159 =M-<=, =M->=, beginning/end of buffer
2160 =M-r=, Repositiong point
2161
2162 *** Moving by S-expression / List
2163 *** Marks
2164 =C-<SPC>= set marks toggle the region
2165 =C-u C-<SPC>= Jump to the mark, repeated calls go further back the mark ring
2166 =C-x C-x= Exchanges the point and mark.
2167
2168 Stolen [[https://www.masteringemacs.org/article/fixing-mark-commands-transient-mark-mode][fixing-mark-commands-transient-mark-mode]]
2169 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2170   (defun push-mark-no-activate ()
2171     "Pushes `point' to `mark-ring' and does not activate the region
2172      Equivalent to \\[set-mark-command] when \\[transient-mark-mode] is disabled"
2173     (interactive)
2174     (push-mark (point) t nil)
2175     (message "Pushed mark to ring"))
2176
2177   ;; (global-set-key (kbd "C-`") 'push-mark-no-activate)
2178
2179   (defun jump-to-mark ()
2180     "Jumps to the local mark, respecting the `mark-ring' order.
2181     This is the same as using \\[set-mark-command] with the prefix argument."
2182     (interactive)
2183     (set-mark-command 1))
2184
2185   ;; (global-set-key (kbd "M-`") 'jump-to-mark)
2186
2187   (defun exchange-point-and-mark-no-activate ()
2188     "Identical to \\[exchange-point-and-mark] but will not activate the region."
2189     (interactive)
2190     (exchange-point-and-mark)
2191     (deactivate-mark nil))
2192
2193   ;; (define-key global-map [remap exchange-point-and-mark] 'exchange-point-and-mark-no-activate)
2194 #+END_SRC
2195
2196 Show the mark ring using =helm-mark-ring=, also mapping =M-`= to quit minibuffer. so that =M-`= can 
2197 toggle the mark ring. the best way is add a new action and mapping to =helm-source-mark-ring=,  but 
2198 since there is no map such as =helm-mark-ring=map=, so I cannot binding a key to the quit action.
2199 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2200   (setq mark-ring-max 50)
2201   (global-set-key (kbd "M-`") #'helm-mark-ring)
2202
2203   (define-key minibuffer-local-map (kbd "M-`") 'keyboard-escape-quit)
2204 #+END_SRC
2205
2206 =M-h= marks the next paragraph
2207 =C-x h= marks the whole buffer
2208 =C-M-h= marks the next defun
2209 =C-x C-p= marks the next page
2210 **** DONE Mapping toggle mark ring=
2211 :LOGBOOK:
2212 - State "DONE"       from "TODO"       [2016-07-22 Fri 23:18]
2213 :END:
2214 *** Registers
2215 Registers can save text, position, rectangles, file and configuration and other things.
2216 Here for movement, we can use register to save/jump position
2217 =C-x r SPC= store point in register
2218 =C-x r j= jump to register
2219 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2220   (use-package list-register
2221     :ensure t)
2222 #+END_SRC
2223
2224 *** Bookmarks
2225 As I would like use bookmakr for different buffer/files. to help to swith
2226 different buffer/file quickly. this setting is in Windows/buffer node
2227 =C-x r m= set a bookmarks
2228 =C-x r l= list bookmarks
2229 =C-x r b= jump to bookmarks
2230
2231 *** Search
2232 Search, replace and hightlight will in later paragraph
2233 *** =Avy= for easy motion
2234 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2235   (use-package avy
2236     :ensure t
2237     :config
2238     (avy-setup-default))
2239
2240   (global-set-key (kbd "C-M-j") 'avy-goto-line-below)
2241   (global-set-key (kbd "C-M-n") 'avy-goto-line-below)
2242   (global-set-key (kbd "C-M-k") 'avy-goto-line-above)
2243   (global-set-key (kbd "C-M-p") 'avy-goto-line-above)
2244
2245   (global-set-key (kbd "C-M-f") 'avy-goto-word-1-below)
2246   (global-set-key (kbd "C-M-b") 'avy-goto-word-1-above)
2247
2248   ;; (global-set-key (kbd "M-g e") 'avy-goto-word-0)
2249   (global-set-key (kbd "C-M-w") 'avy-goto-char-timer)
2250   (global-set-key (kbd "C-M-l") 'avy-goto-char-in-line)
2251
2252   ;; ;; will delete above 
2253   ;; (global-set-key (kbd "M-g j") 'avy-goto-line-below)
2254   ;; (global-set-key (kbd "M-g k") 'avy-goto-line-above)
2255   ;; (global-set-key (kbd "M-g w") 'avy-goto-word-1-below)
2256   ;; (global-set-key (kbd "M-g b") 'avy-goto-word-1-above)
2257   ;; (global-set-key (kbd "M-g e") 'avy-goto-word-0)
2258   ;; (global-set-key (kbd "M-g f") 'avy-goto-char-timer)
2259   ;; (global-set-key (kbd "M-g c") 'avy-goto-char-in-line)
2260 #+END_SRC
2261
2262 *** =Imenu= goto tag
2263 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2264   ;; (global-set-key (kbd "M-i") #'counsel-imenu)
2265   (global-set-key (kbd "M-i") #'imenu)
2266
2267   ;; (global-set-key (kbd "M-l") 'goto-line)
2268 #+END_SRC
2269
2270 *** Go-to line
2271 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2272   (global-set-key (kbd "M-l") 'goto-line)
2273 #+END_SRC
2274
2275 ** Edit
2276 *** basic editting
2277 - cut, yank, =C-w=, =C-y=
2278 - save, revert
2279 - undo, redo - undo-tree
2280 - select, expand-region
2281 - spell check, flyspell
2282
2283 *** Kill ring
2284 =helm-show-kill-ring=
2285 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2286   (setq kill-ring-max 100)                ; default is 60p
2287   (global-set-key (kbd "M-y") #'helm-show-kill-ring)
2288 #+END_SRC
2289
2290 *** Expand-region
2291 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2292   (use-package expand-region
2293     :ensure t
2294     :config
2295     (global-set-key (kbd "C-=") 'er/expand-region))
2296 #+END_SRC
2297
2298 *** undo-tree
2299 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2300   (use-package undo-tree
2301     :ensure t
2302     :config
2303     (define-key undo-tree-visualizer-mode-map "j" 'undo-tree-visualize-redo)
2304     (define-key undo-tree-visualizer-mode-map "k" 'undo-tree-visualize-undo)
2305     (define-key undo-tree-visualizer-mode-map "h" 'undo-tree-visualize-switch-branch-left)
2306     (define-key undo-tree-visualizer-mode-map "l" 'undo-tree-visualize-switch-branch-right)
2307     (global-undo-tree-mode 1))
2308
2309   (global-set-key (kbd "s-u") 'undo-tree-visualize)
2310 #+END_SRC
2311
2312 *** flyspell
2313 Stolen from [[https://github.com/redguardtoo/emacs.d/blob/master/lisp/init-spelling.el][here]], hunspell will search dictionary in =DICPATH=
2314 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2315   (setenv "DICPATH" "/usr/local/share/hunspell")
2316
2317   (when (executable-find "hunspell")
2318     (setq-default ispell-program-name "hunspell")
2319     (setq ispell-really-hunspell t))
2320
2321   ;; (defun text-mode-hook-setup ()
2322   ;;   ;; Turn off RUN-TOGETHER option when spell check text-mode
2323   ;;   (setq-local ispell-extra-args (flyspell-detect-ispell-args)))
2324   ;; (add-hook 'text-mode-hook 'text-mode-hook-setup)
2325   ;; (add-hook 'text-mode-hook 'flyspell-mode)
2326
2327   ;; enable flyspell check on comments and strings in progmamming modes
2328   ;; (add-hook 'prog-mode-hook 'flyspell-prog-mode)
2329
2330   ;; I don't use the default mappings
2331   (with-eval-after-load 'flyspell
2332     (define-key flyspell-mode-map (kbd "C-;") nil)
2333     (define-key flyspell-mode-map (kbd "C-,") nil)
2334     (define-key flyspell-mode-map (kbd "C-.") nil))
2335 #+END_SRC
2336
2337 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]]
2338 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2339   ;; NO spell check for embedded snippets
2340   (defadvice org-mode-flyspell-verify (after org-mode-flyspell-verify-hack activate)
2341     (let ((rlt ad-return-value)
2342           (begin-regexp "^[ \t]*#\\+begin_\\(src\\|html\\|latex\\)")
2343           (end-regexp "^[ \t]*#\\+end_\\(src\\|html\\|latex\\)")
2344           old-flag
2345           b e)
2346       (when ad-return-value
2347         (save-excursion
2348           (setq old-flag case-fold-search)
2349           (setq case-fold-search t)
2350           (setq b (re-search-backward begin-regexp nil t))
2351           (if b (setq e (re-search-forward end-regexp nil t)))
2352           (setq case-fold-search old-flag))
2353         (if (and b e (< (point) e)) (setq rlt nil)))
2354       (setq ad-return-value rlt)))
2355 #+END_SRC
2356
2357 ** Search & Replace / hightlight =M-s=
2358 *** isearch
2359 =C-s=, =C-r=, 
2360 =C-w= add word at point to search string, 
2361 =M-%= query replace
2362 =C-M-y= add character at point to search string
2363 =M-s C-e= add reset of line at point
2364 =C-y= yank from clipboard to search string
2365 =M-n=, =M-p=, history
2366 =C-M-i= complete search string
2367 set the isearch history size, the default is only =16=
2368 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2369   (setq history-length 5000)
2370   (setq regexp-search-ring-max 1000)
2371   (setq search-ring-max 1000)
2372
2373   (defadvice isearch-update-ring (after sd/isearch-update-ring (string &optional regexp) activate)
2374     "Add search-ring to regexp-search-ring"
2375     (unless regexp
2376       (add-to-history 'regexp-search-ring string regexp-search-ring-max)))
2377
2378   ;; (defun isearch-update-ring (string &optional regexp)
2379   ;;   "Add STRING to the beginning of the search ring.
2380   ;; REGEXP if non-nil says use the regexp search ring."
2381   ;;   (add-to-history
2382   ;;    (if regexp 'regexp-search-ring 'search-ring)
2383   ;;    string
2384   ;;    (if regexp regexp-search-ring-max search-ring-max)))
2385 #+END_SRC
2386
2387 *** =M-s= prefix
2388 use the prefix =M-s= for searching in buffers
2389 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2390   (defun sd/make-keymap (key bindings)
2391     (setq keymap (make-sparse-keymap))
2392     (dolist (binding bindings)
2393       (define-key keymap (car binding) (cdr binding)))
2394     (global-set-key key keymap))
2395
2396   ;; (sd/make-keymap "\M-s"
2397   ;;                 '(("w" . save-buffer)
2398   ;;                   ;; ("\M-w" . save-buffer)
2399   ;;                   ("e" . revert-buffer)
2400   ;;                   ("s" . isearch-forward-regexp)
2401   ;;                   ("\M-s" . isearch-forward-regexp)
2402   ;;                   ("r" . isearch-backward-regexp)
2403   ;;                   ("." . isearch-forward-symbol-at-point)
2404   ;;                   ("o" . occur)
2405   ;;                   ;; ("h" . highlight-symbol-at-point)
2406   ;;                   ("h" . highlight-symbol)
2407   ;;                   ("m" . highlight-regexp)
2408   ;;                   ("l" . highlight-lines-matching-regexp)
2409   ;;                   ("M" . unhighlight-regexp)
2410   ;;                   ("f" . keyboard-quit)
2411   ;;                   ("q" . keyboard-quit)))
2412 #+END_SRC
2413
2414 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2415   (use-package highlight-symbol
2416     :ensure t)
2417
2418   (defhydra sd/search-replace (:color red :columns nil)
2419     "Search"
2420     ("w" save-buffer "save" :exit t)
2421     ("e" revert-buffer "revert" :exit t)
2422     ("u" undo-tree-visualize "undo" :exit t)
2423     ("s" isearch-forward-regexp "s-search" :exit t)
2424     ("M-s" isearch-forward-regexp "s-search" :exit t)
2425     ("r" isearch-backward-regexp "r-search" :exit t)
2426     ("." isearch-forward-symbol-at-point "search point" :exit t)
2427     ("/" swiper "swiper" :exit t)
2428     ("o" occur "occur" :exit t)
2429     ("h" highlight-symbol "higlight" :exit t)
2430     ("l" highlight-lines-matching-regexp "higlight line" :exit t)
2431     ("m" highlight-regexp "higlight" :exit t)
2432     ("M" unhighlight-regexp "unhiglight" :exit t)
2433     ("q" nil "quit")
2434     ("f" nil))
2435
2436   (global-unset-key (kbd "M-s"))
2437   (global-set-key (kbd "M-s") 'sd/search-replace/body)
2438
2439
2440   ;; search and replace and highlight
2441   (define-key isearch-mode-map (kbd "M-s") 'isearch-repeat-forward)
2442   (define-key isearch-mode-map (kbd "M-r") 'isearch-repeat-backward)
2443   (global-set-key (kbd "s-[") 'highlight-symbol-next)
2444   (global-set-key (kbd "s-]") 'highlight-symbol-prev)
2445   (global-set-key (kbd "s-\\") 'highlight-symbol-query-replace)
2446 #+END_SRC
2447
2448 *** replace
2449 *** hightlight
2450 *** Occur
2451 Occur search key bindings
2452 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2453   (defun sd/occur-keys ()
2454     "My key bindings in occur-mode"
2455     (interactive)
2456     (switch-to-buffer-other-window "*Occur*")
2457     (define-key occur-mode-map (kbd "C-o") nil)
2458     (define-key occur-mode-map (kbd "C-n") (lambda ()
2459                                              (interactive)
2460                                              (occur-next)
2461                                              (occur-mode-goto-occurrence-other-window)
2462                                              (recenter)
2463                                              (other-window 1)))
2464     (define-key occur-mode-map (kbd "C-p") (lambda ()
2465                                              (interactive)
2466                                              (occur-prev)
2467                                              (occur-mode-goto-occurrence-other-window)
2468                                              (recenter)
2469                                              (other-window 1))))
2470
2471   (add-hook 'occur-hook #'sd/occur-keys)
2472
2473   (use-package color-moccur
2474     :ensure t
2475     :commands (isearch-moccur isearch-all)
2476     :init
2477     (setq isearch-lazy-highlight t)
2478     :config
2479     (use-package moccur-edit))
2480 #+END_SRC
2481
2482 *** Swiper
2483 stolen from [[https://github.com/mariolong/emacs.d/blob/f6a061594ef1b5d1f4750e9dad9dc97d6e122840/emacs-init.org][here]]
2484 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2485   (use-package swiper
2486     :ensure t
2487     :init
2488     (setq ivy-use-virtual-buffers t)
2489     (set-face-attribute 'ivy-current-match nil :background "Orange" :foreground "black")
2490     :config
2491     (ivy-mode)
2492     (global-set-key (kbd "s-/") 'swiper)
2493     (define-key swiper-map (kbd "M-r") 'swiper-query-replace)
2494     (define-key swiper-map (kbd "C-.") (lambda ()
2495                                          (interactive)
2496                                          (insert (format "%s" (with-ivy-window (thing-at-point 'word))))))
2497     (define-key swiper-map (kbd "M-.") (lambda ()
2498                                          (interactive)
2499                                          (insert (format "%s" (with-ivy-window (thing-at-point 'symbol)))))))
2500 #+END_SRC
2501
2502 * TODO Convert ASCII to key
2503 ** map =function-key-map= [[http://academic.evergreen.edu/projects/biophysics/technotes/program/ascii_ctrl.htm][ascii_ctrl]]
2504 new file =C-x C-f C-f=
2505
2506 ** write color syntax for =Man-mode=
2507
2508 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2509   (font-lock-add-keywords 'perl-mode '(("\\(|\\w+?\\(,\\w+?\\)?|\\)" 1 'py-builtins-face)))
2510 #+END_SRC
2511
2512 * TODO jump last change point
2513 * TODO emms mode-line
2514
2515 * TODO Temp directory for cached/history/temp files
2516 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2517   (use-package recentf
2518     :init
2519     (setq recentf-save-file (concat sd-temp-directory "recentf")))
2520
2521   (setq auto-save-list-file-prefix (concat sd-temp-directory "auto-save-list/.saves-")) 
2522
2523 #+END_SRC
2524
2525 * =C-u C-h a= search funtions 
2526 =apropos-command= 
2527
2528 * TODO Questions
2529 - interactive for anonymous function
2530 When define a key to a anonymous function, the lambda function should be interactive
2531
2532 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2533   ;; (require 'saveplace)
2534   ;; (setq-default save-place t)
2535   ;; (delete-selection-mode 1)
2536 #+END_SRC
2537
2538 * key
2539 - passion
2540 - vision
2541 - mission
2542
2543
2544 * M prefix
2545 #+BEGIN_SRC emacs-lisp :tangle yes :results silent
2546
2547   ;; M-h - mark-paragraph
2548   ;; M-j - new line indent
2549   ;; M-k - kill-sentence
2550   ;; M-l - downcase words     ====== goto-line
2551   ;; M-; - comments
2552   ;; M-'- abbrev-prefix-mark  =======
2553   ;; M-RET none                ======
2554
2555   ;; M-y - yank
2556   ;; M-u - upcase word
2557   ;; M-i -                 ====== imenu
2558   ;; M-o             ====== prefix
2559   ;; M-p
2560   ;; M-[                   =====
2561   ;; M-]              ========
2562   ;; M-\   deleter horizontal space =====
2563
2564   ;; M-n 
2565   ;; M-m ---- indent
2566   ;; M-, --- mark stack====== =
2567   ;; M-. lisp-goto-symboo, find definitation
2568
2569   ;; M-a 
2570   ;; M-s ===== 
2571   ;; M-d
2572   ;; M-f
2573   ;; M-g - prefix
2574
2575   ;; M-q - lisp fill, fill paragraph
2576   ;; M-w 
2577   ;; M-e
2578   ;; M-r  - rePositioning 
2579   ;; M-t transpose word 
2580
2581   ;; M-z zap-to-char
2582   ;; M-x
2583   ;; M-c  capitalize-word
2584   ;; M-v 
2585   ;; M-b 
2586 #+END_SRC
2587
2588 * TODO ibuffer hydra
2589 * TODO expand region action, selected mode map