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