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