Skip to content

Instantly share code, notes, and snippets.

@bravosierrasierra
Created October 28, 2017 17:04
Show Gist options
  • Save bravosierrasierra/910ea01fe6e084c9ed24c7cb834d3628 to your computer and use it in GitHub Desktop.
Save bravosierrasierra/910ea01fe6e084c9ed24c7cb834d3628 to your computer and use it in GitHub Desktop.

как подключить этот файл к Emacs

Поместить в ~/.emacs:

;; initial setup with dropbox ;; M-g c <POSITION>

;; (toggle-debug-on-error) ;; ~/emacs.d/emacs.org

;;---------------------------------------------------------------------------- ;; Temporarily reduce garbage collection during startup ;; https://github.com/purcell/emacs.d/blob/master/init.el ;;---------------------------------------------------------------------------- (defconst sanityinc/initial-gc-cons-threshold gc-cons-threshold “Initial value of `gc-cons-threshold’ at start-up time.”) (setq gc-cons-threshold (* 128 1024 1024)) (add-hook ‘after-init-hook (lambda () (setq gc-cons-threshold sanityinc/initial-gc-cons-threshold)))

(setq package-enable-at-startup nil package-archives ‘((“org” . “http://orgmode.org/elpa/”) (“melpa” . “http://melpa.org/packages/”) (“gnu” . “http://elpa.gnu.org/packages/”) ;; (“elpy” . “https://jorgenschaefer.github.io/packages/”) ;; (“marmalade” . “http://marmalade-repo.org/packages/”) ; ))

(package-initialize)

(when (not package-archive-contents) (package-refresh-contents)) (unless (package-installed-p ‘use-package) (package-install ‘use-package)) (eval-when-compile (require ‘use-package)) (require ‘bind-key) ;; if you use any :bind variant (setq use-package-always-ensure t) ;; autoinstall missing packages (setq use-package-verbose t) ;;(use-package auto-compile ;; :config (auto-compile-on-load-mode)) ;;(setq load-prefer-newer t)

(add-to-list ‘load-path “~/.emacs.d/manual-addons”)

;; --------------- Babel init --------------- ;; (require ‘org) (use-package org-plus-contrib) (when (string-match “^[1234567]” (org-version)) (warn “Org-Mode is out of date. We expect org 8 or higher, but instead we have %s” (org-version)))

(org-babel-load-file “~/.emacs.d/emacs.org”) ;; ------------------------------------------

;; (setq custom-file “~/.emacs.d/_emacs-custom.el”) ;; (add-to-list ‘load-path “~/emacs.d”) ;; (load-file custom-file)

(custom-set-variables ;; custom-set-variables was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won’t work right. ‘(ansi-color-faces-vector [default bold shadow italic underline bold bold-italic bold]) ‘(ansi-color-names-vector [“#272822” “#F92672” “#A6E22E” “#E6DB74” “#66D9EF” “#FD5FF0” “#A1EFE4” “#F8F8F2”]) ‘(bmkp-last-as-first-bookmark-file “~/.emacs.d/.emacs.bmk”) ‘(column-number-mode t) ‘(compilation-message-face (quote default)) ‘(cua-global-mark-cursor-color “#2aa198”) ‘(cua-normal-cursor-color “#839496”) ‘(cua-overwrite-cursor-color “#b58900”) ‘(cua-read-only-cursor-color “#859900”) ‘(custom-enabled-themes (quote (wheatgrass))) ‘(custom-safe-themes (quote (“c4156b408e636a1286e0e8ed9531b4767dc2c8aa225d2012959e2a8610272cdc” “6184465774e662dc5f3ddb0751b20d97aaff2ae95d5cf3c885b6c1944ddcb371” “ad97202c92f426a867e83060801938acf035921d5d7e78da3041a999082fb565” “8288b9b453cdd2398339a9fd0cec94105bc5ca79b86695bd7bf0381b1fbe8147” “628278136f88aa1a151bb2d6c8a86bf2b7631fbea5f0f76cba2a0079cd910f7d” “bb08c73af94ee74453c90422485b29e5643b73b05e8de029a6909af6a3fb3f58” “6c189cbe61f4c909769c5e139f5a517b10bad3d478cc95067146f1e029470d0a” “234976f82b2d64c6d2da3bca061d9f09b46e1496f02451fe02a4c707fab32321” “500e239194d4362a579ba5ef4d552aa45304db855572984af447dff261b04c35” “86847534b000a2e7f2b77c24faf3a94283329073bd4687807a4b6a52cae752dd” “0646e3c982ea2169704bb8fe12cb372cf4711156b3b69967353ed7d40a1044b9” “4ab89cc4c58408bb799084a4d9be77fe0700b2f1b75809eae330129b4b921b6f” “307e7ade9a12d6c91fc0871c28708f49f1558aac8ba8639e43cfc03e80b44079” “5e3fc08bcadce4c6785fc49be686a4a82a356db569f55d411258984e952f194a” “8d6fb24169d94df45422617a1dfabf15ca42a97d594d28b3584dc6db711e0e0b” “7153b82e50b6f7452b4519097f880d968a6eaf6f6ef38cc45a144958e553fbc6” “c1fb68aa00235766461c7e31ecfc759aa2dd905899ae6d95097061faeb72f9ee” “cab317d0125d7aab145bc7ee03a1e16804d5abdfa2aa8738198ac30dc5f7b569” “8aebf25556399b58091e533e455dd50a6a9cba958cc4ebb0aab175863c25b9a4” “d677ef584c6dfc0697901a44b885cc18e206f05114c8a3b7fde674fce6180879” “8db4b03b9ae654d4a57804286eb3e332725c84d7cdab38463cb6b97d5762ad26” “357d5abe6f693f2875bb3113f5c031b7031f21717e8078f90d9d9bc3a14bcbd8” “90e4b4a339776e635a78d398118cb782c87810cb384f1d1223da82b612338046” “1b8d67b43ff1723960eb5e0cba512a2c7a2ad544ddb2533a90101fd1852b426e” “82d2cac368ccdec2fcc7573f24c3f79654b78bf133096f9b40c20d97ec1d8016” “06f0b439b62164c6f8f84fdda32b62fb50b6d00e8b01c2208e55543a6337433a” “14225e826195202fbc17dcf333b94d91deb6e6f5ca3f5a75357009754666822a” “98e5e942303b4f356d6573009c96087f9b872f2fa258c673188d913f6faf17ea” “282606e51ef2811142af5068bd6694b7cf643b27d63666868bc97d04422318c1” “108b3724e0d684027c713703f663358779cc6544075bc8fd16ae71470497304f” “7feeed063855b06836e0262f77f5c6d3f415159a98a9676d549bfeb6c49637c4” “08851585c86abcf44bb1232bced2ae13bc9f6323aeda71adfa3791d6e7fea2b6” “30611406f83fae3d001e917b03ad47bbd1c7797cf640a2e7db9d2445741e2554” “0240d45644b370b0518e8407f5990a243c769fb0150a7e74297e6f7052a04a72” “a041a61c0387c57bb65150f002862ebcfe41135a3e3425268de24200b82d6ec9” “013d41c326fa6a010c813cce3fc68879e8a19ca9549ff8abdcb09dd3b82588ac” “c037a590a8097fb519d8b6a3f3f9836baa24431f378bac998968cfd2de58ff87” “422dfd95165c4d42cc174d33dc60a549c65be85e2eafca33bf90adaa3781239d” “5cd698ce53179b1e4eaa7917c992832a220600c973967904fea71e3980a46532” “f3f85a358dc6c3642bc6e0ca335c8909a2210814e5a7d4301993822bbf7db4e6” “e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855” “d5ecb1ae85bb043a10b8c9f10b40118c9b97806c73410c402340f89abbba8ebb” “43ff51aba14c343dbd1d95fa37732f3c3361ba9f61657476a390d94645fdd1eb” “f641bdb1b534a06baa5e05ffdb5039fb265fde2764fbfd9a90b0d23b75f3936b” “c335adbb7d7cb79bc34de77a16e12d28e6b927115b992bccc109fb752a365c72” “0eebf69ceadbbcdd747713f2f3f839fe0d4a45bd0d4d9f46145e40878fc9b098” default))) ‘(default-input-method “russian-no-windows”) ‘(diary-entry-marker (quote font-lock-variable-name-face)) ‘(display-time-24hr-format t) ‘(display-time-default-load-average nil) ‘(display-time-mode t) ‘(emms-mode-line-icon-image-cache (quote (image :type xpm :ascent center :data ”* XPM * static char note[] = { / width height num_colors chars_per_pixel */ " 10 11 2 1", * colors * ". c #358d8d", "# c None s None", * pixels * "###…####", "###.#…##", "###.###…", "###.#####.", "###.#####.", "#…#####.", "....#####.", "#..######.", "#######…", "######....", "#######..#" };”))) ‘(fci-rule-color “#383838”) ‘(fringe-mode 10 nil (fringe)) ‘(gnus-logo-colors (quote (“#259ea2” “#adadad”)) t) ‘(gnus-mode-line-image-cache (quote (image :type xpm :ascent center :data ”* XPM * static char gnus-pointer[] = { / width height num_colors chars_per_pixel */ " 18 13 2 1", * colors * ". c #358d8d", "# c None s None", * pixels * "##################", "######..##..######", "#####........#####", "#.##.##..##…####", "#…####.###…##.", "#..###.######.....", "#####.########…#", "###########.######", "####.###.#..######", "######..###.######", "###....####.######", "###..######.######", "###########.######" };”)) t) ‘(helm-follow-mode-persistent t) ‘(highlight-changes-colors (“#FD5FF0” “#AE81FF”)) ‘(highlight-symbol-colors (–map (solarized-color-blend it “#002b36” 0.25) (quote (“#b58900” “#2aa198” “#dc322f” “#6c71c4” “#859900” “#cb4b16” “#268bd2”)))) ‘(highlight-symbol-foreground-color “#93a1a1”) ‘(highlight-tail-colors ((“#49483E” . 0) (“#67930F” . 20) (“#349B8D” . 30) (“#21889B” . 50) (“#968B26” . 60) (“#A45E0A” . 70) (“#A41F99” . 85) (“#49483E” . 100))) ‘(hl-bg-colors (quote (“#7B6000” “#8B2C02” “#990A1B” “#93115C” “#3F4D91” “#00629D” “#00736F” “#546E00”))) ‘(hl-fg-colors (quote (“#002b36” “#002b36” “#002b36” “#002b36” “#002b36” “#002b36” “#002b36” “#002b36”))) ‘(js2-strict-inconsistent-return-warning nil) ‘(js2-strict-missing-semi-warning nil) ‘(ledger-reports (quote ((“reg -p "this month"” “ledger -f /Users/myusername/notes/ledger/bss.ledger reg -p "this month"”) (“премия” “ledger -f /Users/myusername/notes/ledger/bss.ledger reg –account-width 40 –payee-width 30 накопления:премия”) (“reg -p this month накопления” “ledger -f /Users/myusername/notes/ledger/bss.ledger reg накопления -p this month”) (“reg -p this month зарплатная” “ledger -f /Users/myusername/notes/ledger/bss.ledger reg \з\а\р\п\л\а\т\н\а\я -p this month”) (“reg” “ledger -f /Users/myusername/Dropbox/git/private/notes/ledger/bss.ledger reg”) (“движение по счёту зарплатная карта” “ledger -f /Users/myusername/Dropbox/git/private/notes/ledger/bss.ledger reg зарплатная”) (“движение средств по наличке” “ledger -f /Users/myusername/Dropbox/git/private/notes/ledger/bss.ledger reg наличные”) (“операции по долгам” “ledger -f /Users/myusername/Dropbox/git/private/notes/ledger/bss.ledger reg долги”) (“операции по счёту 10%” “ledger -f /Users/myusername/Dropbox/git/private/notes/ledger/bss.ledger reg десять”) (“bal” “%(binary) -f %(ledger-file) bal”) (“payee” “%(binary) -f %(ledger-file) reg @%(payee)”) (“account” “%(binary) -f %(ledger-file) reg %(account)”)))) ‘(linum-format ” %6d “) ‘(magit-diff-use-overlays nil) ‘(main-line-color1 “#222232”) ‘(main-line-color2 “#333343”) ‘(org-pomodoro-start-sound-p t) ‘(package-selected-packages (quote (tabbar ac-html-bootstrap ac-html-angular jedi jedi-core company-flx helm-company imenu-anywhere evil-numbers olivetti spacemacs-theme ag fb2-mode pdf-tools xpm nav nov flycheck-ledger ledger-mode rainbow-mode palette peep-dired bf-mode dumb-jump dash-at-point multi-term shell-switcher pomidor epa-file ox-html org-clock org-protocol org-id bbdb-com org-bullets org-bbdb message evil-lion pcre2el phpunit phpcbf php-extras comment-dwim-2 company-web web-mode-edit-element uniquify tomatinho js2-refactor js-comint company-tern tern impatient-mode helm-bm bm python-django py-autopep8 flycheck pip-requirements helm-git-grep wgrep edbi-database-url edbi-minor-mode edbi-sqlite edbi spaceline-config ipcalc git-timemachine dockerfile-mode better-shell winum spaceline window-numbering virtualenvwrapper emmet-mode web-mode indent-tools helm-ag hydra yaml-mode ansible ztree realgud python python-x evil-smartparens helm-pydoc pydoc pydoc-info python-info company-jedi company-php f fold-dwim fold-dwim-org folding hideshow-org hideshowvis origami evil-avy elfeed elfeed-goodies sr-speedbar php-mode drag-stuff which-key use-package smartscan reveal-in-osx-finder rainbow-delimiters powershell powerline-evil popwin pomodoro outline-magic org-time-budgets org-pomodoro org-plus-contrib org-outlook org-mobile-sync openwith noflet nlinum-relative neotree monokai-theme molokai-theme mode-icons minimal-theme mc-extras magit macrostep key-chord helm-themes helm-swoop helm-projectile helm-descbinds helm-chronos helm-c-yasnippet google-translate ggtags expand-region evil-visualstar evil-vimish-fold evil-tutor evil-textobj-anyblock evil-surround evil-snipe evil-org evil-nerd-commenter evil-matchit evil-indent-textobject evil-indent-plus evil-escape evil-args escreen ereader elscreen elpy dired-toggle-sudo dired-subtree dired-sort-menu+ dired-sort dired-details dired-avfs company-shell buffer-move bookmark+ bbdb auto-compile auto-async-byte-compile ace-window ace-link ace-jump-mode))) ‘(pos-tip-background-color “#073642”) ‘(pos-tip-foreground-color “#93a1a1”) ‘(powerline-color1 “#222232”) ‘(powerline-color2 “#333343”) ‘(powerline-default-separator (quote wave)) ‘(safe-local-variable-values (quote ((eval org-content 1) (eval org-content 2)))) ‘(show-paren-mode t) ‘(size-indication-mode t) ‘(smartrep-mode-line-active-bg (solarized-color-blend “#859900” “#073642” 0.2)) ‘(term-default-bg-color “#000000”) ‘(term-default-fg-color “#dddd00”) ‘(tool-bar-mode nil) ‘(tramp-default-proxies-alist (quote ((“sudo” nil “/ssh:workmyusername:”)))) ‘(vc-annotate-background “#2B2B2B”) ‘(vc-annotate-color-map (quote ((20 . “#BC8383”) (40 . “#CC9393”) (60 . “#DFAF8F”) (80 . “#D0BF8F”) (100 . “#E0CF9F”) (120 . “#F0DFAF”) (140 . “#5F7F5F”) (160 . “#7F9F7F”) (180 . “#8FB28F”) (200 . “#9FC59F”) (220 . “#AFD8AF”) (240 . “#BFEBBF”) (260 . “#93E0E3”) (280 . “#6CA0A3”) (300 . “#7CB8BB”) (320 . “#8CD0D3”) (340 . “#94BFF3”) (360 . “#DC8CC3”)))) ‘(vc-annotate-very-old-color “#DC8CC3”) ‘(web-mode-markup-indent-offset 2) ‘(weechat-color-list (unspecified “#272822” “#49483E” “#A20C41” “#F92672” “#67930F” “#A6E22E” “#968B26” “#E6DB74” “#21889B” “#66D9EF” “#A41F99” “#FD5FF0” “#349B8D” “#A1EFE4” “#F8F8F2” “#F8F8F0”)))

(custom-set-faces ;; custom-set-faces was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won’t work right. ‘(default ((t (:inherit nil :stipple nil :background “black” :foreground “cornsilk” :inverse-video nil :box nil :strike-through nil :overline nil :underline nil :slant normal :weight bold :height 141 :width normal :foundry “nil” :family “DejaVu Sans Mono”)))) ‘(company-scrollbar-bg ((t (:background “#ffffff”)))) ‘(company-scrollbar-fg ((t (:background “#ffffff”)))) ‘(company-scrollbar<-fg ((t (:background “#999999”)))) ‘(company-tooltip ((t (:inherit default :background “#ffffff”)))) ‘(company-tooltip-common ((t (:inherit font-lock-constant-face)))) ‘(company-tooltip-selection ((t (:inherit font-lock-function-name-face)))) ‘(fringe ((t (:background “grey10” :foreground “dim gray”)))) ‘(ledger-font-other-face ((t (:foreground “aquamarine” :weight normal)))) ‘(ledger-font-payee-pending-face ((t (:foreground “magenta” :weight bold)))) ‘(ledger-font-payee-uncleared-face ((t (:foreground “light coral” :weight bold)))) ‘(ledger-font-posting-account-face ((t (:foreground “cyan”)))) ‘(ledger-font-posting-amount-face ((t (:foreground “green”)))) ‘(ledger-font-posting-date-face ((t (:foreground “lemon chiffon”)))) ‘(ledger-font-report-clickable-face ((t (:foreground “khaki1” :weight bold)))) ‘(ledger-font-xact-pending-face ((t (:foreground “light gray” :weight normal)))) ‘(rainbow-delimiters-depth-1-face ((t (:foreground “orange”)))) ‘(rainbow-delimiters-depth-2-face ((t (:foreground “deep pink”)))) ‘(rainbow-delimiters-depth-3-face ((t (:foreground “chartreuse”)))) ‘(rainbow-delimiters-depth-4-face ((t (:foreground “deep sky blue”)))) ‘(rainbow-delimiters-depth-5-face ((t (:foreground “yellow”)))) ‘(rainbow-delimiters-depth-6-face ((t (:foreground “orchid”)))) ‘(rainbow-delimiters-depth-7-face ((t (:foreground “spring green”)))) ‘(rainbow-delimiters-depth-8-face ((t (:foreground “sienna1”)))) ‘(web-mode-block-attr-name-face ((t (:foreground “orange”)))) ‘(web-mode-html-attr-value-face ((t (:inherit font-lock-string-face :foreground “lime green”)))) ‘(web-mode-html-tag-face ((t (:foreground “light coral”)))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; !!! это надо делать в конце файла, иначе модули перетирают настройки метода ввода (if (eq system-type ‘darwin) (setq russian-input-method “russian-no-windows”) (setq russian-input-method “russian-computer”)) (setq-default default-input-method russian-input-method) (setq default-input-method russian-input-method) (set-input-method russian-input-method)

(toggle-frame-maximized)

;; font settings (if (eq system-type ‘darwin) (custom-set-faces ;; ‘(default ((t (:family “DejaVu Sans Mono” :foundry “outline” :slant normal :weight bold :height 140 :width normal)))) ‘(default ((t (:family “DejaVu Sans Mono” :foundry “outline” :slant normal :weight bold :height 140 :width normal)))) ‘(company-scrollbar-bg ((t (:background “#666666”)))) ‘(company-scrollbar-fg ((t (:background “#999999”)))) ‘(company-tooltip ((t (:inherit default :background “#333333”)))) ‘(company-tooltip-common ((t (:inherit font-lock-constant-face)))) ‘(company-tooltip-selection ((t (:inherit font-lock-function-name-face))))) (custom-set-faces ‘(default ((t (:family “DejaVu Sans Mono” :foundry “outline” :slant normal :weight bold :height 110 :width normal)))) ‘(company-scrollbar-bg ((t (:background “#666666”)))) ‘(company-scrollbar<-fg ((t (:background “#999999”)))) ‘(company-tooltip ((t (:inherit default :background “#333333”)))) ‘(company-tooltip-common ((t (:inherit font-lock-constant-face)))) ‘(company-tooltip-selection ((t (:inherit font-lock-function-name-face))))))

;;;; Proxy settings ;; (setq url-proxy-services nil) (setq url-proxy-services ‘((“no_proxy” . “^\(localhost\|127.*\|10.*\|11.*\|192.168.*\)”))) ;; (setq url-proxy-services ;; ‘((“no_proxy” . “^\(localhost\|127.*\|10.*\|11.*\|192.168.*\)”) ;; (“http” . “somedomain.com:666”) ;; (“https” . “somedomain.com:666”)))

platform-specific settings

Windows

move %HOME% to %USERPROFILE%: add USER!!!! environment variable HOME with value %USERPROFILE% add to environment variable %PATH% c:\emacs\bin;c:\emacs\hunspell mklink /D c:\Users\MY_USERNAME.emacs.d C:\Users\MY_USERNAME\Dropbox\svn\svn-common\env\emacs_conf.emacs.d mklink c:\Users\MY_USERNAME.emacs C:\Users\MY_USERNAME\Dropbox\svn\svn-common\env\emacs_conf.emacs mklink /D c:\emacs c:\Users\MY_USERNAME\Dropbox\svn\svn-common\env\emacs_conf\emacs install all fonts from c:\emacs\fonts mkdir ~/temp

(if (eq system-type 'windows-nt) ;OR gnu/linux
	(progn
        (setq russian-input-method "russian-computer")

      ;;font setting: http://www.gnu.org/software/emacs/manual/html_node/emacs/Windows-Fonts.html
      ;; -xrm Emacs.fontBackend:gdi или -xrm Emacs.fontBackend:uniscribe

	  (setenv "PATH"
			  (concat
			   ;; Change this with your path to MSYS bin directory
			   "C:\\emacs\\bin;"
			   (getenv "PATH")))

	  ;; make PC keyboard's Win key or other to type Super or Hyper, for emacs running on Windows.
	  (setq w32-pass-lwindow-to-system nil)
	  (setq w32-lwindow-modifier 'super) ; Left Windows key
	  ;; (setq w32-lwindow-modifier 'meta) ; Left Windows key

	  (setq w32-pass-rwindow-to-system nil)
	  (setq w32-rwindow-modifier 'super) ; Right Windows key

	  (setq w32-pass-apps-to-system nil)
	  (setq w32-apps-modifier 'hyper) ; Menu/App key

	  ;; Крайне помогло заклинание (setq redisplay-dont-pause t). Наконец-то прокрутка больших буферов с раскрашенным текстом перестала тормозить.

	  ;; источник возможного ускорения http://xeno-by.livejournal.com/57626.html
	  (setq w32-get-true-file-attributes nil)
	  (setq w32-quote-process-args t)
	  (setq redisplay-dont-pause t)
      (setq inhibit-compacting-font-caches t)

	  (setenv "LANG" "ru_RU")
      ;; (setenv "LC_CTYPE" "UTF-8")
      ;; (setenv "LC_ALL" "ru_RU.UTF-8")
      ;; (setenv "LANG" "ru_RU.UTF-8")
	  ;; (setenv "LANG" "en_US")
	  (set-language-environment "UTF-8")

	  (setq browse-url-browser-function 'browse-url-generic)
	  (setq browse-url-generic-program "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe")
      (if (string= (system-name) "myworkstation name")
          (setq browse-url-generic-program "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe")
          ;; (setq browse-url-generic-program "C:\\Program Files\\Internet Explorer\\iexplore.exe")
          ;; (setq browse-url-browser-function '(lambda (url &optional new-window) (interactive) (shell-command (concat "start " url))))
        )


	  (define-coding-system-alias 'windows-1251 'cp1251)
	  ;; (set-language-environment 'UTF-8) ;"Cyrillic-KOI8", "Russian", "cyrillic-koi8"
	  ;; (setq locale-coding-system 'cp866) ;cp1251
	  ;; (prefer-coding-system 'cp866)
	  ;; (prefer-coding-system 'cp1251-dos)
	  ;; (prefer-coding-system 'cp1251)
	  ;; (prefer-coding-system 'windows-1251-dos)
	  ;; (prefer-coding-system 'koi8-r-unix)
	  ;; (prefer-coding-system 'utf-8-unix)
	  ;; (prefer-coding-system 'utf-8)

	  ;; (set-default-coding-systems 'cp866) ;windows-1251
	  ;; (setq set-buffer-process-coding-system 'cp1251)
	  ;; (set-terminal-coding-system 'cp1251) ;utf-8; cp1251
	  ;; (setq default-buffer-file-coding-system 'cp1251-dos);;dos - для CRLF
	  (set-file-name-coding-system 'cp1251)
	  ;; (set-keyboard-coding-system 'utf-8) ;koi8-r;cp1251
	  (set-selection-coding-system 'utf-16le-dos) ;cp1251

	  (setq org-mobile-checksum-binary "c:\\emacs\\bin\\sha1sum.exe")
      (set-w32-system-coding-system 'cp1251)
      (setq w32-system-coding-system 'cp1251)

	  ;; (setq org-export-coding-system 'utf-8)
	  ;; (set-charset-priority 'unicode)
	  (setq default-process-coding-system '(utf-8-unix . utf-8-unix))
	  ;;;; (setq default-process-coding-system '(cp1251 . cp1251))
	  ;; (setq default-process-coding-system '(cp1251 . cp1251))
	  ;; (setq default-process-coding-system '(cp866 . cp866))
	  ;; (setq inherit-process-coding-system t)

	  ;; default-process-coding-system is a variable defined in ‘C source code’.
	  ;; Its value is (utf-8-unix . utf-8-unix)
	  ;; Documentation:
	  ;; Cons of coding systems used for process I/O by default.
	  ;; The car part is used for decoding a process output,
	  ;; the cdr part is used for encoding a text to be sent to a process.

	  ;;руссифицируем консоль
	  (defadvice shell (after my-shell-advice)
		(set-buffer-process-coding-system 'cp1251 'cp1251))
	  (ad-activate 'shell)

	  ;; https://emacswiki.org/emacs/CompileCommand

	  (defun bss/windows-compillation-hook ()
		;; (set-buffer-process-coding-system 'cp1251 'cp1251)
		)
	  (add-hook 'compilation-mode-hook #'bss/windows-compillation-hook)

	  ;; (add-to-list 'compilation-finish-functions 'notify-compilation-result)

	  ;; (defadvice compile (before ad-compile-smart activate)
	  ;; 	""
	  ;; 	(switch-to-buffer-other-window "*compilation*")
	  ;; 	(set-buffer-process-coding-system "cp1251" "cp1251")
	  ;; 	)
	  ;; (defun compile-1251 ()
	  ;; 	"Set compilation buffer for 1251"
	  ;; 	( save-current-buffer
	  ;; 	  (set-buffer "*compilation*")
	  ;; 	  (set-buffer-process-coding-system "cp1251" "cp1251")))

	  ;; (setq compilation-process-setup-function 'compile-1251)

	  ;; (defadvice compile (around split-vertically activate)
	  ;; (set-buffer-process-coding-system 'cp1251 'cp1251))

	  ;; (ad-activate 'compile)
	  ;; ad-do-it)

	  ;; (modify-coding-system-alist 'process "\\*compilation\\*\\'"   'cp1251)


	  ))

(if (eq system-type 'windows-nt) ;OR gnu/linux
	(progn

	  (setq org-file-apps (quote ((auto-mode . emacs)
        ("\\.png\\'" . default)
        ("\\.jpg\\'" . default)
        ("\\.jpeg\\'" . default)
        ("\\.doc\\'" . default)
        ("\\.docx\\'" . default)
        ("\\.xls\\'" . default)
        ("\\.xlsx\\'" . default)
        ("\\.mm\\'" . default)
        ("\\.x?html?\\'" . default)
        ("\\.pdf\\'" . default))))))

Addon from Sachaa Chua I’m on Windows, so I use Cygwin to add Unix-y tools to make my life easier. These config snippets seem to help too. ;; #+begin_src emacs-lisp :tangle yes (when (eq system-type ‘windows-nt) (setenv “CYGWIN” “nodosfilewarning”) (setq shell-file-name “C:/emacs/libexec/emacs/24.4/i686-pc-mingw32/cmdproxy.exe”) (add-hook ‘comint-output-filter-functions ‘shell-strip-ctrl-m nil t) (add-hook ‘comint-output-filter-functions ‘comint-watch-for-password-prompt nil t)) ;; #+end_src

Linux

(if (eq system-type 'gnu/linux)
	(progn	;;We are in linux



        (setq russian-input-method "russian-computer")
	  (setenv "LANG" "ru_RU")
      (setenv "LC_CTYPE" "UTF-8")
      (setenv "LC_ALL" "ru_RU.UTF-8")
      ;; (setenv "LANG" "ru_RU.UTF-8")
	  (setq browse-url-browser-function 'browse-url-generic)
	  (setq browse-url-generic-program "/usr/lib/chromium-browser/chromium-browser")

	  ;;----------------------------------------------------------
	  ;; openwith: https://bitbucket.org/jpkotta/openwith

	  (use-package openwith)
	  (openwith-mode t)
	  (setq openwith-associations
			(list (list (openwith-make-extension-regexp '("pdf"))
						"evince" '(file))
				  (list (openwith-make-extension-regexp '("flac" "mp3" "wav"))
						"vlc" '(file))
				  (list (openwith-make-extension-regexp '("avi" "flv" "mov" "mp4"
														  "mpeg" "mpg" "ogg" "wmv"))
						"vlc" '(file))
				  (list (openwith-make-extension-regexp '("bmp" "jpeg" "jpg" "png"))
						"ristretto" '(file))
				  (list (openwith-make-extension-regexp '("doc" "docx" "odt"))
						"libreoffice" '("--writer" file))
				  (list (openwith-make-extension-regexp '("ods" "xls" "xlsx"))
						"libreoffice" '("--calc" file))
				  (list (openwith-make-extension-regexp '("odp" "pps" "ppt" "pptx"))
						"libreoffice" '("--impress" file))
				  ))

	  ))


(if (eq system-type 'gnu/linux) ;OR gnu/linux
    (progn
        (setq org-file-apps (quote ((auto-mode . emacs)
        ("\\.png\\'" . default)
        ("\\.jpg\\'" . default)
        ("\\.jpeg\\'" . default)
        ("\\.doc\\'" . default)
        ("\\.docx\\'" . default)
        ("\\.xls\\'" . default)
        ("\\.xlsx\\'" . default)
        ;; ("\\.xlsx\\'" . "loffice %s")
        ("\\.mm\\'" . default)
        ("\\.x?html?\\'" . default)
                ("\\.pdf\\'" . "evince \"%s\"" )
        ("\\.fb2\\'" . "cr3 \"%s\"" )
        ;; ("\\.pdf\\'" . (format "~/bin/my_echo.sh \"%%s\"" )
        ;; ("\\.pdf\\'" . "~/bin/my_echo.sh %s" )
                ;; (t . "xdg-open %s")
        )))
;;)
     )
)

Macos

(if (eq system-type 'darwin)
	(progn
	  (setenv "LANG" "ru_RU")
      (setenv "LC_CTYPE" "UTF-8")
      (setenv "LC_ALL" "ru_RU.UTF-8")
      ;; (setenv "LANG" "ru_RU.UTF-8")
	  (setq exec-path (add-to-list 'exec-path "/usr/local/bin"))

	  (setq browse-url-browser-function 'browse-url-generic)
	  (setq browse-url-generic-program "open")
	  (setq mac-command-modifier 'meta)
	  (setq mac-option-modifier 'super)
	  (setq mac-function-modifier 'hyper) ;; https://www.emacswiki.org/emacs/EmacsForMacOS
	  (setq mac-right-command-modifier 'control)
	  ;; mac-right-control-modifier
	  ;; mac-right-option-modifier
      ;; (setq mac-mouse-wheel-smooth-scroll nil)
      ;; (setq mac-mouse-wheel-smooth-scroll t)

	  ;; http://www.manpagez.com/info/emacs/emacs_640.php
	  (setq mac-pass-command-to-system nil)
	  (setq mac-pass-control-to-system nil)

	  (if (eq system-type 'darwin)
		  (defun w32-short-file-name (name)
			"replace under linux"
			name))

	  ;;https://coderwall.com/p/mf2hja/russian-keyboard-layout-for-emacs-on-mac-os-x
	  ;; russian layout
	  (require 'russian-no-windows) ;; For MacOS russian layout

	  (use-package reveal-in-osx-finder)
	  (global-set-key (kbd "C-c z") 'reveal-in-osx-finder)

	(setq russian-input-method "russian-no-windows")
    ;; add missing ; on mac layout via H-8
    (define-key key-translation-map (kbd "H-8") (kbd ";"))
    (define-key key-translation-map (kbd "H-;") (kbd ";"))
    ;; (global-set-key (kbd "H-8") (kbd ";"))
    ;; (global-unset-key  (kbd "H-8"))

    (setq org-file-apps (quote ((auto-mode . emacs)
        ("\\.png\\'" . default)
        ("\\.jpg\\'" . default)
        ("\\.jpeg\\'" . default)
        ("\\.doc\\'" . default)
        ("\\.docx\\'" . default)
        ("\\.ppt\\'" . default)
        ("\\.pptx\\'" . default)
        ("\\.djvu\\'" . default)
        ("\\.xls\\'" . default)
        ("\\.xlsx\\'" . default)
        ("\\.mm\\'" . default)
        ("\\.x?html?\\'" . default)
                ("\\.pdf\\'" . default )
        ("\\.fb2\\'" . default )
                ;; (t . "open %s")
    )))
))


Notifications ftom Howard Abrams

Looking at making some processes a bit more obvious, for instance, when a command kicked off in the eshell takes too much time, I need it to beep when it is done. For this, I simply shell out to Mac’s notification center using the terminal-notifier. To install, do:

brew install terminal-notifier

The beep command can either be typed at the end of a command (after a semi-colon), or at the beginning, since anything following is executed first, and the notification follows.

(defun eshell/beep (&rest args)
  "Send a Mac notification message when the command given has completed."

  (let ((comment (if args
                     (concat "Process has completed: " (car args))
                   "Process has completed.")))
    (if args
        (eshell-plain-command (car args) (cdr args)))

    (shell-command-to-string
     (concat "terminal-notifier -message '"
             comment
             "' -title 'Emacs' -subtitle 'Eshell Process Completed'"
             " -sound default -sender org.gnu.Emacs"))))

базовые настройки emacs

encodings

;;настройка кодировки
;;Используем UTF-8
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; !!! это надо делать в конце файла, иначе модули перетирают настройки метода ввода
(setq-default default-input-method "russian-computer")
(setq default-input-method "russian-computer")

(set-language-environment 'utf-8) ;"Cyrillic-KOI8", "Russian", "cyrillic-koi8"
(set-default-coding-systems 'utf-8)
(set-terminal-coding-system 'utf-8)
(set-keyboard-coding-system 'utf-8)
(setq default-process-coding-system 'utf-8)
(setq file-name-coding-system 'utf-8)
(setq org-export-coding-system 'utf-8)
(setq default-buffer-file-coding-system 'utf-8)
(set-charset-priority 'unicode)
(setq default-process-coding-system '(utf-8-unix . utf-8-unix))
(set-file-name-coding-system 'utf-8)
(set-keyboard-coding-system 'utf-8) ;koi8-r;cp1251
(prefer-coding-system 'utf-8)
;; (add-to-list 'auto-coding-alist '("\\.ps1\\'" . windows1251))
;; (add-to-list 'auto-coding-alist '("\\.vbs\\'" . windows1251))
;; (find-auto-coding "/Volumes/c$/SVN/sql_query.ps1" 1)

настройки каталогов

(setf temporary-file-directory "~/temp")

backup

управляем бэкапом в один файл. Set emacs-tmp-dir variable

(setq emacs-tmp-dir (expand-file-name (format "%s/%s%s/" temporary-file-directory "emacs" (user-uid))))
(if (not (file-exists-p emacs-tmp-dir))
        (make-directory emacs-tmp-dir t))
;; (setq auto-save-list-file-prefix (concat emacs-tmp-dir ".saves-"))
(setq auto-save-list-file-prefix emacs-tmp-dir
      auto-save-file-name-transforms `((".*" ,emacs-tmp-dir t))
      tramp-auto-save-directory emacs-tmp-dir ;; auto-save tramp files in local directory
      backup-directory-alist `((".*" . ,emacs-tmp-dir ))
      tramp-backup-directory-alist backup-directory-alist ; https://www.gnu.org/software/emacs/manual/html_node/tramp/Auto_002dsave-and-Backup.html
      make-backup-files t               ; backup of a file the first time it is saved.
      backup-by-copying t               ; don't clobber symlinks
      version-control t                 ; version numbers for backup files
      delete-old-versions t             ; delete excess backup files silently
      delete-by-moving-to-trash nil
      kept-old-versions 6               ; oldest versions to keep when a new numbered backup is made (default: 2)
      kept-new-versions 9               ; newest versions to keep when a new numbered backup is made (default: 2)
      auto-save-default t               ; auto-save every buffer that visits a file
      auto-save-timeout 20              ; number of seconds idle time before auto-save (default: 30)
      auto-save-interval 200            ; number of keystrokes between auto-saves (default: 300)
      )

automatically purge backup files not accessed in a week:

;;(message "Deleting old backup files...")
;;(let ((week (* 60 60 24 7))
;;      (current (float-time (current-time))))
;;  (dolist (file (directory-files temporary-file-directory t))
;;    (when (and (backup-file-name-p file)
;;               (> (- current (float-time (fifth (file-attributes file))))
;;                  week))
;;      (message "%s" file)
;;      (delete-file file))))

поведение и базовые настройки

(global-auto-revert-mode t)

(setq delete-trailing-lines nil) ;; disable deleting empty lines from files
;; There are a few applications, such as crontab, that require a trailing
;; new line. To be safe, always leave a trailing newline.
(setq-default require-final-newline t)
(setq require-final-newline t)
(put 'narrow-to-region 'disabled nil)

(fset 'yes-or-no-p 'y-or-n-p)
(setq grep-command "grep -nHr -e ")
(setq make-pointer-invisible t) ;;курсор мыши прячется при вводе текста

;;Табулятор
(setq-default tab-width 4)
(setq-default indent-tabs-mode nil) ;; отступы пробелами
(setq tab-always-indent 'complete) ;;после автоматической установки отступов Tab выполняет автодополнение
(setq python-indent-offset 4)
;; (setq tab-always-indent nil)
(setq tab-stop-list '(4 8 12))
;; (setq backward-delete-char-untabify-method 'hungry)

(setq superword-mode nil) ;; смотри описание функции.
(delete-selection-mode 1) ;;выделенный текст полностью удаляется или заменяется при удалении, вставке или вводе
;; (setq mouse-yank-at-point t) ;;мышь вставляет текст на позиции текстового курсора

;; параметры окружения
;; Start off in "C:/home" dir.
(cd "~/")
(setq my-author-name (getenv "USERNAME"))
(setq user-full-name (getenv "USERNAME"))
;;Shut off message buffer.
										;(setq message-log-max nil)
										;(kill-buffer "*Messages*")
;;Clear Scratch buffer
(setq initial-scratch-message nil)

										; no beep
(setq visible-bell t)
;; macos bugfix from https://www.reddit.com/r/emacs/comments/3omsr2/weird_display_issue_in_os_x/
(setq ring-bell-function (lambda () (message "*woop*")))

(when (display-graphic-p)
  (tool-bar-mode -1)
  ;;(menu-bar-mode -1)
  (scroll-bar-mode -1))

;; (setq create-lockfiles nil)
(setq create-lockfiles t)

;any files that change on disk where there are no changes in the buffer automatically revert to the on-disk version.
(global-auto-revert-mode t)

;; http://www.gnu.org/software/emacs/manual/html_node/emacs/File-Aliasqqes.html
(setq vc-follow-symlinks t)
;; Don't show whitespace in diff, but show context
(setq vc-diff-switches '("-b" "-B" "-u"))
(setq vc-git-diff-switches nil)

;; (setq find-file-visit-truename t)
;; (setq find-file-existing-other-name t)
(setq find-file-suppress-same-file-warnings t)

(setq directory-abbrev-alist nil)
;; (setq directory-abbrev-alist '( ("/mnt/sda5/yandexdisk" . "~/yandexdisk")
;; 								("/mnt/sda5/Dropbox" . "~/Dropbox")
;; 								("~/git/private/notes" . "~/notes")
;;                                 ("/Users/myusername/Dropbox/git/private/notes" . "~/notes")
;; 								("~/Dropbox/git" . "~/git")
;; 								("~/Dropbox/git/private/notes/" . "~/notes")
;; 								("~/git/common/env/emacs_conf/_emacs.d" . "~/.emacs.d")
;;                                 ("/Users/myusername/Dropbox/git/common/env/emacs_conf/_emacs.d" . "~/.emacs.d")
;; 								))


;;загружается молча
;(setq inhibit-startup-message t)
;; отключаем wordwrap по умолчанию. включить для буффера можно через M-x toggle-truncate-lines
(toggle-truncate-lines 1)
(setq truncate-partial-width-windows nil)

;;Параграфы разделяются одним пробелом а не по-американски двумя
;; см. http://www.gnu.org/software/emacs/manual/html_node/emacs/Sentences.html
(setq sentence-end-double-space nil)

;;выравнивание текста (wrap mode)
(global-visual-line-mode t)

(setq visual-line-fringe-indicators '(left-curly-arrow right-curly-arrow))
(setq-default word-wrap t)
(setq-default fill-column 79)
;; (add-hook 'org-agenda-mode-hook

(setq default-major-mode 'text-mode)

;(setq longlines-show-hard-newlines
;если выравнивать надо только в текстовом режиме
;(add-hook 'text-mode-hook 'turn-on-visual-line-mode)
;;удаляем в корзину
(setq delete-by-moving-to-trash t)
;;добавлять пустую строку в конец файла при сохранении
(setq require-final-newline t)

;; Save whatever’s in the current (system) clipboard before
;; replacing it with the Emacs’ text.
;; https://github.com/dakrone/eos/blob/master/eos.org
(setq save-interprogram-paste-before-kill t)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; kill line if no region active                                          ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; http://emacs-fu.blogspot.co.uk/2009/11/copying-lines-without-selecting-them.html
;; http://pragmaticemacs.com/emacs/cut-whole-line/
;; (defadvice kill-region (before slick-cut activate compile)
;;   "When called interactively with no active region, kill a single line instead."
;;   (interactive
;;    (if mark-active (list (region-beginning) (region-end))
;;      (list (line-beginning-position)
;;            (line-beginning-position 2)))))

скроллинг и мышь

;;Fix so button 2 pastes at cursor, not Point
;(setq mouse-yank-at-point t)
;;колесо мышки
(mouse-wheel-mode 1)
(setq mouse-avoidance-mode nil)
(mouse-avoidance-mode 'none) ;banish or exile
(setq mouse-avoidance-threshold 10)

(global-set-key [C-mouse-4] '(lambda () (interactive) (text-scale-increase 1)))
(global-set-key [C-mouse-5] '(lambda () (interactive) (text-scale-decrease 1)))
(global-set-key [C-wheel-up] '(lambda () (interactive) (text-scale-increase 1)))
(global-set-key [C-wheel-down] '(lambda () (interactive) (text-scale-decrease 1)))

;;гладкий скроллинг с полями
;(setq scroll-conservatively 50)
;(setq scroll-preserve-screen-position 't)
;(setq scroll-margin 10)
;(setq scroll-conservatively 0)
;(setq scroll-preserve-screen-position nil)
;(setq scroll-margin 0)
(setq scroll-preserve-screen-position t)

;; https://www.emacswiki.org/emacs/SmoothScrolling
;; scroll one line at a time (less "jumpy" than defaults)


(setq mouse-wheel-scroll-amount '(1 ((shift) . 5))) ;; one line at a time
(setq mouse-wheel-progressive-speed 'nil) ;; don't accelerate scrolling
;; (setq scroll-conservatively 101) ;; move minimum when cursor exits view, instead of recentering
;; (setq mouse-wheel-scroll-amount '(1)) ;; mouse scroll moves 1 line at a time, instead of 5 lines
;; (setq mouse-wheel-progressive-speed nil) ;; on a long mouse scroll keep scrolling by 1 line


(setq mouse-wheel-follow-mouse 't) ;; ascroll window under mouse
(setq scroll-step 1) ;; keyboard scroll one line at a time
(setq mac-mouse-wheel-smooth-scroll t)
;; (setq jit-lock-defer-time 0.05)

;; Rectangular select with Meta
;; https://emacs.stackexchange.com/questions/7244/enable-emacs-column-selection-using-mouse/7261#7261
(defun mouse-start-rectangle (start-event)
  (interactive "e")
  (deactivate-mark)
  (mouse-set-point start-event)
  (rectangle-mark-mode +1)
  (let ((drag-event))
    (track-mouse
      (while (progn
               (setq drag-event (read-event))
               (mouse-movement-p drag-event))
        (mouse-set-point drag-event)))))

(global-set-key (kbd "C-<down-mouse-1>") #'mouse-start-rectangle)

настройки даты и времени

Формат даты и времени

;; hour format
(setq display-time-24hr-format t)
;(setq display-time-day-and-date t)
(setq display-time-default-load-average nil)
(display-time)
;(setq calendar-date-display-form (quote ((format "%04s-%02d-%02d" year (string-to-int month) (string-to-int day)))))
;(setq calendar-time-display-form (quote (24-hours ":" minutes (if time-zone " (") time-zone (if time-zone ")"))))
(setq calendar-date-style "european") ;;day/month/year
(setq calendar-week-start-day 1)

внешний вид

Frame Title Format

имя буфера или полное имя файла/директории предваренное именем пользователя и машины при удаленном подключении. Как ни странно, заголовок фрейма (окна в оконном менеджере операционной системы) не кастомизируется стандартными средствами. Если открыто несколько фреймов, заголовок по-умолчанию совершенно бесполезен, поэтому используем наипростейший формат, позволяющий отличить один фрейм от другого.
;; needed for pomodoro
(defun bss/default-frame-title-format()
  (interactive)
  (concat (when (file-remote-p default-directory)
            (let ((user (file-remote-p default-directory 'user))
                  (host (file-remote-p default-directory 'host)))
              (format "%s@%s:" user host)))
          (or
           (buffer-name) buffer-file-truename dired-directory)))


;; (setq frame-title-format (bss/default-frame-title-format))
(setq frame-title-format '(:eval (bss/default-frame-title-format)))
;; (setq frame-title-format

;; (setq frame-title-format
;;       '(:eval (concat (when (file-remote-p default-directory)
;;                         (let ((user (file-remote-p default-directory 'user))
;;                               (host (file-remote-p default-directory 'host)))
;;                           (format "%s@%s:" user host)))
;;                       (or
;;                        ;; (abbreviate-file-name (buffer-file-name))
;;                        (buffer-name) buffer-file-truename dired-directory))))
;; TODO: show [directory] and filename (full filename)

в строке состояния показываем номера строки, колонки, размер файла

(setq column-number-mode t)
(setq line-number-mode t)
(size-indication-mode t)

курсор

http://help-gnu-emacs.gnu.narkive.com/rdmjSPZy/changing-cursor-color-depending-on-input-method

(add-hook 'input-method-activate-hook
		  '(lambda ()
			 (if (not (eq (selected-window) (minibuffer-window)))
				 (set-cursor-color "green"))))
(add-hook 'input-method-inactivate-hook
		  '(lambda ()
			 (if (not (eq (selected-window) (minibuffer-window)))
				 (set-cursor-color "white"))))

(add-hook 'post-command-hook
		  '(lambda ()
			 (set-cursor-color
			  (if current-input-method
				  "green"
				"white"))))

синтаксис

;; Show marked text
;(setq transient-mark-mode '1)
(setq font-lock-maximum-decoration t)
;;for syntax highlighting. needed by org-mode
(global-font-lock-mode t)
;;Выделение парных скобок
(show-paren-mode 1)
;; Показывает курсор только в активном окне
;;(cursor-in-non-selected-windows nil)

показать пробелы и табуляции

;; (global-whitespace-mode t)
;; (global-whitespace-newline-mode t)
;; ;; make whitespace-mode use just basic coloring
;; ;;(setq whitespace-style (quote (spaces tabs newline space-mark tab-mark newline-mark)))
(setq whitespace-style (quote (tabs newline space-mark tab-mark newline-mark)))
;; ;;способ  отображение пробела (「·」), символа новой строки (「¶」) и табуляции (「▷」)
;; ;;все числа - десятичный юникод.
(setq whitespace-display-mappings
      '(
        (space-mark 32 [183] [46]) ; 32 SPACE, 183 MIDDLE DOT 「·」, 46 FULL STOP 「.」
        (newline-mark 10 [182 10]) ; 10 LINE FEED
        (tab-mark 9 [9655 9] [92 9]) ; 9 TAB, 9655 WHITE RIGHT-POINTING TRIANGLE 「▷」
       ))
;; (setq whitespace-global-modes '(not org-mode web-mode "Web" emacs-lisp-mode))
;; (global-whitespace-mode)

шрифты

;; http://www.gnu.org/software/emacs/manual/html_node/emacs/Windows-Fonts.html
;; https://code.google.com/p/mactype/   http://www.mactype.ga/MacTypeInstaller_2013_1231_0.exe

;; '(default ((t (:family "Tahoma" :foundry "outline" :slant normal :weight normal :height 113 :width normal)))))
;; '(default ((t (:family "Droid Sans Mono Dotted" :foundry "outline" :slant normal :weight normal :height 98 :width normal)))))
; (default ((t (:family "DejaVu Sans Mono" :foundry "outline" :slant normal :weight bold :height 98 :width normal))))
(add-hook 'emacs-startup-hook (lambda ()
				(if (eq system-type 'darwin)
				    (custom-set-faces
				     ;; '(default ((t (:family "DejaVu Sans Mono" :foundry "outline" :slant normal :weight bold :height 140 :width normal))))
				     '(default ((t (:family "DejaVu Sans Mono" :foundry "outline" :slant normal :weight bold :height 140 :width normal))))
				     '(company-scrollbar-bg ((t (:background "#666666"))))
				     '(company-scrollbar-fg ((t (:background "#999999"))))
				     '(company-tooltip ((t (:inherit default :background "#333333"))))
				     '(company-tooltip-common ((t (:inherit font-lock-constant-face))))
				     '(company-tooltip-selection ((t (:inherit font-lock-function-name-face)))))
				  (custom-set-faces
				   '(default ((t (:family "DejaVu Sans Mono" :foundry "outline" :slant normal :weight bold :height 110 :width normal))))
				   '(company-scrollbar-bg ((t (:background "#666666"))))
				   '(company-scrollbar<-fg ((t (:background "#999999"))))
				   '(company-tooltip ((t (:inherit default :background "#333333"))))
				   '(company-tooltip-common ((t (:inherit font-lock-constant-face))))
				   '(company-tooltip-selection ((t (:inherit font-lock-function-name-face))))))
				))

разное

;; при старте показывать buffer scratch ;; (setq initial-buffer-choice t)

подчеркнуть текущую строку

;; (global-hl-line-mode -1)
;; (set-face-attribute hl-line-face nil :underline t)
;; (set-face-background 'highlight nil)
;; (set-face-foreground 'highlight nil)
;; (set-face-underline-p 'highlight t)

modeline settings

;;;; modeline section
;; spaceline/powerline modeline  package
;; https://github.com/TheBB/spaceline
;; (use-package spaceline-config
;; (require 'spaceline-config)

;; --------------------------------------------------
;; http://pragmaticemacs.com/emacs/get-that-spacemacs-look-without-spacemacs/
;; было в .emacs: '(custom-enabled-themes (quote (wheatgrass)))

(use-package spacemacs-theme
  :ensure t
  :init
  ;; (load-theme 'spacemacs-dark t)
  (setq spacemacs-theme-org-agenda-height nil)
  (setq spacemacs-theme-org-height nil)

  ;; ;; set sizes here to stop spacemacs theme resizing these
  ;; (set-face-attribute 'org-level-1 nil :height 1.0)
  ;; (set-face-attribute 'org-level-2 nil :height 1.0)
  ;; (set-face-attribute 'org-level-3 nil :height 1.0)
  ;; (set-face-attribute 'org-scheduled-today nil :height 1.0)
  ;; (set-face-attribute 'org-agenda-date-today nil :height 1.1)
  ;; (set-face-attribute 'org-table nil :foreground "#008787")

  )

(use-package spaceline
  :demand t
  :init
  (if (display-graphic-p)
      ;; (setq powerline-default-separator 'arrow)
      ;; (setq powerline-default-separator 'arrow-fade)
      ;; (setq powerline-default-separator 'wave)
      (setq powerline-default-separator 'arrow-fade)
    (setq powerline-default-separator 'utf-8))
  :config
  (require 'spaceline-config)
  (spaceline-spacemacs-theme)

  ;; (spaceline-spacemacs-theme)
  (spaceline-toggle-minor-modes-off)
  (spaceline-toggle-major-mode-off)
  (spaceline-toggle-org-pomodoro-on)
  (spaceline-toggle-org-clock-off)


  ;; (spaceline-emacs-theme)

  (setq ns-use-srgb-colorspace nil)
  (setq powerline-image-apple-rgb t)
  (setq spaceline-highlight-face-func 'spaceline-highlight-face-evil-state)
  (setq spaceline-window-numbers-unicode t)
  (setq spaceline-workspace-numbers-unicode t)


  (set-face-attribute 'mode-line nil          :foreground "Black" :background "DarkOrange" :box nil)
  (set-face-attribute 'mode-line-inactive nil :foreground "Black" :background "Darkorange2"  :box nil)
  (set-face-attribute 'powerline-active1 nil  :foreground "Black" :background "DarkOrange" :box nil)
  (set-face-attribute 'powerline-active2 nil  :foreground "Black" :background "Darkorange4"  :box nil)
  (set-face-attribute 'powerline-inactive1 nil  :foreground "Black" :background "DarkOrange" :box nil)
  (set-face-attribute 'powerline-inactive2 nil  :foreground "Black" :background "Darkorange4"  :box nil)


  ;; ("%e" (:eval (spaceline-ml-main)))
  ;; mode-line-format is a variable defined in ‘C source code’.
  ;; Its value is ("%e" (:eval (spaceline-ml-main)))
  ;; (setq mode-line-format '("%e" buffer-file-name (:eval (spaceline-ml-main))))
  (setq mode-line-format '("%e" (:eval (spaceline-ml-main))))


  )



;; --------------------------------------------------




;; --------------------------------------------------

;; (use-package diminish
(use-package diminish)
  ;; :disabled
  ;; :ensure t
  ;; :config

  (if (display-graphic-p)
      (progn
        ;; (eval-after-load "projectile" '(diminish 'projectile-mode "Ⓟ"))
        ;; (diminish 'evil-snipe-local-mode "➶")

        )
    )
  (diminish 'evil-snipe-local-mode)
  (diminish 'visual-line-mode)
  (diminish 'which-key-mode)
  (diminish 'undo-tree-mode)
  (diminish 'helm-mode)
  (diminish 'company-mode)
  (diminish 'global-company-mode)
  (diminish 'abbrev-mode)
  (diminish 'evil-escape-mode)
  ;;
  (mode-icons-mode)
  ;; install these fonts:
  ;; env/emacs_conf/emacs/fonts/font-mfizz.ttf
  ;; env/emacs_conf/emacs/fonts/fontawesome-webfont.ttf
  ;; env/emacs_conf/emacs/fonts/octicons.ttf


  ;; ;; ;;скрываем ненужные и очевидные режимы из статуса
  ;; ;; https://www.masteringemacs.org/article/hiding-replacing-modeline-strings
  ;; (defvar mode-line-cleaner-alist
  ;;   `((auto-complete-mode . " α")
  ;;     (yas/minor-mode . " υ")
  ;;     (paredit-mode . " π")
  ;;     (eldoc-mode . "")
  ;;     (abbrev-mode . "")
  ;;     (helm-mode . " H")
  ;;     (undo-tree-mode . "")
  ;; 	(org-mode . "")
  ;; 	(org-indent-mode . "")
  ;;     (org-agenda-mode . "Am")
  ;;     (superword-mode . "")
  ;; 	(yas-minor-mode . "")
  ;; 	(yas-global-mode . "")
  ;; 	(visual-line-mode . "")
  ;; 	(fundamental-mode . " F")
  ;;     ;; Major modes
  ;;     (lisp-interaction-mode . "λ")
  ;;     (hi-lock-mode . "")
  ;;     (python-mode . "Py")
  ;;     (emacs-lisp-mode . "EL")
  ;;     (nxhtml-mode . "nx"))
  ;;   "Alist for `clean-mode-line'.
  ;;
  ;; When you add a new element to the alist, keep in mind that you
  ;; must pass the correct minor/major mode symbol and a string you
  ;; want to use in the modeline *in lieu of* the original.")
  ;;
  ;;
  ;; (defun clean-mode-line ()
  ;;   (interactive)
  ;;   (loop for cleaner in mode-line-cleaner-alist
  ;;         do (let* ((mode (car cleaner))
  ;;                  (mode-str (cdr cleaner))
  ;;                  (old-mode-str (cdr (assq mode minor-mode-alist))))
  ;;              (when old-mode-str
  ;;                  (setcar old-mode-str mode-str))
  ;;                ;; major mode
  ;;              (when (eq mode major-mode)
  ;;                (setq mode-name mode-str)))))
  ;;
  ;;
  ;; (add-hook 'after-change-major-mode-hook 'clean-mode-line)

;;; alias the new `flymake-report-status-slim' to
;;; `flymake-report-status'
  (defalias 'flymake-report-status 'flymake-report-status-slim)
  (defun flymake-report-status-slim (e-w &optional status)
    "Show \"slim\" flymake status in mode line."
    (when e-w
      (setq flymake-mode-line-e-w e-w))
    (when status
      (setq flymake-mode-line-status status))
    (let* ((mode-line " Φ"))
      (when (> (length flymake-mode-line-e-w) 0)
        (setq mode-line (concat mode-line ":" flymake-mode-line-e-w)))
      (setq mode-line (concat mode-line flymake-mode-line-status))
      (setq flymake-mode-line mode-line)
      (force-mode-line-update)))




  ;; ;;скрываем ненужные и очевидные режимы из статуса
  ;; ;; http://emacs.stackexchange.com/questions/3925/hide-list-of-minor-modes-in-mode-line
  ;; (defvar hidden-minor-modes ; example, write your own list of hidden
  ;;   '(abbrev-mode            ; minor modes
  ;;     auto-fill-function
  ;;     flycheck-mode
  ;;     flyspell-mode
  ;;     inf-haskell-mode
  ;;     haskell-indent-mode
  ;;     haskell-doc-mode
  ;; 	Undo-Tree
  ;; 	Helm
  ;; 	Wrap
  ;;     smooth-scroll-mode))

  ;; (defun purge-minor-modes ()
  ;;   (interactive)
  ;;   (dolist (x hidden-minor-modes nil)
  ;;     (let ((trg (cdr (assoc x minor-mode-alist))))
  ;;       (when trg
  ;;         (setcar trg "")))))

  ;; (add-hook 'after-change-major-mode-hook 'purge-minor-modes)
  ;; ;; Вариант 2
  ;; )

window numbering

;;;; window-numbering
(use-package window-numbering
  ;; :disabled
  :ensure t
  :config
  (defun window-numbering-install-mode-line (&optional position)
    "Do nothing, the display is handled by the powerline.")
  (setq window-numbering-auto-assign-0-to-minibuffer nil)
  (window-numbering-mode 1)

;; disable selective numbering ;;   ;; make sure neotree is always 0
;; disable selective numbering ;;   (defun spacemacs//window-numbering-assign ()
;; disable selective numbering ;;     "Custom number assignment for neotree."
;; disable selective numbering ;;     (if (and (boundp 'neo-buffer-name)
;; disable selective numbering ;;              (string= (buffer-name) neo-buffer-name)
;; disable selective numbering ;;              ;; in case there are two neotree windows. Example: when
;; disable selective numbering ;;              ;; invoking a transient state from neotree window, the new
;; disable selective numbering ;;              ;; window will show neotree briefly before displaying the TS,
;; disable selective numbering ;;              ;; causing an error message. the error is eliminated by
;; disable selective numbering ;;              ;; assigning 0 only to the top-left window
;; disable selective numbering ;;              (eq (selected-window) (window-at 0 0)))
;; disable selective numbering ;;         0)
;; disable selective numbering ;;     ;; set scratch to 9
;; disable selective numbering ;;     ;; (if (equal (buffer-name) "*scratch*") 9)
;; disable selective numbering ;;     )
;; disable selective numbering ;;
;; disable selective numbering ;;   (setq window-numbering-assign-func
;; disable selective numbering ;;         (lambda () (spacemacs//window-numbering-assign)))
;; disable selective numbering ;;
;; disable selective numbering ;;
;; (setq window-numbering-assign-func nil)
)

winner-mode

[2017-09-19 Tue 12:50]

EmacsWiki: Winner Mode

Winner Mode is a global minor mode. When activated, it allows you to “undo” (and “redo”) changes in the window configuration with the key commands ‘C-c left’ and ‘C-c right’

(when (fboundp 'winner-mode)
     (winner-mode 1))

tab bar

EmacsWiki: Tab Bar Mode

(use-package tabbar
  :config
                                        ; turn on the tabbar
  (tabbar-mode -1)
  ;; (setq tabbar-use-images nil)
  (setq tabbar-use-images nil)
                                        ; define all tabs to be one of 3 possible groups: “Emacs Buffer”, “Dired”,
                                        ;“User Buffer”.

  (global-set-key [M-s-left] 'tabbar-backward)
  (global-set-key [M-s-right] 'tabbar-forward)

  (defun tabbar-buffer-groups ()
    "Return the list of group names the current buffer belongs to.
This function is a custom function for tabbar-mode's tabbar-buffer-groups.
This function group all buffers into 3 groups:
Those Dired, those user buffer, and those emacs buffer.
Emacs buffer are those starting with “*”."
    (list
     (cond
      ((eq major-mode 'dired-mode)
       "Dired"
       )
      ((or (eq major-mode 'web-mode)
           (eq major-mode 'js2-mode))
       "Web-Mode"
       )
      ((or (eq major-mode 'org-mode)
           (eq major-mode 'org-agenda-mode))
       "Org-Mode"
       )
      ((string-equal "*" (substring (buffer-name) 0 1))
       "Emacs Buffer"
       )
      (t
       ;; "User Buffer"
       (if (and (stringp mode-name)
                ;; Take care of preserving the match-data because this
                ;; function is called when updating the header line.
                (save-match-data (string-match "[^ ]" mode-name)))
           mode-name
         (symbol-name major-mode))
       )
      )))

  (setq tabbar-buffer-groups-function 'tabbar-buffer-group)

  (setq tbbr-md "groups")
  (defun toggle-tabbar-mode ()
    "Toggles tabbar modes - all buffers vs. defined in the `tabbar-buffer-groups'."
    (interactive)
    (if (string= tbbr-md "groups")
        (progn ;; then
          (setq tabbar-buffer-groups-function
                (lambda ()
                  (list "All")))
          (setq tbbr-md "all"))
      (progn ;; else
        (setq tabbar-buffer-groups-function 'tabbar-buffer-groups)
        (setq tbbr-md "groups"))))

  ;; Sort tabbar buffers by name
  (defun tabbar-add-tab (tabset object &optional append_ignored)
    "Add to TABSET a tab with value OBJECT if there isn't one there yet.
 If the tab is added, it is added at the beginning of the tab list,
 unless the optional argument APPEND is non-nil, in which case it is
 added at the end."
    (let ((tabs (tabbar-tabs tabset)))
      (if (tabbar-get-tab object tabset)
          tabs
        (let ((tab (tabbar-make-tab object tabset)))
          (tabbar-set-template tabset nil)
          (set tabset (sort (cons tab tabs)
                            (lambda (a b) (string< (buffer-name (car a)) (buffer-name (car b))))))))))

  ;; Add a buffer modification state indicator in the label
  ;; Add a buffer modification state indicator in the tab label, and place a
  ;; space around the label to make it looks less crowd.
  (defadvice tabbar-buffer-tab-label (after fixup_tab_label_space_and_flag activate)
    (setq ad-return-value
          (if (and (buffer-modified-p (tabbar-tab-value tab))
                   (buffer-file-name (tabbar-tab-value tab)))
              (concat " * " (concat ad-return-value " "))
            (concat " " (concat ad-return-value " ")))))

  ;; Called each time the modification state of the buffer changed.
  (defun ztl-modification-state-change ()
    (tabbar-set-template tabbar-current-tabset nil)
    (tabbar-display-update))

  ;; First-change-hook is called BEFORE the change is made.
  (defun ztl-on-buffer-modification ()
    (set-buffer-modified-p t)
    (ztl-modification-state-change))
  (add-hook 'after-save-hook 'ztl-modification-state-change)

  ;; This doesn't work for revert, I don't know.
  ;;(add-hook 'after-revert-hook 'ztl-modification-state-change)
  (add-hook 'first-change-hook 'ztl-on-buffer-modification)

  )

настройки поиска

;; настраиваем ignorecase
;; (toggle-case-fold-search)
(setq case-fold-search t)
(setq helm-case-fold-search t)
;;отключаем умную замену в "поиске и замене"
(setq case-replace nil)

Поиск по шаблонам регулярных выражений более актуален в качестве поиска по-умолчанию.

(global-set-key (kbd "C-s") #'isearch-forward-regexp)
(global-set-key (kbd "C-r") #'isearch-backward-regexp)
(global-set-key (kbd "C-M-s") #'isearch-forward)
(global-set-key (kbd "C-M-r") #'isearch-backward)
(global-set-key (kbd "C-M-%") #'query-replace)
(global-set-key (kbd "M-%") #'query-replace-regexp)

выделение

Настройка поведения редактора “как в Windows”

;;No region when it is not highlighted
(transient-mark-mode 1)
(setq org-support-shift-select 't)
(setq shift-select-mode t)

проверка орфографии

;;используем установленный hunspell
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(use-package ispell)
(setq ispell-program-name (executable-find "hunspell"))
;;;;выбор словаря по умолчанию
;;;;в windows эта строка обязательна
										;(setenv "LANG" "ru_RU")
;;(setenv "LANG" "ru_RU_yo")

(add-to-list 'ispell-dictionary-alist '(("russian"
										 "[АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЫЪЭЮЯабвгдеёжзийклмнопрстуфхцчшщьыъэюя]"
										 "[^АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЫЪЭЮЯабвгдеёжзийклмнопрстуфхцчшщьыъэюя]"
                                         "[']"
										 nil
                                         ("-d" "ru_RU_yo")
                                         t
                                         utf-8)
                                        ("english"
                                         "[[:alpha:]]"
                                         "[^[:alpha:]]"
                                         "[']"
										 t
										 ("-d" "en_US")
										 nil
										 utf-8)))

server-mode

(setq server-auth-dir "~/.emacs.d/emacsserver/")
;; (setq server-socket-dir "~/.emacs.d/emacsserver/")
(server-start)

;; (setq server-use-tcp t)

Настройка печати

печатаем на принтер по умолчанию через notepad.exe Use Notepad to print plain text files to the default Windows printer

(setq lpr-command "notepad")
(setq lpr-headers-switches '("/p"))    ; \ mis-use these
(setq lpr-switches nil)                ; / two variables
(setq printer-name nil); notepad takes the default
(setq lpr-printer-switch "/P") ;; run notepad as batch printer

локализация

локализуем функции даты-времени.

from http://thenybble.de/

;;;; Локализация

;;the below breaks gnus. The problem is that message-make-date, which actually shouldn't be localized, uses parse-time-weekdays and parse-time-months, which are localized. So, some more work is needed, along the lines of this:

(use-package parse-time)
(require 'message)

;; Do this before setting the variables  correctly.
(setq parse-time-months-unlocalized parse-time-months)
(setq parse-time-weekdays-unlocalized parse-time-weekdays)

(mapc (lambda (x) (add-to-list 'parse-time-months x))
      '(("янв" . 1) ("фев" . 2) ("мар" . 3) ("апр" . 4)
      ("май" . 5) ("мая" . 5) ("июн" . 6) ("июл" . 7)
      ("авг" . 8) ("сен" . 9) ("окт" . 10) ("ноя" . 11) ("дек" . 12)
	  ("январь" . 1) ("февраль" . 2) ("март" . 3) ("апрель" . 4)
	  ("января" . 1) ("февраля" . 2) ("марта" . 3) ("апреля" . 4)
      ("июнь" . 6) ("июня" . 6) ("июль" . 7) ("июля" . 7)
	  ("август" . 8) ("августа" . 8) ("сентябрь" . 9) ("сентября" . 9)
      ("октябрь" . 10) ("ноябрь" . 11) ("декабрь" . 12)
	  ("октября" . 10) ("ноября" . 11) ("декабря" . 12)))

(mapc (lambda (x) (add-to-list 'parse-time-weekdays x))
	  '(("пн" . 1) ("пон" . 1) ("вт" . 2) ("ср" . 3) ("чт" . 4) ("пт" . 5)
		("сб" . 6) ("вс" . 0) ("понедельник" . 1) ("вторник" . 2)
		("среда" . 3) ("среду" . 3) ("четверг" . 4) ("пятница" . 5)
		("пятницу" . 5) ("суббота" . 6) ("субботу" . 6) ("воскресенье" . 0)))


(defun message-make-date-localized (&optional now)
  "Make a valid data header. Uses localized values from parse-time.el. If NOW, use that time instead."
  (let* ((now (or now (current-time)))
         (zone (nth 8 (decode-time now)))
         (sign "+"))
    (when (< zone 0)
      (setq sign "-")
      (setq zone (- zone)))
    (concat
     ;; The day name of the %a spec is locale-specific.  Pfff.
     (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
                                             parse-time-weekdays))))
     (format-time-string "%d" now)
     ;; The month name of the %b spec is locale-specific.  Pfff.
     (format " %s "
             (capitalize (car (rassoc (nth 4 (decode-time now))
                                      parse-time-months))))
     (format-time-string "%Y %H:%M:%S " now)
     ;; We do all of this because XEmacs doesn't have the %z spec.
     (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))

(defun message-make-date-unlocalized (&optional now)
  (let ((parse-time-weekdays parse-time-weekdays-unlocalized)
        (parse-time-months parse-time-months-unlocalized))
    (message-make-date now)))

;(defalias 'message-make-date message-make-date-unlocalized)
;; локализуем функции даты-времени. from http://thenybble.de/

переключалка

(global-unset-key (kbd "M-SPC"))
(global-set-key (kbd "M-SPC") 'toggle-input-method)

(define-key isearch-mode-map (kbd "M-SPC") 'toggle-input-method)

reverse-im

[2017-10-03 Tue 13:33]

https://github.com/a13/reverse-im.el

linux hacks

;; (define-key isearch-mode-map [?\s-/] 'isearch-toggle-input-method)
;; (define-key isearch-mode-map (kbd "M-SPC") 'isearch-toggle-input-method)
;; (setf (gethash #xfe08 x-keysym-table) (aref (kbd "M-SPC") 0))

(if (eq system-type 'gnu/linux)
	(progn
	  (defun linux_iso_next_group_hack()
		(interactive)
		(message "function linux_iso_next_group_hack: method was %s" current-input-method)
		(toggle-input-method)
		;; (shell-command-to-string "/bin/bash ~/.emacs.d/switch_to_en.sh")
		;; (shell-command-to-string "/usr/bin/setxkbmap -layout \"us,ru\"")
		;; (shell-command "notify-send \"/usr/bin/setxkbmap -layout us,ru\"")
		;; (shell-command "~/bin/switch_layout_to_us")
		;; (call-process "~/bin/switch_layout_to_us")
		(shell-command-to-string "~/bin/switch_layout_to_us")
		(message "new method: %s" current-input-method)
		)

	  ;; (setf (gethash #xfe08 x-keysym-table) (aref (kbd "H-C-M-SPC") 0))
	  (global-set-key (kbd "H-C-M-SPC") 'linux_iso_next_group_hack)
	  (define-key isearch-mode-map (kbd "H-C-M-SPC") 'linux_iso_next_group_hack)
	  ))

;; recode keys ;; ;; http://stackoverflow.com/questions/10639429/emacs-linux-and-international-keyboard-layouts
;; recode keys ;; ;; USAGE:
;; recode keys ;; ;; Put in your .emacs:
;; recode keys ;; ;;
;; recode keys ;; ;; (translate-keystrokes-ru->en)
;; recode keys ;; ;; (add-hook 'text-mode-hook
;; recode keys ;; ;;           (lambda () (literal-insert-mode 1)))
;; recode keys ;; ;;
;; recode keys ;; ;; Only buffers with literal-insert-mode active will be sensitive to the
;; recode keys ;; ;; environment language. Prefixed keybindings will still be usable.
;; recode keys ;;
;; recode keys ;; (defun translate-keystrokes-ru->en ()
;; recode keys ;;   "Make emacs output english characters, regardless whether
;; recode keys ;; the OS keyboard is english or russian"
;; recode keys ;;   (flet ((make-key-stroke (prefix char)
;; recode keys ;;            (eval `(kbd ,(if (and (string-match "^C-" prefix)
;; recode keys ;;                                  (string-match "[A-Z]" (string char)))
;; recode keys ;;                             (concat "S-" prefix (string (downcase char)))
;; recode keys ;;                             (concat prefix (string char)))))))
;; recode keys ;;     (let ((case-fold-search nil)
;; recode keys ;;           (keys-pairs (mapcar* 'cons
;; recode keys ;;                                "йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖ\ЭЯЧСМИТЬБЮ№"
;; recode keys ;;                                "qwertyuiop[]asdfghjkl;'zxcvbnm,.QWERTYUIOP{}ASDFGHJKL:\"ZXCVBNM<>#"))
;; recode keys ;;           (prefixes '(""    "s-"    "M-"    "M-s-"
;; recode keys ;;                       "C-"  "C-s-"  "C-M-"  "C-M-s-")))
;; recode keys ;;       (mapc (lambda (prefix)
;; recode keys ;;               (mapc (lambda (pair)
;; recode keys ;;                       (define-key key-translation-map
;; recode keys ;;                           (make-key-stroke prefix (car pair))
;; recode keys ;;                         (make-key-stroke prefix (cdr pair))))
;; recode keys ;;                     keys-pairs))
;; recode keys ;;             prefixes))))
;; recode keys ;;
;; recode keys ;; (defun literal-insert ()
;; recode keys ;;   (interactive)
;; recode keys ;;   (insert-char last-input-event 1))
;; recode keys ;;
;; recode keys ;; (define-minor-mode literal-insert-mode
;; recode keys ;;     "Make emacs output characters corresponging to the OS keyboard,
;; recode keys ;;  ignoring the key-translation-map"
;; recode keys ;;   :keymap (let ((new-map (make-sparse-keymap))
;; recode keys ;;                 (english-chars "qwertyuiop[]asdfghjkl;'zxcvbnm,.QWERTYUIOP{}ASDFGHJKL:\"ZXCVBNM<>#"))
;; recode keys ;;             (mapc (lambda (char)
;; recode keys ;;                     (define-key new-map (string char)
;; recode keys ;;                       'literal-insert))
;; recode keys ;;                   english-chars)
;; recode keys ;;             new-map))
;; recode keys ;;
;; recode keys ;; (translate-keystrokes-ru->en)
;; recode keys ;; (add-hook 'text-mode-hook
;; recode keys ;;           (lambda () (literal-insert-mode 1)))
;; recode keys ;;
;; recode keys ;; ;; http://stackoverflow.com/questions/16048231/how-to-enable-a-non-global-minor-mode-by-default-on-emacs-startup
;; recode keys ;; ;; (define-globalized-minor-mode my-global-literal-insert-mode literal-insert-mode
;; recode keys ;;   ;; (lambda () (literal-insert-mode 1)))
;; recode keys ;; ;; (my-global-literal-insert-mode 1)


;;20-01-16;; ;;http://ru-emacs.livejournal.com/78130.html
;;20-01-16;; ;; Проблема «не ловит переключалку» как минимум в современном емаксе решается так:
;;20-01-16;; ;; (setf (gethash #xfe08 x-keysym-table) (kbd "s-x"))
;;20-01-16;; ;;(setf (gethash #xfe08 x-keysym-table) (aref (kbd "M-SPC") 0))
;;20-01-16;;
;;20-01-16;; ;; ---- Правильный вариант конфига через xxkb ----
;;20-01-16;; ;; По поводу xxkb, вот такой у меня .xxkbrc:
;;20-01-16;; ;; XXkb.mainwindow.enable: no
;;20-01-16;; ;; XXkb.button.enable: yes
;;20-01-16;; ;; XXkb.controls.add_when_change: yes
;;20-01-16;; ;; XXkb.controls.focusout: yes
;;20-01-16;; ;; XXkb.app_list.wm_class_class.alt_group1: *emacs* *Emacs*
;;20-01-16;;
;;20-01-16;;
;;20-01-16;; ;; (if (eq system-type 'gnu/linux)
;;20-01-16;; 	;; (progn
;;20-01-16;;
;;20-01-16;; (defun linux_iso_next_group_hack()
;;20-01-16;;   (interactive)
;;20-01-16;;
;;20-01-16;;   ;; (if (equal current-input-method nil)
;;20-01-16;;   ;; 	  (set-input-method "russian-computer") ;(toggle-input-method)
;;20-01-16;;   ;; 	(set-input-method nil) ;;(toggle-input-method)
;;20-01-16;;   ;; 	)
;;20-01-16;;   ;; (message "%s" current-input-method)
;;20-01-16;;   ;;(shell-command-to-string "~/.emacs.d/switch_layout_to_us")
;;20-01-16;;   (shell-command "~/.emacs.d/switch_layout_to_us")
;;20-01-16;;   (message "function linux_iso_next_group_hack: %s" current-input-method)
;;20-01-16;;   (toggle-input-method)
;;20-01-16;;   )
;;20-01-16;;
;;20-01-16;; (setf (gethash #xfe08 x-keysym-table) (aref (kbd "H-C-M-SPC") 0))
;;20-01-16;; (global-set-key (kbd "H-C-M-SPC") 'linux_iso_next_group_hack)
;;20-01-16;; (global-set-key (kbd "s-SPC") 'linux_iso_next_group_hack)
;;20-01-16;; ;;(linux_iso_next_group_hack)
;;20-01-16;; ;; ))
;;20-01-16;;
;;20-01-16;; (global-unset-key (kbd "M-SPC"))
;;20-01-16;; (if (eq system-type 'gnu/linux)
;;20-01-16;; 	(progn
;;20-01-16;; 	  (global-set-key (kbd "M-SPC") 'linux_iso_next_group_hack)
;;20-01-16;; 	  (define-key helm-map (kbd "M-SPC") 'linux_iso_next_group_hack))
;;20-01-16;;   (progn
;;20-01-16;; 	(global-set-key (kbd "M-SPC") 'toggle-input-method)
;;20-01-16;; 	(define-key helm-map (kbd "M-SPC") 'toggle-input-method)
;;20-01-16;; 	))
;;20-01-16;;

punto-switcher

;; RECODE ENGLISH TO RUSSIAN ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; punto switcher
;; rus<->lat перекодировка
;; К сожалению не помню автора :(
;; Иногда начинаешь набирать текст, забыв переключить регистр - очень обидно
;; M^x rus<->lat и M^x lat<->rus поможет этому горю
;;
(use-package cl)
;; http://www.emacswiki.org/emacs/%D0%9F%D0%B5%D1%80%D0%B5%D0%BA%D0%BE%D0%B4%D0%B8%D1%80%D0%BE%D0%B2%D0%BA%D0%B0%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%BE%D0%B3%D0%BE%D0%A2%D0%B5%D0%BA%D1%81%D1%82%D0%B0
(defvar usr:*en/ru-table* '((?q . ) (?w . ) (?e . ) (?r . )
                            (?t . ) (?y . ) (?u . ) (?i . )
                            (?o . ) (?p . ) (?\[ . ) (?\] . )
                            (?a . ) (?s . ) (?d . ) (?f . )
                            (?g . ?п) (?h . ) (?j . ) (?k . )
                            (?l . ) (?\; . ) (?' . ) (?z . )
                            (?x . ) (?c . ) (?v . ) (?b . )
                            (?n . ) (?m . ) (?, . ) (?. . )
                            (?Q . ) (?W . ) (?E . ) (?R . )
                            (?T . ) (?Y . ) (?U . ) (?I . )
                            (?O . ) (?P . ) (?{ . ) (?} . )
                            (?A . ) (?S . ) (?D . ) (?F . )
                            (?G . ) (?H . ) (?J . ) (?K . )
                            (?L . ) (?: . ) (?\" . ) (?Z . )
                            (?X . ) (?C . ) (?V . ) (?B. )
                            (?N . ) (?M . ) (?< . ) (?> . )
							(?\\ . ) (?| . )
                            (?` . ) (?~ . ) (?@ . ?\") (?# . ?\')
                            (?$ . ?*) (?% . ?:) (?? . ?,) (?/ . ?.)
                            (?* . ?\;)))
;; (assoc ?\[ usr:*en/ru-table*)
;; (rassoc ?х usr:*en/ru-table*)
;; ?х ?\[
;; \;br

(defun lat<->rus (beg end &optional arg)
  "Recode region that contains russain text typed in english into russian. With
ARG given recode region in the other direction."
  (interactive "*r\nP")
  (save-excursion
	(goto-char beg)
    (do () ((>= (point) end))
        (let* ((en-char (char-after (point)))
               (ru-char (if arg
                            (car (rassoc en-char usr:*en/ru-table*))
                          (cdr (assoc en-char usr:*en/ru-table*)))))
          (delete-char 1)
          (insert (if ru-char ru-char en-char))))))

(defun rus<->lat (beg end &optional arg)
  "Recode region that contains russain text typed in russian into enflish. With
ARG given recode region in the other direction."
  (interactive "*r\nP")
  (save-excursion
    (goto-char beg)
    (do () ((>= (point) end))
    (let* ((en-char (char-after (point)))
           (ru-char (if arg
                       (cdr (assoc en-char usr:*en/ru-table*))
                       (car (rassoc en-char usr:*en/ru-table*)))))
          (delete-char 1)
          (insert (if ru-char ru-char en-char))))))

(transient-mark-mode 1)
;; - используем не (line-beginning-position) а (org-beginning-of-line &optional ARG)
;; major-mode 'org-mode

(defun fix-wrong-input-method-on-line-and-toggle-input-method ()
  "fix wrong input method and toggle input method on entire line"
  (interactive)
  (if (equal current-input-method nil)
      (progn    ;; мы писали по русски на английской раскладке
		(if (eq major-mode 'org-mode)
			(progn
			  (org-beginning-of-line)
			  (lat<->rus (point) (line-end-position))
			  (end-of-line)
			  )
		  (progn
			(lat<->rus (line-beginning-position) (line-end-position))
			(end-of-line)))
	   (set-input-method russian-input-method) ;(toggle-input-method)
	   )
	  (progn ;; мы писали по английски на русской раскладке
		(if (eq major-mode 'org-mode)
			(progn
			  (org-beginning-of-line)
			  (rus<->lat (point) (line-end-position))
			  (end-of-line))
		  (progn
			(rus<->lat (line-beginning-position) (line-end-position))
			(end-of-line)))
	   (set-input-method nil) ;;(toggle-input-method)
	   )
  ))

(defun fix-wrong-input-method-and-toggle-input-method ()
  "fix wrong input method and toggle input method"
  (interactive)
   (setq temp-point (point))
   (if (equal current-input-method nil)
	   (progn    ;; мы писали по русски на английской раскладке
		 (if mark-active
			 (lat<->rus (region-beginning) (region-end))
		   (progn
			 (set-mark (point))
			 (evil-backward-WORD-begin)
			 (lat<->rus (region-beginning) (region-end))))
	     (set-input-method russian-input-method) ;(toggle-input-method)
	   )
	 (progn ;; мы писали по английски на русской раскладке
		 (if mark-active
			 (lat<->rus (region-beginning) (region-end))
		   (progn
			 (set-mark (point))
			 (evil-backward-WORD-begin)
			 (rus<->lat (region-beginning) (region-end))))
	     (set-input-method nil) ;;(toggle-input-method)
	   ))
   (goto-char temp-point)
   )
;; (global-set-key (kbd "<C-pause>") 'fix-wrong-input-method-on-line-and-toggle-input-method)
;; (global-set-key (kbd "M-C") 'fix-wrong-input-method-on-line-and-toggle-input-method)
;; (global-set-key (kbd "C-M-c")       'fix-wrong-input-method-and-toggle-input-method)
;; (global-set-key (kbd "s-v") 'fix-wrong-input-method-on-line-and-toggle-input-method)
;; (global-set-key (kbd "s-c")       'fix-wrong-input-method-and-toggle-input-method)
;; (global-set-key (kbd "<pause>")   'fix-wrong-input-method-and-toggle-input-method)
;; ;; (global-set-key (kbd "M-c")       'toggle-input-method)
;; ;;(global-set-key (kbd "<C-pause>") 'rus<->lat)
;; ;;(global-set-key (kbd "<C-M-pause>") 'lat<->rus)

global keymappings

(global-set-key (kbd "<kp-subtract>") 'scroll-down-line)
(global-set-key (kbd "<kp-add>") 'scroll-up-line)
;; По Ctrl-F12 переключаемся в fulscreen
(global-set-key (kbd "<C-f12>") 'toggle-frame-fullscreen)
;;по shift-f1 изменяем состояние максимизации
(global-set-key (kbd "<S-f1>") '(lambda () (interactive)(toggle-frame-maximized)))
;;по Ctrl-f3 открываем окно в новом фрейме
(global-set-key (kbd "<s-f3>") '(lambda () (interactive)(make-frame-command)))
(global-set-key (kbd "<M-s-f3>") '(lambda () (interactive)(make-frame-command)))
;;по shift-f3 закрываем текущий фрейм
(global-set-key (kbd "<S-f3>") '(lambda () (interactive)(delete-frame)))


;; H-backspace это delete
(global-set-key (kbd "<H-backspace>") #'delete-forward-char)

(global-set-key (kbd "<C-M-backspace>") '(lambda () (interactive)(kill-word 1)(delete-forward-char 1)))
(global-set-key (kbd "<M-backspace>") 'backward-kill-word)

(global-set-key (kbd "<C-f2>") 'bs-show)
(global-set-key (kbd "<M-f2>") 'ido-switch-buffer)
(global-set-key (kbd "<f2>") 'save-buffer)


;;; Перемещение по буферам
;;
;; Следующий буфер (global-unset-key (kbd "M-q")) (global-set-key (kbd "s-q") 'fill-paragraph)
(global-set-key (kbd "M-q") 'other-window)
;; (global-set-key (kbd "M-q") 'fill-paragraph)
;;(global-set-key [M-C-left] 'windmove-left) (global-set-key [M-C-right] 'windmove-right)
;;(global-set-key [M-C-up] 'windmove-up) (global-set-key [M-C-down] 'windmove-down)

(global-set-key [s-tab]  'next-multiframe-window)
(global-set-key (kbd "M-`") 'other-frame)
(global-set-key (kbd "M-\\") 'other-frame)

(global-set-key (kbd "C-j") 'newline)
(define-key isearch-mode-map (kbd "C-j") (kbd "<return>"))

(global-set-key (kbd "<M-f3>") '(lambda () (interactive)(toggle-word-wrap 1)(toggle-truncate-lines)))

;; map esc to ctrl-g
;; https://www.emacswiki.org/emacs/CancelingInEmacs
;; (define-key isearch-mode-map [escape] 'isearch-abort)   ;; isearch
;; (define-key isearch-mode-map "\e" 'isearch-abort)   ;; \e seems to work better for terminals
;; (global-set-key [escape] 'keyboard-escape-quit)         ;; everywhere else

(define-key key-translation-map (kbd "ESC") (kbd "C-g"))


(global-set-key (kbd "C-M-P") 'scroll-down-command)
(global-set-key (kbd "C-M-;") 'scroll-up-command)
(global-set-key (kbd "<s-up>") 'scroll-down-command)
(global-set-key (kbd "<s-down>") 'scroll-up-command)
(global-set-key (kbd "<H-up>") 'scroll-down)
(global-set-key (kbd "<H-down>") 'scroll-up)

;; (setq viper-mode nil)
;; (use-package viper)
;; (global-set-key (kbd "M-f") 'viper-forward-word)
;; (global-set-key (kbd "M-b") 'viper-backward-word)

(global-set-key (kbd "<home>") 'beginning-of-line)
(global-set-key (kbd "<end>") 'end-of-line)
(global-set-key (kbd "<H-left>") 'beginning-of-line)
(global-set-key (kbd "<H-right>") 'end-of-line)
(global-set-key (kbd "<C-home>") 'beginning-of-buffer)
(global-set-key (kbd "<C-end>") 'end-of-buffer)


(global-set-key [f1]    'help)

C-a normally moves us to the beginning of the line unconditionally with move-beginning-of-line. This version is more useful, as it moves to the first non-whitespace character if we’re already at the beginning of the line. Repeated use of `C-a’ toggles between these two positions.

(defun beginning-of-line-dwim ()
  "Toggles between moving point to the first non-whitespace character, and
  the start of the line."
  (interactive)
  (let ((start-position (point)))
    ;; Move to the first non-whitespace character.
    (back-to-indentation)

    ;; If we haven't moved position, go to start of the line.
    (when (= (point) start-position)
      (move-beginning-of-line nil))))

(global-set-key (kbd "C-a") 'beginning-of-line-dwim)

kill other window via “C-x K” and evil leader “SPC D”

(defun other-window-kill-buffer ()
  "Kill the buffer in the other window"
  (interactive)
  ;; Window selection is used because point goes to a different window
  ;; if more than 2 windows are present
  (let ((win-curr (selected-window))
        (win-other (next-window)))
    (select-window win-other)
    (kill-this-buffer)
    (select-window win-curr)))
(global-set-key (kbd "C-x K") 'other-window-kill-buffer)

(global-set-key (kbd "<C-pause>") 'fix-wrong-input-method-on-line-and-toggle-input-method)
(global-set-key (kbd "M-C") 'fix-wrong-input-method-on-line-and-toggle-input-method)
(global-set-key (kbd "C-M-c")       'fix-wrong-input-method-and-toggle-input-method)
(global-set-key (kbd "s-v") 'fix-wrong-input-method-on-line-and-toggle-input-method)
(global-set-key (kbd "s-c")       'fix-wrong-input-method-and-toggle-input-method)
(global-set-key (kbd "<pause>")   'fix-wrong-input-method-and-toggle-input-method)

(define-key global-map (kbd "C-<f7>") '(lambda () (interactive)(flush-lines "^$")))

низкоуровневые хаки

перекомпилляция

Перекомпиллируем все el, у которых устарели elc

(setq load-prefer-newer t)
;; ;; (add-to-list 'load-path "/path/to/auto-compile")
;; (require 'auto-compile)
;; (auto-compile-on-load-mode 1)
;; (auto-compile-on-save-mode 1)

запрет редактирования служебной части в minibuffer

http://ergoemacs.org/emacs/emacs_stop_cursor_enter_prompt.html

(setq minibuffer-prompt-properties '(read-only t point-entered minibuffer-avoid-prompt face minibuffer-prompt))

Сохраняем состояние редактора при выходе.

Для включения надо раскомментировать ;;(desktop-save-mode t)

;; save all on exit
(setq desktop-dirname "~/.emacs.d/")
;;(setq desktop-base-file-name ".emacs.desktop")
;;(desktop-save-mode t)

Прибиваем все процессы при выходе

[2017-10-26 Thu 17:00]

(defadvice yes-or-no-p (around hack-exit (prompt))
  (if (string= prompt "Active processes exist; kill them and exit anyway? ")
      t
    ad-do-it))

пакеты

Recent files (recentf)

;;Recent files in menu http://www.emacswiki.org/emacs/RecentFiles
(use-package recentf
  :config
  (setq recentf-auto-cleanup 600 ;'never
	recentf-max-saved-items 200
	recentf-max-menu-items 15)
  (recentf-mode 1)
  )

undo и undo-tree

;; increase undo limits
(setq undo-limit 10000000)
(setq undo-strong-limit 15000000)
(setq undo-outer-limit 20000000)
;; (setq evil-want-fine-undo 'fine)
(setq evil-want-fine-undo 'Yes)

;;; https://stackoverflow.com/a/41560712/2112489
;;; [[https://www.reddit.com/r/emacs/comments/6ol9rn/how_to_increase_granularity_of_undo/][How to increase granularity of undo? : emacs]]
(advice-add 'undo-auto--last-boundary-amalgamating-number :override #'ignore)

(use-package undo-tree
  :config
  ;; Remember undo history
  (setq
   undo-tree-auto-save-history t
   undo-tree-history-directory-alist `(("." . ,(concat emacs-tmp-dir "/undo/")))
   undo-tree-visualizer-timestamps t
   undo-tree-visualizer-diff t
   )
  (global-undo-tree-mode 1)

  :bind (
         ("M-z" . undo-tree-undo) ;; make ctrl-z undo
         ("C-z" . undo-tree-undo)
         ;; (defalias 'redo 'undo-tree-redo)
         ("C-M-z" . undo-tree-redo) ;; make ctrl-Z redo
         )

  )

quick jumps

avy mode

;; avy: https://github.com/abo-abo/avy
;; https://github.com/louy2/evil-avy
;; http://emacsredux.com/blog/2015/07/19/ace-jump-mode-is-dead-long-live-avy/
(use-package avy)

;; evil-snipe is successor
;; (use-package evil-avy)
;; (evil-avy-mode -1)
(global-set-key (kbd "C-c j") 'avy-goto-word-or-subword-1)
;; (global-set-key (kbd "s-.") 'avy-goto-word-or-subword-1)
;; (evil-make-overriding-map org-agenda-mode-map 'normal)

;; (defun evil-avy-find-char-check-agenda-mode (orig-fun &rest args)
;;   (if (equal major-mode 'org-agenda-mode)
;;       (org-agenda-todo)
;;     (apply orig-fun args)))
;; (advice-add 'evil-avy-find-char :around 'evil-avy-find-char-check-agenda-mode)

;; (defun evil-avy-find-char-to-check-agenda-mode (orig-fun &rest args)
;;   (if (equal major-mode 'org-agenda-mode)
;;       (org-agenda-filter-by-tag)
;;     (apply orig-fun args)))
;; (advice-add 'evil-avy-find-char-to :around 'evil-avy-find-char-check-agenda-mode)

;; evil-avy-find-char-to

ace-jump-mode LOAD BEFORE EVIL MODE!!!!!

;;;; AceJump package
;;                  http://www.emacswiki.org/emacs/AceJump
;;                  https://github.com/winterTTr/ace-jump-mode/wiki
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; replacement: https://github.com/abo-abo/avy
(use-package ace-jump-mode)
;; (setq ace-jump-mode-scope 'global) ;; global, frame, visible, window
(setq ace-jump-mode-scope 'visible) ;; global, frame, visible, window
;;avy;; ;; config from https://github.com/winterTTr/ace-jump-mode/wiki
;;avy;;
;;avy;; (autoload 'ace-jump-mode "ace-jump-mode" "Emacs quick move minor mode" t)
;;avy;;
;;avy;; (define-key global-map (kbd "C-.") 'ace-jump-mode)
;;avy;; ;;(define-key global-map (kbd "C-.") 'ace-jump-word-mode)
;;avy;; ;;
;;avy;; ;; enable a more powerful jump back function from ace jump mode
;;avy;; ;;
;;avy;; (autoload 'ace-jump-mode-pop-mark "ace-jump-mode" "Ace jump back:-)" t)
;;avy;; (eval-after-load "ace-jump-mode" '(ace-jump-mode-enable-mark-sync))
;;avy;;
;;avy;; ;;(define-key global-map (kbd "C-x SPC") 'ace-jump-mode-pop-mark)
;;avy;; (define-key global-map (kbd "C-,") 'ace-jump-mode-pop-mark)
;;avy;; ;; How do I use it?
;;avy;; ;; If you use the default configuration, which binds to “C-c SPC”.
;;avy;; ;;
;;avy;; ;; “C-c SPC” ⇒ ace-jump-word-mode
;;avy;; ;;   enter first char of a word, select the highlight key to move to.
;;avy;; ;; “C-u C-c SPC” ⇒ ace-jump-char-mode
;;avy;; ;;   enter a char for query, select the highlight key to move to.
;;avy;; ;; “C-u C-u C-c SPC” ⇒ ace-jump-line-mode
;;avy;; ;;   each non-empty line will be marked, select the highlight key to move to.
;;avy;;
;;avy;; (define-key org-mode-map (kbd "C-,") 'ace-jump-mode-pop-mark)
;;avy;; ;; (defun bss/remap-org-mode-keys ()
;;avy;; ;;   (local-unset-key (kbd "C-,")) ;;disable local C-, key mapping
;;avy;; ;;   (define-key org-mode-map (kbd "C-,") 'ace-jump-mode-pop-mark)
;;avy;; ;;   )
;;avy;; ;; (eval-after-load "org" '(bss/remap-org-mode-keys))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;(use-package ace-jump-helm-line)
;;(eval-after-load "helm" '(define-key helm-map (kbd "C-'") 'ace-jump-helm-line))

;;testing-testing
;; (defadvice split-window (after move-point-to-new-window activate)
;;   "Moves the point to the newly created window after splitting."
;;   (other-window 1))

ace-window (disabled)

;;;; Ace-window plugin
;; https://github.com/abo-abo/ace-window
;; You can swap windows by calling ace-window with a prefix argument C-u.
;; You can delete the selected window by calling ace-window with a double prefix argument, i.e. C-u C-u.

(use-package ace-window
  :disabled t
  :config
  (global-unset-key (kbd "M-p"))
  (global-set-key (kbd "M-p") 'ace-window)
  (define-key shell-mode-map (kbd "M-p") 'ace-window)

  (setq aw-keys '(?a ?s ?d ?f ?g ?h ?j ?k ?l))
  ;; (setq aw-background nil)
  (setq aw-scope 'frame) ;; 'global for multiframe

  (setq aw-dispatch-alist
        '((?x aw-delete-window " Ace - Delete Window")
          (?s aw-swap-window " Ace - Swap Window")
          (?n aw-flip-window)
          (?v aw-split-window-vert " Ace - Split Vert Window")
          (?h aw-split-window-horz " Ace - Split Horz Window")
          (?i delete-other-windows " Ace - Maximize Window (select which window)")
          (?o delete-other-windows)
          (?b balance-windows)
          ))

  )

ace-link

;; ace-link: https://github.com/abo-abo/ace-link
(use-package ace-link)
(ace-link-setup-default "[")
;; default-key is o, in org we remap it to M-[
(define-key org-mode-map (kbd "M-[") 'ace-link-org)
;; (global-set-key (kbd "M-[") 'ace-link-addr)

goto-chg

;; (use-package goto-chg)

;; (global-set-key (kbd "s-.") 'goto-last-change)
;; (global-set-key (kbd "s-,") 'goto-last-change-reverse)

dumb-jump

[2017-04-30 Sun 00:02]

GitHub - jacktasia/dumb-jump: an Emacs "jump to definition" package

(use-package dumb-jump
  :bind (("M-g o" . dumb-jump-go-other-window)
         ("M-g b" . dumb-jump-back)
         ("M-g q" . dumb-jump-quick-look)
         ("M-g j" . dumb-jump-go)
         ("M-g x" . dumb-jump-go-prefer-external)
         ("M-g z" . dumb-jump-go-prefer-external-other-window))
  :config
  ;; (setq dumb-jump-selector 'ivy)
  (setq dumb-jump-selector 'helm)
  (add-hook 'python-mode-hook 'dumb-jump-mode)

  :ensure t
  )

evil-mode

evil-init

;; EVIL mode
;; https://bitbucket.org/lyro/evil/wiki/Home
(use-package evil)
(evil-mode 1)

buffer-modes

(loop for (mode . state) in '((inferior-emacs-lisp-mode . emacs)
                              (nrepl-mode . insert)
                              (pylookup-mode . emacs)
                              (chronos-mode . emacs)
                              (comint-mode . normal)
                              (shell-mode . insert)
                              (eshell-mode . emacs)
                              (git-commit-mode . insert)
                              (git-rebase-mode . emacs)
                              (term-mode . emacs)
                              (image-mode . emacs)
                              (help-mode . motion)
                              (helm-grep-mode . emacs)
                              (grep-mode . emacs)
                              (bc-menu-mode . emacs)
                              (elfeed-show-mode . emacs)
                              (elfeed-search-mode . emacs)
                              (rdictcc-buffer-mode . emacs)
                              (dired-mode . emacs)
                              (image-dired-thumbnail-mode . emacs)
                              (ztree-mode . emacs)
                              (ctbl:table-mode . emacs)
                              (edbi:sql-mode . emacs)
                              (diff-mode . emacs)
							  (vc-svn-log-view-mode . emacs)
                              (wdired-mode . normal))
      do (evil-set-initial-state mode state))

(push '("\\*CAPTURE-\\*" . insert) evil-buffer-regexps)
(push '("\\*help\\*" . motion) evil-buffer-regexps)
(push '("\\*Keys\\*" . emacs) evil-buffer-regexps)
(push '("\\*magit\\*" . emacs) evil-buffer-regexps)
(push '("\\*Django\\*" . emacs) evil-buffer-regexps)

;; (add-hook 'after-change-major-mode-hook
;;           '(lambda ()
;;              (evil-mode (if (or (equal major-mode 'magit-log-mode) (equal major-mode 'magit-popup-mode) (equal major-mode 'magit-status-mode)(equal major-mode 'magit-mode)) 0 1))))
;;              ;; (evil-mode (if (or (equal major-mode 'text-mode) (equal major-mode 'magit-log-mode) (equal major-mode 'magit-popup-mode) (equal major-mode 'magit-status-mode)(equal major-mode 'magit-mode)) 0 1))))

(push '("\\*chronos\\*" . emacs) evil-buffer-regexps)
(push '("\\*eshell\\*" . emacs) evil-buffer-regexps)
(push '("\\*backtrace\\*" . emacs) evil-buffer-regexps)
(push '("\\*org-goto\\*" . emacs) evil-buffer-regexps)
(push '("\\*vc-\\*" . insert) evil-buffer-regexps)
(push '("\\*edbi-dbviewer\\*" . emacs) evil-buffer-regexps)
(push '("\\*edbi-dbviewer-table\\*" . emacs) evil-buffer-regexps)

evil settings

;; evil settings
(setq evil-emacs-state-cursor '("red" box))
(setq evil-normal-state-cursor '("green" box))
(setq evil-visual-state-cursor '("orange" box))
(setq evil-insert-state-cursor '("red" bar))
(setq evil-replace-state-cursor '("red" bar))
(setq evil-operator-state-cursor '("red" hollow))
(setq evil-search-wrap t
      evil-regexp-search t
      evil-shift-width 4
      evil-want-C-i-jump t
      evil-want-C-u-scroll t
      evil-complete-all-buffers nil
      evil-want-fine-undo nil
      ;; Don't wait for any other keys after escape is pressed.
      evil-esc-delay 0
      ;; Make horizontal movement cross lines
      evil-cross-lines t
      )

keymappings

;; disable unneeded evil-repeat-pop-next
;; (define-key evil-normal-state-map (kbd "M-.") 'evil-repeat-pop-next)
(define-key evil-normal-state-map (kbd "M-.") nil)



;; (use-package comment-dwim-2
;; :bind
;;    ("M-;" . comment-dwim-2)
;; )
;; settings from http://juanjoalvarez.net/es/detail/2014/sep/19/vim-emacsevil-chaotic-migration-guide/
;; (global-set-key (kbd "M-;") 'evilnc-comment-or-uncomment-lines)
;; (global-set-key (kbd "C-c l") 'evilnc-quick-comment-or-uncomment-to-the-line)
;; (global-set-key (kbd "C-c c") 'evilnc-copy-and-comment-lines)
;; (global-set-key (kbd "C-c p") 'evilnc-comment-or-uncomment-paragraphs)
(define-key evil-normal-state-map (kbd "<f4>") '(lambda () (interactive) (evilnc-comment-or-uncomment-lines 1)))
(define-key evil-insert-state-map (kbd "<f4>") '(lambda () (interactive) (evilnc-comment-or-uncomment-lines 1)))
;; (define-key evil-normal-state-map (kbd "<f4>") 'evilnc-comment-or-uncomment-lines)
;; (define-key evil-insert-state-map (kbd "<f4>") 'evilnc-comment-or-uncomment-lines)
(evil-define-key 'normal magit-mode-map
  "j" 'magit-goto-next-section
  "k" 'magit-goto-previous-section)
(evil-define-key 'normal magit-log-mode-map
  "j" 'magit-goto-next-section
  "k" 'magit-goto-previous-section)
(evil-define-key 'normal magit-diff-mode-map
  "j" 'magit-goto-next-section
  "k" 'magit-goto-previous-section)
;; Make HJKL keys work in special buffers
(evil-add-hjkl-bindings magit-branch-manager-mode-map 'emacs
  "K" 'magit-discard
  "L" 'magit-key-mode-popup-logging)
(evil-add-hjkl-bindings magit-status-mode-map 'emacs
  (kbd "DEL") 'magit-discard
  "K" 'magit-discard
  ;; "l" 'magit-key-mode-popup-logging
  "l" 'magit-log-popup
  "h" 'magit-toggle-diff-refine-hunk)
(evil-add-hjkl-bindings ztree-mode-map 'emacs)
(evil-add-hjkl-bindings magit-log-mode-map 'emacs)
(evil-add-hjkl-bindings magit-commit-mode-map 'emacs)
(evil-add-hjkl-bindings occur-mode 'emacs)
;; FIXME ;; (evil-define-key 'motion compilation-mode-map "h" 'evil-backward-char)
;; FIXME ;; (define-key compilation-mode-map (kbd "C-u") 'evil-scroll-page-up)


;;;; Evil Keys
;; set man instead woman
(setq evil-lookup-func #'man)
(evil-define-motion evil-lookup ()
  (call-interactively evil-lookup-func))


;; Start the commit window in insert mode
;; (add-hook 'with-editor-mode-hook 'evil-insert-state)
(add-hook 'with-editor-mode-hook '(lambda () (evil-insert-state)(set-input-method russian-input-method)))
(add-hook 'org-capture-mode-hook '(lambda () (evil-insert-state)(set-input-method russian-input-method)))
;; Add Evil bindings to accept/cancel commit
(evil-define-key 'normal with-editor-mode-map
  (kbd "RET") 'with-editor-finish
  [escape] 'with-editor-cancel)

(global-set-key (kbd "C-M-x") 'delete-forward-char)
(global-set-key (kbd "M-X") 'delete-backward-char)

;; !!!!!!!!!!!!!!!!!!! BASE KEYS !!!!!!!!!!!!!!!!!!!!!
(global-set-key (kbd "M-h") 'backward-char)
(global-set-key (kbd "M-j") 'evil-next-line)
(global-set-key (kbd "M-k") 'evil-previous-line)
(global-set-key (kbd "M-l") 'forward-char)

(define-key evil-insert-state-map (kbd "M-h") 'backward-char)
(define-key evil-insert-state-map (kbd "M-j") 'evil-next-line)
(define-key evil-insert-state-map (kbd "M-k") 'evil-previous-line)
(define-key evil-insert-state-map (kbd "M-l") 'forward-char)

;; (global-set-key (kbd "s-h") 'bss/first-non-blank)
;; (global-set-key (kbd "s-j") 'drag-stuff-down)
;; (global-set-key (kbd "s-k") 'drag-stuff-up)
;; (global-set-key (kbd "s-l") 'bss/end-of-line)
(global-set-key (kbd "M-y") 'bss/first-non-blank)
(global-set-key (kbd "M-u") 'drag-stuff-down)
(global-set-key (kbd "M-i") 'drag-stuff-up)
(global-set-key (kbd "M-o") 'bss/end-of-line)
;; !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


(global-set-key (kbd "C-M-h") 'evil-backward-WORD-begin)
(global-set-key (kbd "C-M-j") '(lambda () (interactive) (backward-char)(evil-backward-WORD-end)(forward-char)))
(global-set-key (kbd "C-M-k") '(lambda () (interactive) (evil-forward-WORD-end)(forward-char)))
(global-set-key (kbd "C-M-l") 'evil-forward-WORD-begin)

;; H-keys
(global-set-key (kbd "H-h") 'evil-backward-WORD-begin)
;; (global-set-key (kbd "H-j") '(lambda () (interactive) (backward-char)(evil-backward-WORD-end)(forward-char)))
;; (global-set-key (kbd "H-k") '(lambda () (interactive) (evil-forward-WORD-end)(forward-char)))
(global-set-key (kbd "H-l") 'evil-forward-WORD-begin)

;; (global-set-key (kbd "<s-left>") 'bss/first-non-blank)
;; (global-set-key (kbd "<s-right>") 'bss/end-of-line)
(global-set-key (kbd "<s-left>") 'evil-backward-word-begin)
(global-set-key (kbd "<s-right>") 'evil-forward-word-begin)
(global-set-key (kbd "<S-s-left>") 'evil-backward-WORD-begin)
(global-set-key (kbd "<S-s-right>") 'evil-forward-WORD-begin)

;;
;; (global-set-key (kbd "H-j") 'drag-stuff-down)
;; (global-set-key (kbd "H-k") 'drag-stuff-up)
;; (global-set-key (kbd "<s-up>") 'drag-stuff-up)
;; (global-set-key (kbd "<s-down>") 'drag-stuff-down)


(global-set-key (kbd "<f7>") 'evil-ace-jump-word-mode)

(global-set-key (kbd "<f6>") '(lambda () (interactive) (org-insert-time-stamp nil t t nil nil nil)))
;; [2017-04-13 Thu 21:04]


;; (global-set-key (kbd "<M-f6>") 'point-to-register)
;; (global-unset-key (kbd "<C-f6>") )
;; (global-set-key (kbd "<C-f6>") '(lambda () (interactive) (list-registers) (other-window 1)))
;; (global-set-key (kbd "<f6>") 'jump-to-register)
;; (global-set-key (kbd "<C-f6>") 'list-registers)

;; (define-key evil-normal-state-map (kbd "<f6>") [escape])
;; (define-key evil-insert-state-map (kbd "<f6>") [escape])
;; (define-key evil-visual-state-map (kbd "<f6>") [escape])
(define-key evil-normal-state-map (kbd "<f3>") 'evil-visual-line)
(define-key evil-insert-state-map (kbd "<f3>") 'evil-visual-line)

(define-key evil-normal-state-map (kbd "C-u") 'evil-scroll-page-up)
(define-key evil-normal-state-map (kbd "C-d") 'evil-scroll-page-down)
;; (define-key evil-normal-state-map (kbd "<up>") 'evil-scroll-page-up)
;; (define-key evil-normal-state-map (kbd "<down>") 'evil-scroll-page-down)
;; (define-key evil-motion-state-map (kbd "<up>") 'evil-scroll-page-up)
;; (define-key evil-motion-state-map (kbd "<down>") 'evil-scroll-page-down)
;; Restore default settings:
;; (define-key evil-normal-state-map (kbd "<up>") 'evil-previous-line)
;; (define-key evil-normal-state-map (kbd "<down>") 'evil-next-line)
;; (define-key evil-motion-state-map (kbd "<up>") 'evil-previous-line)
;; (define-key evil-motion-state-map (kbd "<down>") 'evil-next-line)

(global-set-key (kbd "<s-up>") 'evil-scroll-page-up)
(global-set-key (kbd "<s-down>") 'evil-scroll-page-down)

(define-key evil-insert-state-map (kbd "C-a") 'org-beginning-of-line)
(evil-define-key 'insert org-mode-map (kbd "C-a") 'org-beginning-of-line)
(define-key evil-insert-state-map (kbd "C-e") 'org-end-of-line)
(define-key evil-insert-state-map (kbd "M-a") 'org-backward-sentence)
(define-key evil-insert-state-map (kbd "M-e") 'org-forward-sentence)

(define-key evil-insert-state-map (kbd "C-A") 'evil-paste-last-insertion)


;; The reason for this is that q is being used at many places in Emacs to close
;; things, and sometimes it so happens that Evil Mode is turned on in that window
;; at the same time, which results in recording a macro instead of closing the
;; window. Use M-x evi mac re
;; disable q in evil
;; (define-key evil-normal-state-map (kbd "q") nil)
;; evil-mode view mode hack
(define-key dired-mode-map (kbd "v") '(lambda()
                                        (interactive)
                                        (dired-view-file)
                                        (evil-motion-state)))



(defun bss/goto-Word-end ()
  (interactive)
  ;; (while (re-search-forward "[\s_\(\)\[\]\{\}]" nil t)
  (re-search-forward "\<\w+")
  ;; (when (re-search-forward "\<\w+")
    ;; (goto-char (match-end 0)))
	;; (re-search-forward "[?(?)?{?}?[?]? ?\t?\n]")
  ;; (when (search-forward-regexp "[(){}\[\]]" nil 'noerror)
	;; (goto-char (match-end 0)))
  ;; (re-search-forward "\b" nil 'noerror)
  ;; (re-search-forward "\>")
  ;; (when (search-forward-regexp "\b" nil 'noerror)
	;; (goto-char (match-end 0)))
  )

;; visual-line mode and evil-mode
;; http://stackoverflow.com/questions/20882935/how-to-move-between-visual-lines-and-move-past-newline-in-evil-mode
(defun evil-next-line--check-visual-line-mode (orig-fun &rest args)
  (if visual-line-mode
      (apply 'evil-next-visual-line args)
    (apply orig-fun args)))

(advice-add 'evil-next-line :around 'evil-next-line--check-visual-line-mode)

(defun evil-previous-line--check-visual-line-mode (orig-fun &rest args)
  (if visual-line-mode
      (apply 'evil-previous-visual-line args)
    (apply orig-fun args)))

(advice-add 'evil-previous-line :around 'evil-previous-line--check-visual-line-mode)
;;; visual line solution from http://stackoverflow.com/questions/20882935/how-to-move-between-visual-lines-and-move-past-newline-in-evil-mode
;;(define-key evil-normal-state-map (kbd "<remap> <evil-next-line>") 'evil-next-visual-line)
;;(define-key evil-normal-state-map (kbd "<remap> <evil-previous-line>") 'evil-previous-visual-line)
;;(define-key evil-motion-state-map (kbd "<remap> <evil-next-line>") 'evil-next-visual-line)
;;(define-key evil-motion-state-map (kbd "<remap> <evil-previous-line>") 'evil-previous-visual-line)


;; esc quits
(defun minibuffer-keyboard-quit ()
  "Abort recursive edit.
In Delete Selection mode, if the mark is active, just deactivate it;
then it takes a second \\[keyboard-quit] to abort the minibuffer."
  (interactive)
  (if (and delete-selection-mode transient-mark-mode mark-active)
      (setq deactivate-mark  t)
    (when (get-buffer "*Completions*") (delete-windows-on "*Completions*"))
    (abort-recursive-edit)))
(define-key evil-normal-state-map [escape] 'keyboard-quit)
(define-key evil-visual-state-map [escape] 'keyboard-quit)
(define-key minibuffer-local-map [escape] 'minibuffer-keyboard-quit)
(define-key minibuffer-local-ns-map [escape] 'minibuffer-keyboard-quit)
(define-key minibuffer-local-completion-map [escape] 'minibuffer-keyboard-quit)
(define-key minibuffer-local-must-match-map [escape] 'minibuffer-keyboard-quit)
(define-key minibuffer-local-isearch-map [escape] 'minibuffer-keyboard-quit)
;; (global-set-key [escape] 'evil-exit-emacs-state)




;; normal state shortcuts
(define-key evil-normal-state-map "gh" 'outline-up-heading)
(define-key evil-normal-state-map "gp" 'outline-previous-heading)
(define-key evil-normal-state-map "gk" 'org-previous-visible-heading)
(define-key evil-normal-state-map "gj" 'org-next-visible-heading)
;; (define-key evil-normal-state-map "gl" 'outline-next-visible-heading)
;; (define-key evil-normal-state-map "gj" 'org-forward-heading-same-level)
;; (define-key evil-normal-state-map  "gk" 'org-backward-heading-same-level)

(defun bss/first-non-blank ()
  "selective first-non-blank-function"
  (interactive)
  (if (equal major-mode 'org-mode)
	  (org-beginning-of-line)
	  (evil-first-non-blank-of-visual-line)
  ))
(define-key evil-normal-state-map  "^" 'bss/first-non-blank)

(defun bss/end-of-line ()
  "selective first-non-blank-function"
  (interactive)
  (if (equal major-mode 'org-mode)
	  (org-end-of-line)
	(evil-end-of-line)
	(if (equal evil-state 'insert) (forward-char))
  ))
(define-key evil-normal-state-map  "$" 'bss/end-of-line)
(define-key org-mode-map (kbd "M-h") 'backward-char)
(define-key org-mode-map (kbd "M-H") 'org-metaleft)
(define-key org-mode-map (kbd "M-J") 'org-metadown)
(define-key org-mode-map (kbd "M-K") 'org-metaup)
(define-key org-mode-map (kbd "M-L") 'org-metaright)

;; evilificate calendar in org-mode
(define-key org-read-date-minibuffer-local-map (kbd "M-h") (lambda () (interactive) (org-eval-in-calendar '(calendar-backward-day 1))))
(define-key org-read-date-minibuffer-local-map (kbd "M-l") (lambda () (interactive) (org-eval-in-calendar '(calendar-forward-day 1))))
(define-key org-read-date-minibuffer-local-map (kbd "M-k") (lambda () (interactive) (org-eval-in-calendar '(calendar-backward-week 1))))
(define-key org-read-date-minibuffer-local-map (kbd "M-j") (lambda () (interactive) (org-eval-in-calendar '(calendar-forward-week 1))))
(define-key org-read-date-minibuffer-local-map (kbd "M-H") (lambda () (interactive) (org-eval-in-calendar '(calendar-backward-month 1))))
(define-key org-read-date-minibuffer-local-map (kbd "M-L") (lambda () (interactive) (org-eval-in-calendar '(calendar-forward-month 1))))
(define-key org-read-date-minibuffer-local-map (kbd "M-K") (lambda () (interactive) (org-eval-in-calendar '(calendar-backward-year 1))))
(define-key org-read-date-minibuffer-local-map (kbd "M-J") (lambda () (interactive) (org-eval-in-calendar '(calendar-forward-year 1))))

;; (defun always-insert-item ()
;;      (interactive)
;;      (if (not (org-in-item-p))
;;        (insert "\n- ")
;;        (org-insert-item)))

;; (evil-define-key 'normal org-mode-map "O" (lambda ()
;;                      (interactive)
;;                      (end-of-line)
;;                      (org-insert-heading t)
;;                      (evil-append nil)
;;                      ))

;; (evil-define-key 'normal org-mode-map "o" (lambda ()
;;                      (interactive)
;;                      (end-of-line)
;;                      (always-insert-item)
;;                      (evil-append nil)
;;                      ))

вспомогательные функции

;; evil-mode hacks
;; allow locale switching: http://stackoverflow.com/questions/15169428/use-the-default-input-method-when-doing-an-incremental-search-in-evil
(evil-define-motion evil-search-forward ()
  (format "Search forward for user-entered text.
Searches for regular expression if `evil-regexp-search' is t.%s"
		  (if (and (fboundp 'isearch-forward)
				   (documentation 'isearch-forward))
			  (format "\n\nBelow is the documentation string \
for `isearch-forward',\nwhich lists available keys:\n\n%s"
					  (documentation 'isearch-forward)) ""))
  :jump t
  :type exclusive
  :repeat evil-repeat-search
  (progn                 ;MADE CHANGES HERE
	(evil-insert-state)
	(evil-search-incrementally t evil-regexp-search)
	(evil-normal-state)
	))

(evil-define-motion evil-search-backward ()
  (format "Search forward for user-entered text.
Searches for regular expression if `evil-regexp-search' is t.%s"
		  (if (and (fboundp 'isearch-forward)
				   (documentation 'isearch-forward))
			  (format "\n\nBelow is the documentation string \
for `isearch-forward',\nwhich lists available keys:\n\n%s"
					  (documentation 'isearch-forward)) ""))
  :jump t
  :type exclusive
  :repeat evil-repeat-search
  (progn                 ;MADE CHANGES HERE
	(evil-insert-state)
	(evil-search-incrementally nil evil-regexp-search)
	(evil-normal-state)
	))

evil-leader

https://github.com/cofi/evil-leader evil-leader in org-mode protector

;; (use-package 'evil-leader
;; :config
;;     (evil-leader/set-leader "SPC")
;;     (global-evil-leader-mode)
;; )

;(require 'evil-leader) ;;; Evil-leader
(use-package evil-leader
  ;; https://github.com/cofi/evil-leader
  :config
  (evil-leader/set-leader "SPC")
  (global-evil-leader-mode)

  (evil-leader/set-key
    "0" 'select-window-0
    "1" 'select-window-1
    "2" 'select-window-2
    "3" 'select-window-3
    "4" 'select-window-4
    "5" 'select-window-5
    "6" 'select-window-6
    "7" 'select-window-7
    "8" 'select-window-8
    "9" 'select-window-9
    "<tab>" 'evil-buffer
    "a" 'browse-url-of-file
    ;; Bookmarks
    "bb" 'helm-bm
    "bt" 'bm-toggle
    "bn" 'bm-next
    "bp" 'bm-previous

    "t" '(lambda() (interactive)(helm-chronos-add-timer)(switch-to-buffer "*chronos*"))
    "T" '(lambda() (interactive)(switch-to-buffer "*chronos*"))
    "c" 'bss/selective-spc-c
    "r" 'tabbar-mode
    ;; "c" 'org-ctrl-c-ctrl-c
    ;; "C" 'ace-jump-char-mode
    "E" 'eshell
    "e" 'better-shell-for-current-dir
    "f" 'helm-find-files
    "w" 'avy-goto-word-or-subword-1
    "l" 'avy-goto-line
    ;; "SPC" 'avy-goto-char-2
    ;;"c" 'avy-goto-char-2
    "L" 'ace-jump-line-mode
    "SPC" 'ace-jump-word-mode
    ;; "SPC" 'avy-goto-word-or-subword-1
    "d" 'kill-this-buffer
    "D" 'other-window-kill-buffer
    "O" 'helm-occur
    "/" 'helm-occur
    "s" 'helm-swoop
    "I" 'helm-imenu
    ;; "I" 'helm-semantic-or-imenu
    "i" 'imenu-anywhere
    ;; "i" 'org-clock-in
    ;; "o" 'org-clock-out
    ;; ;; "p" 'project-find-file
    "p" 'projectile-find-file
    "g" 'magit-status
    ;; "j" 'ranger
    "j" 'dired-jump
    "k" 'kill-buffer
    "u" 'undo-tree-visualize
    "y" 'helm-show-kill-ring
    ;; "j" 'save-buffer
    "|" '(lambda () (interactive) (split-window-horizontally) (other-window 1))
    "m" 'narrow-or-widen-dwim
    "nh" 'org-habit-toggle-habits
    "nb" 'bss/org-toggle-budgets-and-habits
    "nn" 'bss/org-todo
    "nd" 'org-deadline
    "na" 'org-archive-subtree-default
    "nr" 'bss/org-refile
    "nm" 'bss/org-refile
    "nf" 'org-narrow-to-subtree ;; focus
    "ns" 'bss/org-schedule
    "nw" 'widen ;;unfocus
    "ny" 'org-cut-special
    "nc" 'org-capture
    "nt" 'org-ctrl-c-ctrl-c
    "v" 'org-capture
    "x" 'nlinum-mode
    "-" (lambda () (interactive) (split-window-vertically) (other-window 1))
    ;; "gg" '(lambda () (interactive) (w3m-search "g" (thing-at-point 'symbol)))
    )
  )

evil-org-agenda

;;;; Evil Org Agenda

;; dirty hack: "t" in agenda call org-agenda-todo
(evil-define-motion evil-avy-find-char-to (count char)
  "Use avy to move till char in line"
  :jump t
  :type inclusive
  (interactive "<c><C>")
  (if (equal major-mode 'org-agenda-mode)
	  (org-agenda-todo)
	(if (null count)
		(progn
		  (avy-forward-char-in-line char)
		  (backward-char))
	  (evil-find-char-to count char))))

;; (defun bss/org-agenda-refile ()
;;     (interactive)
;;     (org-agenda-refile)
;;     (set-input-method russian-input-method)
;;     )

(eval-after-load 'org-agenda
 '(progn
    ;; (evil-set-initial-state 'org-agenda-mode 'emacs)
    (evil-set-initial-state 'org-agenda-mode 'normal)
    (evil-define-key 'normal org-agenda-mode-map
      (kbd "<RET>") 'org-agenda-switch-to
	  (kbd "<tab>") 'bss/agenda-tab-replace
	  (kbd "<SPC>") 'bss/agenda-spc-replace
	  "§" 'bss/agenda-spc-replace
      "\C-n" 'org-agenda-next-line
      "\C-p" 'org-agenda-previous-line
      "\C-r" 'org-agenda-redo
      "a" 'org-archive-subtree-default-with-confirmation
      "b" 'org-agenda-bulk-action
      "c" 'org-agenda-show-tags
      "B" 'org-agenda-bulk-action
	  "d" 'org-agenda-deadline
      "D" 'org-agenda-goto-date
      "e" 'org-agenda-set-effort
      ;; "f" 'org-agenda-filter-by-category
      "f" 'org-agenda-filter-by-tag
      "\C-f" 'org-agenda-filter-by-tag
      "F" 'org-agenda-follow-mode
      "g" 'org-agenda-redo
      ;; "h"  'org-agenda-earlier
	  "h" nil
      "H" 'bss/org-toggle-budgets-and-habits
      "j"  'org-agenda-next-line
      "k"  'org-agenda-previous-line
      ;; "l"  'org-agenda-later
	  "l" nil
      "m" 'org-agenda-bulk-mark
      "n" nil                          ; evil-search-next
      "q" 'org-agenda-quit
      "s" 'org-agenda-schedule
	  "r" 'org-agenda-refile
	  ;; "r" 'bss/org-agenda-refile
      "t" 'org-agenda-todo
      ;; "\C-t" 'org-agenda-todo
      "T" 'org-agenda-set-tags
      "u" 'org-agenda-bulk-unmark
      "v" 'org-agenda-view-mode-dispatch
      "x" 'org-agenda-exit
      "y" 'org-agenda-year-view
      "+" 'org-agenda-priority-up
      "-" 'org-agenda-priority-down
      "." 'org-agenda-goto-today
      "0" 'evil-digit-argument-or-evil-beginning-of-line
      "I" 'org-agenda-clock-in
      "O" 'org-agenda-clock-out
      "X" 'org-agenda-clock-cancel
	  )))
;; next evil plugin

evil plugins

каша

(use-package evil-surround)
(global-evil-surround-mode 1)



;;hlsearch
;;(require 'evil-search-highlight-persist)
;;(global-evil-search-highlight-persist t)
;;(evil-leader/set-key "SPC" 'evil-search-highlight-persist-remove-all)


;; macro debug ;; (require 'evil-args)

(use-package evil-visualstar)
(global-evil-visualstar-mode t)

evil text objects

[2017-03-22 Wed 13:57]

(use-package evil-indent-textobject)

(use-package evil-textobj-anyblock)
(define-key evil-inner-text-objects-map "b" 'evil-textobj-anyblock-inner-block)
(define-key evil-outer-text-objects-map "b" 'evil-textobj-anyblock-a-block)

;; bind evil-args text objects
(define-key evil-inner-text-objects-map "a" 'evil-inner-arg)
(define-key evil-outer-text-objects-map "a" 'evil-outer-arg)

match parent

[2017-03-22 Wed 13:55]

;; https://github.com/redguardtoo/evil-matchit/
(use-package evil-matchit)
(global-evil-matchit-mode 1)
;; (global-set-key "%" 'match-paren)

;; (defun match-paren (arg)
;;   "Go to the matching paren if on a paren; otherwise insert %."
;;   (interactive "p")
;;   (cond ((looking-at "\\s\(") (forward-list 1) (backward-char 1))
;;         ((looking-at "\\s\)") (forward-char 1) (backward-list 1))
;;         (t (self-insert-command (or arg 1)))))

smartparents

[2017-03-22 Wed 13:53]

;; https://github.com/Fuco1/smartparens
;; manual: https://ebzzry.github.io/emacs-pairs.html
;; Inside Emacs, M-x sp-cheat-sheet will show you all the commands available, with examples.
;; (use-package smartparens)
;; (use-package smartparens-config)
;; (add-hook 'prog-mode-hook 'turn-on-smartparens-strict-mode)
;;; (add-hook 'prog-mode-hook 'turn-on-smartparens-mode)
;; (add-hook 'markdown-mode-hook 'turn-on-smartparens-strict-mode)

;; !!!! Evil-smartparents !!!!
;; https://github.com/expez/evil-smartparens
;; (add-hook 'smartparens-enabled-hook #'evil-smartparens-mode)

;; Another solutions!!!
;; https://github.com/luxbock/evil-cleverparens
;; https://github.com/noctuid/lispyville

evil-snipe

[2017-03-22 Wed 13:52]

;;;; Evil snipe mode
;; https://github.com/hlissner/evil-snipe
(use-package evil-snipe
  :disabled
  :config
    ;; (evil-snipe-mode nil)
    (evil-snipe-mode 1)
    (evil-snipe-override-mode 1)
    (setq evil-snipe-scope 'whole-visible) ;; line, buffer, visible, 'whole-line, 'whole-bufferm 'whole-visible
    (setq evil-snipe-repeat-scope 'whole-visible)
    ;; (setq evil-snipe-repeat-scope 'line)
    (setq evil-snipe-repeat-keys nil)

    ;; map [ to any opening parentheses or bracket in all modes:
    (push '(?\[ "[[{(]") evil-snipe-aliases)
    (push '(?\] "[]})]") evil-snipe-aliases)

    ;; (evil-define-key 'visual evil-snipe-mode-map "z" 'evil-snipe-s)
    ;; (evil-define-key 'visual evil-snipe-mode-map "Z" 'evil-snipe-S)
    (add-hook 'magit-mode-hook 'turn-off-evil-snipe-override-mode)
    (add-hook 'org-agenda-mode-hook 'turn-off-evil-snipe-override-mode)

  )

evil-lion (glip= gLip= glib)

[2017-03-22 Wed 13:45]

https://github.com/edkolev/evil-lion

one = 1 three = 3 fifteen = 15

;; #+begin_src emacs-lisp (use-package evil-lion :disabled :ensure t :config ;; (evil-lion-mode) (add-hook ‘prog-mode-hook ‘evil-lion-mode) ) ;; #+end_src

evil-numbers (disabled)

[2017-10-03 вт 12:22]

(use-package evil-numbers
 :disabled
 :config
  (define-key evil-normal-state-map (kbd "C-c +") 'evil-numbers/inc-at-pt)
  (define-key evil-normal-state-map (kbd "C-c -") 'evil-numbers/dec-at-pt)
)

hjkl in tetris

[2017-09-14 Thu 09:33]

(require 'tetris)
(define-key tetris-mode-map "h" 'tetris-move-left)
(define-key tetris-mode-map "l" 'tetris-move-right)
(define-key tetris-mode-map "j" 'tetris-rotate-next)
(define-key tetris-mode-map "k" 'tetris-rotate-prev)
(evil-set-initial-state 'tetris-mode 'emacs)
(push '("\\*Tetris\\*" . emacs) evil-buffer-regexps)
(push '("\\*tetris-scores\\*" . emacs) evil-buffer-regexps)

org-mode

requires

(add-to-list 'auto-mode-alist '("\\.\\(org\\|org_archive\\|gpg_archive\.gpg\\|txt\\)$" . org-mode))


; Enable habit tracking (and a bunch of other modules)
(setq org-modules (quote (org-bbdb
                          org-mac-link
                          org-babel
                          org-bibtex
                          org-crypt
                          org-gnus
                          org-id
                          org-info
                          org-habit
                          org-inlinetask
                          org-timer
                          org-irc
                          org-mhe
                          org-protocol
                          org-rmail
                          org-w3m)))

;; (use-package org)
;; (use-package org-plus-contrib)
(require 'org-bbdb)
(require 'org-bibtex)
(require 'org-crypt)
(require 'org-gnus)
(require 'org-id)
(require 'org-info)
;; (defconst org-ts-regexp-inactive
;;   "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
;;   "Regular expression for fast inactive time stamp matching.")
(require 'org-habit)
(require 'org-inlinetask)
(require 'org-irc)
(require 'org-mhe)
(require 'org-protocol)
(require 'org-rmail)
(require 'org-w3m)
(require 'org-timer)
;; (require 'org-babel-gnuplot)

org-settings

(setq org-directory "~/notes/org-mode")
(setq org-default-notes-file "~/notes/org-mode/refile.org")

(setq org-agenda-files (quote (
                               "~/notes/org-mode/work.org"
                               "~/notes/org-mode/personal.org"
                               "~/notes/org-mode/finances.org.gpg"
                               "~/notes/org-mode/farm.org"
                               ; "~/notes/org-mode/notes.org"
                               "~/notes/org-mode/diary.org.gpg"
                               "~/notes/org-mode/refile.org"
                               "~/notes/org-mode/common.org"
                               )))



(setq org-keep-stored-link-after-insertion t)
; Overwrite the current window with the agenda
(setq org-agenda-window-setup 'current-window)


;; default
(setq org-show-context-detail  '((agenda . local)
				 (bookmark-jump . lineage)
				 (isearch . lineage)
				 (default . canonical)))
(setq org-show-context-detail  '((default . tree)))
;; (push '(tags-tree . local) org-show-context-detail)

;; Allowed visibility spans are
;;   minimal        show current headline; if point is not on headline,
;;                  also show entry
;;   local          show current headline, entry and next headline
;;   ancestors      show current headline and its direct ancestors; if
;;                  point is not on headline, also show entry
;;   lineage        show current headline, its direct ancestors and all
;;                  their children; if point is not on headline, also show
;;                  entry and first child
;;   tree           show current headline, its direct ancestors and all
;;                  their children; if point is not on headline, also show
;;                  entry and all children
;;   canonical      show current headline, its direct ancestors along with
;;                  their entries and children; if point is not located on
;;                  the headline, also show current entry and all children



(setq org-clone-delete-id t)

(setq org-cycle-include-plain-lists t)

(setq org-src-fontify-natively t)
(setq org-agenda-skip-additional-timestamps-same-entry t)
(setq org-use-fast-todo-selection t)
;; https://www.gnu.org/software/emacs/manual/html_node/org/Speeding-up-your-agendas.html#Speeding-up-your-agendas
;; (setq org-agenda-inhibit-startup t)
(setq org-treat-S-cursor-todo-selection-as-state-change nil)
(setq org-agenda-span 'day)
(setq org-stuck-projects (quote ("" nil nil "")))
(setq org-alphabetical-lists t)
(setq org-export-with-timestamps nil)

(setq org-remove-highlights-with-change t)

(add-to-list 'Info-default-directory-list "~/notes/org-mode/doc")

(setq org-read-date-prefer-future 'time)

(setq org-list-demote-modify-bullet (quote (("+" . "-")
                                            ("*" . "-")
                                            ("1." . "-")
                                            ("1)" . "-")
                                            ("A)" . "-")
                                            ("B)" . "-")
                                            ("a)" . "-")
                                            ("b)" . "-")
                                            ("A." . "-")
                                            ("B." . "-")
                                            ("a." . "-")
                                            ("b." . "-"))))

(setq org-tags-match-list-sublevels t)

(setq org-agenda-persistent-filter t)

(setq org-link-mailto-program (quote (compose-mail "%a" "%s")))

(setq org-return-follows-link t)

(setq org-archive-mark-done nil)
;;(setq org-archive-location "%s_archive::* Archived Tasks")
;; (setq org-archive-location "%s_archive::")
(setq org-archive-location "%s_archive.gpg::")


;;(defvar bh/organization-task-id "f97e7daa-05e3-428c-9cfa-99757a3beb43")
;; задача для клокинга по-умолчанию
;; [[id:E56BE5F4-681F-41A0-9621-4EA546AAEB97][задача для планирования]]
(defvar bh/organization-task-id "E56BE5F4-681F-41A0-9621-4EA546AAEB97")

;; Resume clocking task when emacs is restarted
(org-clock-persistence-insinuate)
;;
;; Show lot of clocking history so it's easy to pick items off the C-F11 list
(setq org-clock-history-length 23)
;; Resume clocking task on clock-in if the clock is open
(setq org-clock-in-resume t)
;; Change tasks to NEXT when clocking in
(setq org-clock-in-switch-to-state 'bh/clock-in-to-next)
;; Separate drawers for clocking and logs
(setq org-drawers (quote ("PROPERTIES" "LOGBOOK")))
;; Save clock data and state changes and notes in the LOGBOOK drawer
(setq org-clock-into-drawer t)
;; Sometimes I change tasks I'm clocking quickly - this removes clocked tasks with 0:00 duration
(setq org-clock-out-remove-zero-time-clocks t)
;; Clock out when moving task to a done state
(setq org-clock-out-when-done t)
;; Save the running clock and all clock history when exiting Emacs, load it on startup
(setq org-clock-persist t)
;; Do not prompt to resume an active clock
(setq org-clock-persist-query-resume nil)
;; Enable auto clock resolution for finding open clocks
(setq org-clock-auto-clock-resolution (quote when-no-clock-is-running))
;; Include current clocking task in clock reports
(setq org-clock-report-include-clocking-task t)

(setq bh/keep-clock-running nil)
; Use the current window for indirect buffer display
(setq org-indirect-buffer-display 'current-window)

(setq org-cycle-open-archived-trees t)
;; Do not dim blocked tasks
(setq org-agenda-dim-blocked-tasks nil)

;; Compact the block agenda view
(setq org-agenda-compact-blocks t)

;; indent agenda subtasks
(setq org-tags-match-list-sublevels 'indented)

; position the habit graph on the agenda to the right of the default
(setq org-habit-graph-column 60)
(setq org-habit-show-habits t)
;; (run-at-time "06:00" 86400 '(lambda () (setq org-habit-show-habits t)))
;; (setq org-habit-show-all-today t)
;; (setq org-habit-show-habits-only-for-today t)

; отключаем разрыв строк по M-RET
;; (setq org-M-RET-may-split-line '((default . t)))
(setq org-M-RET-may-split-line nil)

(setq org-cycle-global-at-bob t)
(setq org-time-stamp-rounding-minutes (quote (1 1)))

(setq org-agenda-clock-consistency-checks
      (quote (:max-duration "4:00"
              :min-duration 0
              :max-gap 0
              :gap-ok-around ("4:00"))))

;; Sometimes I change tasks I'm clocking quickly - this removes clocked tasks with 0:00 duration
(setq org-clock-out-remove-zero-time-clocks t)

;; Agenda clock report parameters
(setq org-agenda-clockreport-parameter-plist
      (quote (:link t :maxlevel 5 :fileskip0 t :compact t :narrow 80)))

; Set default column view headings: Task Effort Clock_Summary
(setq org-columns-default-format "%80ITEM(Task) %10Effort(Effort){:} %10CLOCKSUM")

; global Effort estimate values
; global STYLE property values for completion
(setq org-global-properties (quote (("Effort_ALL" . "0:15 0:30 0:45 1:00 2:00 3:00 4:00 5:00 6:00 0:00")
                                    ("STYLE_ALL" . "habit"))))

;; Agenda log mode items to display (closed and state changes by default)
(setq org-agenda-log-mode-items (quote (closed state)))



(setq org-enforce-todo-dependencies t)

;; (setq org-hide-leading-stars nil)

(setq org-startup-indented t)
(setq org-startup-folded t)
(setq org-indent-mode t)
;;norang;;
(setq org-cycle-separator-lines 0)
;;(setq org-cycle-separator-lines 2)

;;norang;; (setq org-blank-before-new-entry (quote ((heading)
;;norang;;                                          (plain-list-item . auto))))
(setq org-blank-before-new-entry (quote ((heading . auto)
                                         (plain-list-item . auto))))

;;norang;; (setq org-insert-heading-respect-content nil)
(setq org-insert-heading-respect-content t)

(setq org-reverse-note-order nil)

(setq org-show-following-heading t)
(setq org-show-hierarchy-above t)
(setq org-show-siblings (quote ((default))))

(setq org-special-ctrl-a/e t)
(setq org-special-ctrl-k t)
(setq org-yank-adjusted-subtrees t)

(setq org-id-method (quote uuidgen))

(setq org-deadline-warning-days 30)

(setq org-table-export-default-format "orgtbl-to-csv")

(setq org-link-frame-setup (quote ((vm . vm-visit-folder)
                                   (gnus . org-gnus-no-new-news)
                                   (file . find-file))))

; Use the current window for C-c ' source editing
(setq org-src-window-setup 'current-window)

(setq org-log-done (quote time))
(setq org-log-redeadline (quote time)) ;; record when the deadline date of a tasks is modified
(setq org-log-reschedule (quote time))
(setq org-log-into-drawer t)
(setq org-log-state-notes-insert-after-drawers nil)

(setq org-clock-sound "~/.emacs.d/manual-addons/tada.wav")
;;(play-sound-file org-clock-sound)


(setq org-src-preserve-indentation nil)
(setq org-edit-src-content-indentation 0)

(setq org-catch-invisible-edits 'error)


;priority setup
(setq org-highest-priority ?A)
(setq org-default-priority ?B)
(setq org-lowest-priority ?C)

(setq org-time-clocksum-format
      '(:hours "%d" :require-hours t :minutes ":%02d" :require-minutes t))

(setq org-id-link-to-org-use-id 'create-if-interactive-and-no-custom-id)

(setq org-emphasis-alist (quote (("*" bold "<b>" "</b>")
                                 ("/" italic "<i>" "</i>")
                                 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
                                 ("=" org-code "<code>" "</code>" verbatim)
                                 ("~" org-verbatim "<code>" "</code>" verbatim))))

(setq org-use-sub-superscripts nil)

(setq org-odd-levels-only nil)


;;link abbreviations http://orgmode.org/org.html#Link-abbreviations
;; With the above setting, you could link to a specific bug with [[bugzilla:129]], search the web for ‘OrgMode’ with [[google:OrgMode]], show the map location of the Free Software Foundation [[gmap:51 Franklin Street, Boston]] or of Carsten office [[omap:Science Park 904, Amsterdam, The Netherlands]] and find out what the Org author is doing besides Emacs hacking with [[ads:Dominik,C]].
(setq org-link-abbrev-alist
       '(("bugzilla"  . "http://10.1.2.9/bugzilla/show_bug.cgi?id=")
         ("url-to-ja" . "http://translate.google.fr/translate?sl=en&tl=ja&u=%h")
         ("google"    . "http://www.google.com/search?q=")
         ("gmap"      . "http://maps.google.com/maps?q=%s")
         ("omap"      . "http://nominatim.openstreetmap.org/search?q=%s&polygon=1")
         ("ads"       . "http://adsabs.harvard.edu/cgi-bin/nph-abs_connect?author=%s&db_key=AST")))

org-mode todo keywords

http://orgmode.org/manual/Tracking-TODO-state-changes.html

(setq org-todo-keywords
      (quote ((sequence "TODO(t)" "NEXT(n)" "|" "DONE(d!)")
              (sequence "WAITING(w!)" "HOLD(h!)" "|" "CANCELLED(c!)" "PHONE" "MEETING"))))
              ;; (sequence "WAITING(w@/!)" "HOLD(h@/!)" "|" "CANCELLED(c@/!)" "PHONE" "MEETING"))))

(setq org-todo-keyword-faces
      (quote (("TODO" :foreground "red" :weight bold)
              ;;("NEXT" :foreground "blue" :weight bold)
              ("NEXT" :foreground "yellow" :weight bold)
              ("DONE" :foreground "forest green" :weight bold)
              ("WAITING" :foreground "orange" :weight bold)
              ("HOLD" :foreground "magenta" :weight bold)
              ("CANCELLED" :foreground "forest green" :weight bold)
              ("MEETING" :foreground "forest green" :weight bold)
              ("PHONE" :foreground "forest green" :weight bold))))

;; from Howard Abrams config
;; (font-lock-add-keywords            ; A bit silly but my headers are now
;;  'org-mode `(("^\\*+ \\(NEXT\\) "  ; shorter, and that is nice canceled
;;               (1 (progn (compose-region (match-beginning 1) (match-end 1) "⚑")
;;                         nil)))
;;              ("^\\*+ \\(TODO\\) "
;;               (1 (progn (compose-region (match-beginning 1) (match-end 1) "⚐")
;;                         nil)))
;;              ("^\\*+ \\(CANCELLED\\) "
;;               (1 (progn (compose-region (match-beginning 1) (match-end 1) "✘")
;;                         nil)))
;;              ("^\\*+ \\(HOLD\\) "
;;               (1 (progn (compose-region (match-beginning 1) (match-end 1) "⏳")
;;                         nil)))
;;              ("^\\*+ \\(DONE\\) "
;;               (1 (progn (compose-region (match-beginning 1) (match-end 1) "✔")
;;                         nil)))))
;; (font-lock-add-keywords 'org-mode
;;                         '(("^ +\\([-*]\\) "
;;                            (0 (prog1 () (compose-region (match-beginning 1) (match-end 1) "•"))))))

(setq org-todo-state-tags-triggers
      (quote (("CANCELLED" ("CANCELLED" . t))
              ("WAITING" ("WAITING" . t))
              ("HOLD" ("WAITING") ("HOLD" . t))
              (done ("WAITING") ("HOLD"))
              ("TODO" ("WAITING") ("CANCELLED") ("HOLD"))
              ("NEXT" ("WAITING") ("CANCELLED") ("HOLD"))
              ("DONE" ("WAITING") ("CANCELLED") ("HOLD")))))


org-capture settings

Capture templates for: TODO tasks, Notes, appointments, phone calls, meetings, and org-protocol manual: http://orgmode.org/manual/Template-expansion.html#Template-expansion

(setq org-capture-templates
      (quote (("t" "todo" entry (file "~/notes/org-mode/refile.org")
               "* TODO %?\n%U \n" :clock-in t :clock-resume t)
              ;; ("r" "respond" entry (file "~/notes/org-mode/refile.org")
              ;;  "* NEXT Respond to %:from on %:subject\nSCHEDULED: %t\n%U \n" :clock-in t :clock-resume t :immediate-finish t)
              ("n" "note" entry (file "~/notes/org-mode/refile.org")
               "* %? :NOTE:\n%U \n" :clock-in t :clock-resume t)
              ("j" "Journal" entry (file+datetree "~/notes/org-mode/diary.org.gpg")
               "* %?\n%U \n" :clock-in t :clock-resume t)
              ("s" "Summary of day with active questions" entry (file+datetree "~/notes/org-mode/diary.org.gpg")
               (file "~/notes/org-mode/templates/active-questions.txt") :clock-in t :clock-resume t)
              ("S" "Summary of WEEK" entry (file+datetree "~/notes/org-mode/diary.org.gpg")
               (file "~/notes/org-mode/templates/active-questions-week.txt") :clock-in t :clock-resume t)
              ("g" "Goals for current day" entry (file+datetree "~/notes/org-mode/diary.org.gpg")
               (file "~/notes/org-mode/templates/goals-for-day.txt") :clock-in t :clock-resume t)
              ("G" "Goals for current WEEK" entry (file+datetree "~/notes/org-mode/diary.org.gpg")
               (file "~/notes/org-mode/templates/goals-for-week.txt") :clock-in t :clock-resume t)
              ("M" "Goals for current MONTH" entry (file+datetree "~/notes/org-mode/diary.org.gpg")
               (file "~/notes/org-mode/templates/goals-for-month.txt") :clock-in t :clock-resume t)
              ;; ("w" "org-protocol" entry (file "~/notes/org-mode/refile.org")
              ;;  "* TODO Review %c\n%U \n" :immediate-finish t)
              ("m" "Meeting" entry (file "~/notes/org-mode/refile.org")
               "* MEETING with %? :MEETING:\n%U " :clock-in t :clock-resume t)
              ("p" "Phone call" entry (file "~/notes/org-mode/refile.org")
               "* PHONE %? :PHONE:\n%U " :clock-in t :clock-resume t)
			  ;; ("o" "org-outlook" entry (file "~/notes/org-mode/refile.org") "* TODO Email %c %?
              ;;  %i
              ;;  %U" :clock-in t :clock-resume t)
              ("h" "Habit" entry (file "~/notes/org-mode/refile.org")
			   "* NEXT %?\n%U \nSCHEDULED: %(format-time-string \"%<<%Y-%m-%d %a .+1d/3d>>\")\n:PROPERTIES:\n:STYLE: habit\n:REPEAT_TO_STATE: NEXT\n:END:\n")

              ;; ("l" "Ledger entries")
              ;; ("lm" "MBNA" plain
              ;;  (file "~/notes/ledger/bss.ledger")
              ;;  "\n\n%(org-read-date) * %^{Где потрачено}\n    активы:Зарплатная карта\n    расходы:%^{Статья расходов}  %^{Сумма}р\n" :immediate-finish t)
              ;; ("lp" "pMBNA" plain
              ;;  (file "~/notes/ledger/bss.ledger")
              ;;  "\n\n%(replace-regexp-in-string \"-\" \"/\" (org-read-date)) * %^{Где потрачено}\n    активы:Зарплатная карта\n    расходы:%^{Статья расходов}  %^{Сумма}р\n" :immediate-finish t)


              ))
	  )
               ;; "\n\n%(org-read-date) * %^{Где потрачено}\n    активы:Зарплатная карта\n    Расходы:%^{Статья расходов}  %^{Сумма}р\n" :immediate-finish t)

;;;;;;;;;; External org-capture. Call it via OS command 'emacsclient -ne "(make-capture-frame)"'
(defadvice org-capture-finalize
    (after delete-capture-frame activate)
  "Advise capture-finalize to close the frame"
  (if (equal "capture" (frame-parameter nil 'name))
    (delete-frame)))

(defadvice org-capture-destroy
    (after delete-capture-frame activate)
  "Advise capture-destroy to close the frame"
  (if (equal "capture" (frame-parameter nil 'name))
    (delete-frame)))

(use-package noflet)
;; (use-package noflet
  ;; :ensure t )
(defun make-capture-frame ()
  "Create a new frame and run org-capture."
  (interactive)
  (make-frame '((name . "capture")))
  (select-frame-by-name "capture")
  (delete-other-windows)
  (noflet ((switch-to-buffer-other-window (buf) (switch-to-buffer buf)))
    (org-capture)))

refile settings

; Targets include this file and any file contributing to the agenda - up to 9 levels deep
(setq org-refile-targets (quote ((nil :maxlevel . 3)
                                 (org-agenda-files :maxlevel . 3))))
;; (setq org-refile-targets '((org-agenda-files :maxlevel . 3)))

; Use full outline paths for refile targets - we file directly with IDO
(setq org-refile-use-outline-path t)

; Targets complete directly with IDO
(setq org-outline-path-complete-in-steps nil)

; Allow refile to create parent tasks with confirmation
(setq org-refile-allow-creating-parent-nodes (quote confirm))


; Exclude DONE state tasks from refile targets
(defun bh/verify-refile-target ()
  "Exclude todo keywords with a done state from refile targets"
  (not (member (nth 2 (org-heading-components)) org-done-keywords)))

(setq org-refile-target-verify-function 'bh/verify-refile-target)

bullets

http://nadeausoftware.com/articles/2007/11/latency_friendly_customized_bullets_using_unicode_characters красивые буллеты для org-mode потенциально очень тормозные

(use-package org-bullets
  :disabled t
  :config
  (add-hook 'org-mode-hook (lambda () (org-bullets-mode 1)))
  (eval-after-load 'org-bullets
    '(setq org-bullets-bullet-list '("" "" "" "" "" "" "" "" "" "" )))
  )
;; "..."
(setq org-ellipsis "")
;; (setq org-ellipsis " ⤵")
;; (setq org-ellipsis " \u25bc" )

вспомогательные функции

;; Flexible scheduling of tasks
;; I (theoretically) want to be able to schedule tasks for dates like the first Saturday of every month. Fortunately, someone else has figured that out!

;; Get this from https://raw.github.com/chenfengyuan/elisp/master/next-spec-day.el
(load "~/.emacs.d/manual-addons/next-spec-day.el" t)
;; set NEXT-SPEC-DEADLINE and/or NEXT-SPEC-SCHEDULED property of a TODO task,like this:
;;
;; * test
;;                                                                         :PROPERTIES:
;;   :NEXT-SPEC-SCHEDULED: (org-float t 6 1)
;;                                                                                :END:
;; The value of NEXT-SPEC-SCHEDULED is a sexp will return non-nil if date is the first Saturday of the month
;;
;; Then,when you change the TODO state of that tasks,the timestamp will be changed automatically(include lead time of warnings settings).It becomes:
;;
;; * TODO test
;;   SCHEDULED: <2013-01-05 Sat>
;;                                                                         :PROPERTIES:
;;   :NEXT-SPEC-SCHEDULED: (org-float t 6 1)
;;                                                                                :END:


(defun bss/my-org-goto (id)
    (interactive)
    (org-id-goto id)
    (bss/show-task-and-collapse-other)
)


(use-package bbdb)
(require 'bbdb-com)
;;
;; Phone capture template handling with BBDB lookup
;; Adapted from code by Gregory J. Grubbs
(defun bh/phone-call ()
  "Return name and company info for caller from bbdb lookup"
  (interactive)
  (let* (name rec caller)
    (setq name (completing-read "Who is calling? "
                                (bbdb-hashtable)
                                'bbdb-completion-predicate
                                'confirm))
    (when (> (length name) 0)
      ; Something was supplied - look it up in bbdb
      (setq rec
            (or (first
                 (or (bbdb-search (bbdb-records) name nil nil)
                     (bbdb-search (bbdb-records) nil name nil)))
                name)))

    ; Build the bbdb link if we have a bbdb record, otherwise just return the name
    (setq caller (cond ((and rec (vectorp rec))
                        (let ((name (bbdb-record-name rec))
                              (company (bbdb-record-company rec)))
                          (concat "[[bbdb:"
                                  name "]["
                                  name "]]"
                                  (when company
                                    (concat " - " company)))))
                       (rec)
                       (t "NameOfCaller")))
    (insert caller)))

(defun ded/org-show-next-heading-tidily ()
  "Show next entry, keeping other entries closed."
  (interactive)
  (if (save-excursion (end-of-line) (outline-invisible-p))
      (progn (org-show-entry) (show-children))
    (outline-next-heading)
    (unless (and (bolp) (org-on-heading-p))
      (org-up-heading-safe)
      (hide-subtree)
      (error "Boundary reached"))
    (org-overview)
    (org-reveal t)
    (org-show-entry)
    (recenter-top-bottom)
    (show-children)
    ;;(recenter-top-bottom)
	(recenter 0)
	))

(defun ded/org-show-previous-heading-tidily ()
  "Show previous entry, keeping other entries closed."
  (interactive)
  (let ((pos (point)))
    (outline-previous-heading)
    (unless (and (< (point) pos) (bolp) (org-on-heading-p))
      (goto-char pos)
      (hide-subtree)
      (error "Boundary reached"))
    (org-overview)
    (org-reveal t)
    (org-show-entry)
    (recenter-top-bottom)
    (show-children)
    ;;(recenter-top-bottom)
	(recenter 0)
	))

(defun ded/org-show-current-heading-tidily ()
  (interactive)  ;Inteactive
  "Show next entry, keeping other entries closed."
  (if (save-excursion (end-of-line) (outline-invisible-p))
      (progn (org-show-entry) (show-children))
    (outline-back-to-heading)
    (unless (and (bolp) (org-on-heading-p))
      (org-up-heading-safe)
      (hide-subtree)
      (error "Boundary reached"))
    (org-overview)
    (org-reveal t)
    (org-show-entry)
    (show-children)))


(defun bh/hide-other ()
   (interactive)
   (save-excursion
     (org-back-to-heading 'invisible-ok)
    (hide-other)
    (org-cycle)
    (org-cycle)
    (org-cycle)))

;;http://stackoverflow.com/questions/25161792/emacs-org-mode-how-can-i-fold-everything-but-the-current-headline
;;http://emacs.stackexchange.com/questions/2237/show-siblings-of-visible-headers-after-hide-other

(defun bss/show-task-and-collapse-other ()
  "Show next entry, keeping other entries closed."
  (interactive)
  (save-excursion
    (let ((level (progn
                   (outline-back-to-heading)
                   (funcall outline-level))))
      (hide-other)
      (while (> level 1)
        (outline-up-heading 1)
        (show-children 1)
        (setq level (funcall outline-level)))
	  ))
  (show-children 1)
  (org-show-entry)
  ;; (recenter-top-bottom)
  (evil-scroll-line-to-top nil)
  (scroll-down-line 2)
  )

(defun bss/hide-other ()
  "Show next entry, keeping other entries closed."
  (interactive)
  (if (save-excursion (end-of-line) (outline-invisible-p))
      (progn (org-show-entry) (show-children))
    (outline-back-to-heading)
    (unless (and (bolp) (org-on-heading-p))
      (org-up-heading-safe)
      (hide-subtree)
      (error "Boundary reached"))
    (org-overview)
    (org-reveal t)
    (org-show-entry)
    (show-children)))

;; spc: (org-agenda-show-and-scroll-up &optional ARG)
;; tab: (org-agenda-goto &optional HIGHLIGHT)
;; https://lists.gnu.org/archive/html/emacs-orgmode/2012-11/msg00087.html

(defun bss/agenda-tab-replace ()
  "Hide other headings"
    (interactive)
    (org-agenda-goto)
    ;; (bss/hide-other)
	(bss/show-task-and-collapse-other)
	(if (evil-mode) (evil-normal-state))
	)

(defun bss/agenda-spc-replace ()
  "Hide other headings"
    (interactive)
    (bss/agenda-tab-replace)
	(other-window -1)
	)

(defun bss/selective-ace-jump ()
  "Ace-jump-word not in agenda-mode"
  (interactive)
  (if (equal major-mode 'org-agenda-mode)
	  (bss/agenda-spc-replace)
	  ;; (evil-ace-jump-word-mode)
	(avy-goto-word-or-subword-1)
  ))


(defun bss/selective-spc-c ()
  "<c-c><c-c> in org-mode or ace-jump-char-mode"
  (interactive)
  (if (equal major-mode 'org-mode)
	  (org-ctrl-c-ctrl-c)
	(evil-ace-jump-char-mode)
  ))


(defun bh/set-truncate-lines ()
  "Toggle value of truncate-lines and refresh window display."
  (interactive)
  (setq truncate-lines (not truncate-lines))
  ;; now refresh window display (an idiom from simple.el):
  (save-excursion
    (set-window-start (selected-window)
                      (window-start (selected-window)))))

(defun bh/make-org-scratch ()
  (interactive)
  (find-file (concat temporary-file-directory "publish/scratch.org"))
  (gnus-make-directory (concat temporary-file-directory "publish")))

(defun bh/switch-to-scratch ()
  (interactive)
  (switch-to-buffer "*scratch*"))


;; вспомогательная функция для исключения из блока агенды тэгированных задач. Их нельзя вырезать
;; регекспом, т.к. тэги могут наследоваться и на этом заголовке записи :тэг: не будет. для справки:
;; регекспы (org-agenda-skip-entry-if 'regexp "regular expression") посмотреть варианты можно в
;; описании функции org-agenda-skip-entry-if function
;; from http://stackoverflow.com/questions/10074016/org-mode-filter-on-tag-in-agenda-view
(defun zin/org-agenda-skip-tag (tag &optional others)
  "Skip all entries that correspond to TAG.

If OTHERS is true, skip all entries that do not correspond to TAG."
  (let ((next-headline (save-excursion (or (outline-next-heading) (point-max))))
        (current-headline (or (and (org-at-heading-p)
                                   (point))
                              (save-excursion (org-back-to-heading)))))
    (if others
        (if (not (member tag (org-get-tags-at current-headline)))
            next-headline
          nil)
      ;; Меняем "пропускаем задачи с заданным тэгом" на
      ;;        "пропускаем задачи с заданным тэгом, если они ожидают выполнения"
      ;; Это нужно для того, чтобы показывались логи выполненного
      ;; оригинал: (if (member tag (org-get-tags-at current-headline))
      (if (and (member tag (org-get-tags-at current-headline))
               (member (org-get-todo-state) (list "TODO" "NEXT")))
          next-headline
        nil))))

(defun bss/skip-low-priority-tasks ()
  "Skip low-priority tasks: non #A and non BOSS|URGENT-tagged"
  (let ((next-headline (save-excursion (or (outline-next-heading) (point-max))))
        (current-headline (or (and (org-at-heading-p)
                                   (point))
                              (save-excursion (org-back-to-heading))))
		(is-high-priority nil) ;;by default all tasks have low priority
		)

	;; Priority [#A] has high priority
	(if (org-agenda-skip-entry-if 'regexp "\\=.*\\[#A\\]")
		;; If hideing is needed (by default), then show only standalone [#A]-tasks
		(if bh/hide-scheduled-and-waiting-next-tasks
			(progn
			  (if (and (not (bh/is-subproject-p))
					   (not (bh/is-project-p)) )
				  (setq is-high-priority t))
			  )
		  (setq is-high-priority t)))


	;; For tasks with "BOSS" or "URGENT" tags
	(if (or (member "BOSS" (org-get-tags-at current-headline))
			(member "URGENT" (org-get-tags-at current-headline)))
		(progn
		  ;; If hideing is not needed show all BOSS-tasks
		  (if bh/hide-scheduled-and-waiting-next-tasks
			  (progn
				;; If my-high-priority-tags -related single task not in project, then it has high priority
				(if (and (not (bh/is-subproject-p))
						 (not (bh/is-project-p)) )
					(setq is-high-priority t))

				;; for projects show only NEXT-tasks
				(if (and (bh/is-subproject-p)
						 (member (org-get-todo-state) '("NEXT")))
					(setq is-high-priority t)))
			(setq is-high-priority t))
		  ))



	(if is-high-priority
		nil
	  next-headline)
	))


(defun bh/clock-in-to-next (kw)
  "Switch a task from TODO to NEXT when clocking in.
Skips capture tasks, projects, and subprojects.
Switch projects and subprojects from NEXT back to TODO"
  (when (not (and (boundp 'org-capture-mode) org-capture-mode))
    (cond
     ((and (member (org-get-todo-state) (list "TODO"))
           (bh/is-task-p))
      "NEXT")
     ((and (member (org-get-todo-state) (list "NEXT"))
           (bh/is-project-p))
      "TODO"))))

(defun bh/find-project-task ()
  "Move point to the parent (project) task if any"
  (save-restriction
    (widen)
    (let ((parent-task (save-excursion (org-back-to-heading 'invisible-ok) (point))))
      (while (org-up-heading-safe)
        (when (member (nth 2 (org-heading-components)) org-todo-keywords-1)
          (setq parent-task (point))))
      (goto-char parent-task)
      parent-task)))

(defun bh/punch-in (arg)
  "Start continuous clocking and set the default task to the
selected task.  If no task is selected set the Organization task
as the default task."
  (interactive "p")
  (setq bh/keep-clock-running t)
  (if (equal major-mode 'org-agenda-mode)
      ;;
      ;; We're in the agenda
      ;;
      (let* ((marker (org-get-at-bol 'org-hd-marker))
             (tags (org-with-point-at marker (org-get-tags-at))))
        (if (and (eq arg 4) tags)
            (org-agenda-clock-in '(16))
          (bh/clock-in-organization-task-as-default)))
    ;;
    ;; We are not in the agenda
    ;;
    (save-restriction
      (widen)
      ; Find the tags on the current task
      (if (and (equal major-mode 'org-mode) (not (org-before-first-heading-p)) (eq arg 4))
          (org-clock-in '(16))
        (bh/clock-in-organization-task-as-default)))))

(defun bh/punch-out ()
  (interactive)
  (setq bh/keep-clock-running nil)
  (when (org-clock-is-active)
    (org-clock-out))
  (org-agenda-remove-restriction-lock))

(defun bh/clock-in-default-task ()
  (save-excursion
    (org-with-point-at org-clock-default-task
      (org-clock-in))))

(defun bh/clock-in-parent-task ()
  "Move point to the parent (project) task if any and clock in"
  (let ((parent-task))
    (save-excursion
      (save-restriction
        (widen)
        (while (and (not parent-task) (org-up-heading-safe))
          (when (member (nth 2 (org-heading-components)) org-todo-keywords-1)
            (setq parent-task (point))))
        (if parent-task
            (org-with-point-at parent-task
              (org-clock-in))
          (when bh/keep-clock-running
            (bh/clock-in-default-task)))))))


(defun bh/clock-in-organization-task-as-default ()
  (interactive)
  (org-with-point-at (org-id-find bh/organization-task-id 'marker)
    (org-clock-in '(16))))

(defun bh/clock-out-maybe ()
  (when (and bh/keep-clock-running
             (not org-clock-clocking-in)
             (marker-buffer org-clock-default-task)
             (not org-clock-resolving-clocks-due-to-idleness))
    (bh/clock-in-parent-task)))

(add-hook 'org-clock-out-hook 'bh/clock-out-maybe 'append)

(require 'org-id)
(defun bh/clock-in-task-by-id (id)
  "Clock in a task by id"
  (org-with-point-at (org-id-find id 'marker)
    (org-clock-in nil)))

(defun bh/clock-in-last-task (arg)
  "Clock in the interrupted task if there is one
Skip the default task and get the next one.
A prefix arg forces clock in of the default task."
  (interactive "p")
  (let ((clock-in-to-task
         (cond
          ((eq arg 4) org-clock-default-task)
          ((and (org-clock-is-active)
                (equal org-clock-default-task (cadr org-clock-history)))
           (caddr org-clock-history))
          ((org-clock-is-active) (cadr org-clock-history))
          ((equal org-clock-default-task (car org-clock-history)) (cadr org-clock-history))
          (t (car org-clock-history)))))
    (widen)
    (org-with-point-at clock-in-to-task
      (org-clock-in nil))))

(defun bh/is-project-p ()
  "Any task with a todo keyword subtask"
  (save-restriction
    (widen)
    (let ((has-subtask)
          (subtree-end (save-excursion (org-end-of-subtree t)))
          (is-a-task (member (nth 2 (org-heading-components)) org-todo-keywords-1)))
      (save-excursion
        (forward-line 1)
        (while (and (not has-subtask)
                    (< (point) subtree-end)
                    (re-search-forward "^\*+ " subtree-end t))
          (when (member (org-get-todo-state) org-todo-keywords-1)
            (setq has-subtask t))))
      (and is-a-task has-subtask))))

(defun bh/is-project-subtree-p ()
  "Any task with a todo keyword that is in a project subtree.
Callers of this function already widen the buffer view."
  (let ((task (save-excursion (org-back-to-heading 'invisible-ok)
                              (point))))
    (save-excursion
      (bh/find-project-task)
      (if (equal (point) task)
          nil
        t))))

(defun bh/is-task-p ()
  "Any task with a todo keyword and no subtask"
  (save-restriction
    (widen)
    (let ((has-subtask)
          (subtree-end (save-excursion (org-end-of-subtree t)))
          (is-a-task (member (nth 2 (org-heading-components)) org-todo-keywords-1)))
      (save-excursion
        (forward-line 1)
        (while (and (not has-subtask)
                    (< (point) subtree-end)
                    (re-search-forward "^\*+ " subtree-end t))
          (when (member (org-get-todo-state) org-todo-keywords-1)
            (setq has-subtask t))))
      (and is-a-task (not has-subtask)))))

(defun bh/is-subproject-p ()
  "Any task which is a subtask of another project"
  (let ((is-subproject)
        (is-a-task (member (nth 2 (org-heading-components)) org-todo-keywords-1)))
    (save-excursion
      (while (and (not is-subproject) (org-up-heading-safe))
        (when (member (nth 2 (org-heading-components)) org-todo-keywords-1)
          (setq is-subproject t))))
    (and is-a-task is-subproject)))

(defun bh/list-sublevels-for-projects-indented ()
  "Set org-tags-match-list-sublevels so when restricted to a subtree we list all subtasks.
  This is normally used by skipping functions where this variable is already local to the agenda."
  (if (marker-buffer org-agenda-restrict-begin)
      (setq org-tags-match-list-sublevels 'indented)
    (setq org-tags-match-list-sublevels nil))
  nil)

(defun bh/list-sublevels-for-projects ()
  "Set org-tags-match-list-sublevels so when restricted to a subtree we list all subtasks.
  This is normally used by skipping functions where this variable is already local to the agenda."
  (if (marker-buffer org-agenda-restrict-begin)
      (setq org-tags-match-list-sublevels t)
    (setq org-tags-match-list-sublevels nil))
  nil)

(defvar bh/hide-scheduled-and-waiting-next-tasks t)
(defvar bh/boss-tasks-sheduled 'future)
(defvar bh/boss-tasks-deadline 'far)
(defvar bh/year-tasks-sheduled 'future)
(defvar bh/year-tasks-deadline 'far)
(defvar bh/hide-scheduled-tasks 'future)
(defvar bh/hide-deadlined-tasks 'far)

(defun bh/toggle-next-task-display ()
  (interactive)
  (setq bh/hide-scheduled-and-waiting-next-tasks (not bh/hide-scheduled-and-waiting-next-tasks))
  (if bh/hide-scheduled-and-waiting-next-tasks
  	  (progn
		(setq bh/hide-scheduled-tasks 'future)
		(setq bh/hide-deadlined-tasks 'far)
  		(setq bh/boss-tasks-sheduled 'future)
  		(setq bh/boss-tasks-deadline 'far)
  		(setq bh/year-tasks-sheduled 'future)
  		(setq bh/year-tasks-deadline 'far)
  		)
	(setq bh/boss-tasks-sheduled nil)
    (setq bh/boss-tasks-deadline nil)
	(setq bh/year-tasks-sheduled nil)
    (setq bh/year-tasks-deadline nil)
	(setq bh/hide-scheduled-tasks nil)
	(setq bh/hide-deadlined-tasks nil)

   )

  (when  (equal major-mode 'org-agenda-mode)
    (org-agenda-redo))
  (message "%s WAITING and SCHEDULED NEXT Tasks" (if bh/hide-scheduled-and-waiting-next-tasks "Hide" "Show")))

(defun bh/skip-stuck-projects ()
  "Skip trees that are not stuck projects"
  (save-restriction
    (widen)
    (let ((next-headline (save-excursion (or (outline-next-heading) (point-max)))))
      (if (bh/is-project-p)
          (let* ((subtree-end (save-excursion (org-end-of-subtree t)))
                 (has-next ))
            (save-excursion
              (forward-line 1)
              (while (and (not has-next) (< (point) subtree-end) (re-search-forward "^\\*+ NEXT " subtree-end t))
                (unless (member "WAITING" (org-get-tags-at))
                  (setq has-next t))))
            (if has-next
                nil
              next-headline)) ; a stuck project, has subtasks but no next task
        nil))))

(defun bh/skip-non-stuck-projects ()
  "Skip trees that are not stuck projects"
  ;; (bh/list-sublevels-for-projects-indented)
  (save-restriction
    (widen)
    (let ((next-headline (save-excursion (or (outline-next-heading) (point-max)))))
      (if (bh/is-project-p)
          (let* ((subtree-end (save-excursion (org-end-of-subtree t)))
                 (has-next ))
            (save-excursion
              (forward-line 1)
              (while (and (not has-next) (< (point) subtree-end) (re-search-forward "^\\*+ NEXT " subtree-end t))
                (unless (member "WAITING" (org-get-tags-at))
                  (setq has-next t))))
            (if has-next
                next-headline
              nil)) ; a stuck project, has subtasks but no next task
        next-headline))))

(defun bh/skip-non-projects ()
  "Skip trees that are not projects"
  ;; (bh/list-sublevels-for-projects-indented)
  (if (save-excursion (bh/skip-non-stuck-projects))
      (save-restriction
        (widen)
        (let ((subtree-end (save-excursion (org-end-of-subtree t))))
          (cond
           ((bh/is-project-p)
            nil)
           ((and (bh/is-project-subtree-p) (not (bh/is-task-p)))
            nil)
           (t
            subtree-end))))
    (save-excursion (org-end-of-subtree t))))

(defun bh/skip-project-trees-and-habits ()
  "Skip trees that are projects"
  (save-restriction
    (widen)
    (let ((subtree-end (save-excursion (org-end-of-subtree t))))
      (cond
       ((bh/is-project-p)
        subtree-end)
       ((org-is-habit-p)
        subtree-end)
       (t
        nil)))))

(defun bh/skip-projects-and-habits-and-single-tasks ()
  "Skip trees that are projects, tasks that are habits, single non-project tasks"
  (save-restriction
    (widen)
    (let ((next-headline (save-excursion (or (outline-next-heading) (point-max)))))
      (cond
       ((org-is-habit-p)
        next-headline)
       ((and bh/hide-scheduled-and-waiting-next-tasks
             (member "WAITING" (org-get-tags-at)))
        next-headline)
       ((bh/is-project-p)
        next-headline)
       ((and (bh/is-task-p) (not (bh/is-project-subtree-p)))
        next-headline)
       (t
        nil)))))

(defun bss/show-project-next-tasks-and-standalone ()
  "Show project NEXT-tasks and standalone tasks"
  (save-restriction
    (widen)
    (let ((next-headline (save-excursion (or (outline-next-heading) (point-max)))))
      (cond
       ;; ((org-is-habit-p) ;; если это привычка -- пропускаем
        ;; next-headline)
       ;; ((and bh/hide-scheduled-and-waiting-next-tasks
       ;;       (member "WAITING" (org-get-tags-at)))
       ;;  next-headline)
	   ;; показываем все задачи, если не надо ничего скрывать
       ((not bh/hide-scheduled-and-waiting-next-tasks)
        nil)
       ((bh/is-project-p) ;; если это заголовок проекта -- пропускаем
        next-headline)

	   ;; если это задача, она часть проекта (подзадача проекта) и не в статусе NEXT -- пропускаем
	   ((and (not (member (org-get-todo-state) (list "NEXT"))) (bh/is-project-subtree-p))
        next-headline)

       (t
        nil)))))

(defun bss/skip-projects-if-needed ()
  "Skip project headings, if bh/hide-scheduled-and-waiting-next-tasks is t"
  (save-restriction
    (widen)
    (let ((next-headline (save-excursion (or (outline-next-heading) (point-max)))))
      (cond
;;       ((and bh/hide-scheduled-and-waiting-next-tasks
;;             (member "WAITING" (org-get-tags-at)))
;;        next-headline)
       ((and (bh/is-project-p) bh/hide-scheduled-and-waiting-next-tasks)
        next-headline)
;;       ((and (bh/is-task-p) (not (bh/is-project-subtree-p)))
;;        next-headline)
       (t
        nil)))))



(defun bh/skip-project-tasks-maybe ()
  "Show tasks related to the current restriction.
When restricted to a project, skip project and sub project tasks, habits, NEXT tasks, and loose tasks.
When not restricted, skip project and sub-project tasks, habits, and project related tasks."
  (save-restriction
    (widen)
    (let* ((subtree-end (save-excursion (org-end-of-subtree t)))
           (next-headline (save-excursion (or (outline-next-heading) (point-max))))
           (limit-to-project (marker-buffer org-agenda-restrict-begin)))
      (cond
       ((bh/is-project-p)
        next-headline)
       ((org-is-habit-p)
        subtree-end)
       ((and (not limit-to-project)
             (bh/is-project-subtree-p))
        subtree-end)
       ((and limit-to-project
             (bh/is-project-subtree-p)
             (member (org-get-todo-state) (list "NEXT")))
        subtree-end)
       (t
        nil)))))

(defun bh/skip-project-tasks ()
  "Show non-project tasks.
Skip project and sub-project tasks, habits, and project related tasks."
  (save-restriction
    (widen)
    (let* ((subtree-end (save-excursion (org-end-of-subtree t))))
      (cond
       ((bh/is-project-p)
        subtree-end)
       ((org-is-habit-p)
        subtree-end)
       ((bh/is-project-subtree-p)
        subtree-end)
       (t
        nil)))))

(defun bh/skip-non-project-tasks ()
  "Show project tasks.
Skip project and sub-project tasks, habits, and loose non-project tasks."
  (save-restriction
    (widen)
    (let* ((subtree-end (save-excursion (org-end-of-subtree t)))
           (next-headline (save-excursion (or (outline-next-heading) (point-max)))))
      (cond
       ((bh/is-project-p)
        next-headline)
       ((org-is-habit-p)
        subtree-end)
       ((and (bh/is-project-subtree-p)
             (member (org-get-todo-state) (list "NEXT")))
        subtree-end)
       ((not (bh/is-project-subtree-p))
        subtree-end)
       (t
        nil)))))

(defun bh/skip-projects-and-habits ()
  "Skip trees that are projects and tasks that are habits"
  (save-restriction
    (widen)
    (let ((subtree-end (save-excursion (org-end-of-subtree t))))
      (cond
       ((bh/is-project-p)
        subtree-end)
       ((org-is-habit-p)
        subtree-end)
       (t
        nil)))))

(defun bh/skip-non-subprojects ()
  "Skip trees that are not projects"
  (let ((next-headline (save-excursion (outline-next-heading))))
    (if (bh/is-subproject-p)
        nil
      next-headline)))

;;archive subtree with subtree and tags
;; from: http://orgmode.org/worg/org-hacks.html Preserve top level headings when archiving to a file

(defun my-org-inherited-no-file-tags ()
  (let ((tags (org-entry-get nil "ALLTAGS" 'selective))
        (ltags (org-entry-get nil "TAGS")))
    (mapc (lambda (tag)
            (setq tags
                  (replace-regexp-in-string (concat tag ":") "" tags)))
          (append org-file-tags (when ltags (split-string ltags ":" t))))
    (if (string= ":" tags) nil tags)))

(defadvice org-archive-subtree (around my-org-archive-subtree-low-level activate)
  (let ((tags (my-org-inherited-no-file-tags))
        (org-archive-location
         (if (save-excursion (org-back-to-heading)
                             (> (org-outline-level) 1))
             (concat (car (split-string org-archive-location "::"))
                     "::* "
                     (car (org-get-outline-path)))
           org-archive-location)))
    ad-do-it
    (with-current-buffer (find-file-noselect (org-extract-archive-file))
      (save-excursion
        (while (org-up-heading-safe))
        (org-set-tags-to tags)))))
;;----------------------------------------------------------------------


(defun bh/skip-non-archivable-tasks ()
  "Skip trees that are not available for archiving"
  (save-restriction
    (widen)
    ;; Consider only tasks with done todo headings as archivable candidates
    (let ((next-headline (save-excursion (or (outline-next-heading) (point-max))))
          (subtree-end (save-excursion (org-end-of-subtree t))))
      (if (member (org-get-todo-state) org-todo-keywords-1)
          (if (member (org-get-todo-state) org-done-keywords)
              (let* ((daynr (string-to-int (format-time-string "%d" (current-time))))
                     (a-month-ago (* 60 60 24 (+ daynr 1)))
                     (last-month (format-time-string "%Y-%m-" (time-subtract (current-time) (seconds-to-time a-month-ago))))
                     (this-month (format-time-string "%Y-%m-" (current-time)))
                     (subtree-is-current (save-excursion
                                           (forward-line 1)
                                           (and (< (point) subtree-end)
                                                (re-search-forward (concat last-month "\\|" this-month) subtree-end t)))))
                (if subtree-is-current
                    subtree-end ; Has a date in this month or last month, skip it
                  nil))  ; available to archive
            (or subtree-end (point-max)))
        next-headline))))



;; (global-set-key (kbd "<f5>") 'bh/org-todo)

(defun bh/org-todo (arg)
  (interactive "p")
  (if (equal arg 4)
      (save-restriction
        (bh/narrow-to-org-subtree)
        (org-show-todo-tree nil))
    (bh/narrow-to-org-subtree)
    (org-show-todo-tree nil)))

;; (global-set-key (kbd "<S-f5>") 'bh/widen)

(defun bh/widen ()
  (interactive)
  (if (equal major-mode 'org-agenda-mode)
      (progn
        (org-agenda-remove-restriction-lock)
        (when org-agenda-sticky
          (org-agenda-redo)))
    (widen)))

(add-hook 'org-agenda-mode-hook
          '(lambda () (org-defkey org-agenda-mode-map "W" (lambda () (interactive) (setq bh/hide-scheduled-and-waiting-next-tasks t) (bh/widen))))
          'append)

(defun bh/restrict-to-file-or-follow (arg)
  "Set agenda restriction to 'file or with argument invoke follow mode.
I don't use follow mode very often but I restrict to file all the time
so change the default 'F' binding in the agenda to allow both"
  (interactive "p")
  (if (equal arg 4)
      (org-agenda-follow-mode)
    (widen)
    (bh/set-agenda-restriction-lock 4)
    (org-agenda-redo)
    (beginning-of-buffer)))

(add-hook 'org-agenda-mode-hook
          '(lambda () (org-defkey org-agenda-mode-map "F" 'bh/restrict-to-file-or-follow))
          'append)

(defun bh/narrow-to-org-subtree ()
  (widen)
  (org-narrow-to-subtree)
  (save-restriction
    (org-agenda-set-restriction-lock)))

(defun bh/narrow-to-subtree ()
  (interactive)
  (if (equal major-mode 'org-agenda-mode)
      (progn
        (org-with-point-at (org-get-at-bol 'org-hd-marker)
          (bh/narrow-to-org-subtree))
        (when org-agenda-sticky
          (org-agenda-redo)))
    (bh/narrow-to-org-subtree)))

(add-hook 'org-agenda-mode-hook
          '(lambda () (org-defkey org-agenda-mode-map "N" 'bh/narrow-to-subtree))
          'append)

(defun bh/narrow-up-one-org-level ()
  (widen)
  (save-excursion
    (outline-up-heading 1 'invisible-ok)
    (bh/narrow-to-org-subtree)))

(defun bh/get-pom-from-agenda-restriction-or-point ()
  (or (and (marker-position org-agenda-restrict-begin) org-agenda-restrict-begin)
      (org-get-at-bol 'org-hd-marker)
      (and (equal major-mode 'org-mode) (point))
      org-clock-marker))

(defun bh/narrow-up-one-level ()
  (interactive)
  (if (equal major-mode 'org-agenda-mode)
      (progn
        (org-with-point-at (bh/get-pom-from-agenda-restriction-or-point)
          (bh/narrow-up-one-org-level))
        (org-agenda-redo))
    (bh/narrow-up-one-org-level)))

(add-hook 'org-agenda-mode-hook
          '(lambda () (org-defkey org-agenda-mode-map "U" 'bh/narrow-up-one-level))
          'append)

(defun bh/narrow-to-org-project ()
  (widen)
  (save-excursion
    (bh/find-project-task)
    (bh/narrow-to-org-subtree)))

(defun bh/narrow-to-project ()
  (interactive)
  (if (equal major-mode 'org-agenda-mode)
      (progn
        (org-with-point-at (bh/get-pom-from-agenda-restriction-or-point)
          (bh/narrow-to-org-project)
          (save-excursion
            (bh/find-project-task)
            (org-agenda-set-restriction-lock)))
        (org-agenda-redo)
        (beginning-of-buffer))
    (bh/narrow-to-org-project)
    (save-restriction
      (org-agenda-set-restriction-lock))))

(add-hook 'org-agenda-mode-hook
          '(lambda () (org-defkey org-agenda-mode-map "P" 'bh/narrow-to-project))
          'append)

(defvar bh/project-list nil)

(defun bh/view-next-project ()
  (interactive)
  (let (num-project-left current-project)
    (unless (marker-position org-agenda-restrict-begin)
      (goto-char (point-min))
      ; Clear all of the existing markers on the list
      (while bh/project-list
        (set-marker (pop bh/project-list) nil))
      (re-search-forward "Tasks to Refile")
      (forward-visible-line 1))

    ; Build a new project marker list
    (unless bh/project-list
      (while (< (point) (point-max))
        (while (and (< (point) (point-max))
                    (or (not (org-get-at-bol 'org-hd-marker))
                        (org-with-point-at (org-get-at-bol 'org-hd-marker)
                          (or (not (bh/is-project-p))
                              (bh/is-project-subtree-p)))))
          (forward-visible-line 1))
        (when (< (point) (point-max))
          (add-to-list 'bh/project-list (copy-marker (org-get-at-bol 'org-hd-marker)) 'append))
        (forward-visible-line 1)))

    ; Pop off the first marker on the list and display
    (setq current-project (pop bh/project-list))
    (when current-project
      (org-with-point-at current-project
        (setq bh/hide-scheduled-and-waiting-next-tasks nil)
        (bh/narrow-to-project))
      ; Remove the marker
      (setq current-project nil)
      (org-agenda-redo)
      (beginning-of-buffer)
      (setq num-projects-left (length bh/project-list))
      (if (> num-projects-left 0)
          (message "%s projects left to view" num-projects-left)
        (beginning-of-buffer)
        (setq bh/hide-scheduled-and-waiting-next-tasks t)
        (error "All projects viewed.")))))

(add-hook 'org-agenda-mode-hook
          '(lambda () (org-defkey org-agenda-mode-map "V" 'bh/view-next-project))
          'append)

;; norang bss disabled
;;(setq org-show-entry-below (quote ((default))))

(add-hook 'org-agenda-mode-hook
          '(lambda () (org-defkey org-agenda-mode-map "\C-c\C-x<" 'bh/set-agenda-restriction-lock))
          'append)

(defun bh/set-agenda-restriction-lock (arg)
  "Set restriction lock to current task subtree or file if prefix is specified"
  (interactive "p")
  (let* ((pom (bh/get-pom-from-agenda-restriction-or-point))
         (tags (org-with-point-at pom (org-get-tags-at))))
    (let ((restriction-type (if (equal arg 4) 'file 'subtree)))
      (save-restriction
        (cond
         ((and (equal major-mode 'org-agenda-mode) pom)
          (org-with-point-at pom
            (org-agenda-set-restriction-lock restriction-type))
          (org-agenda-redo))
         ((and (equal major-mode 'org-mode) (org-before-first-heading-p))
          (org-agenda-set-restriction-lock 'file))
         (pom
          (org-with-point-at pom
            (org-agenda-set-restriction-lock restriction-type))))))))


(defun bh/show-org-agenda ()
  (interactive)
  (if org-agenda-sticky
      (switch-to-buffer "*Org Agenda( )*")
    (switch-to-buffer "*Org Agenda*"))
  (delete-other-windows))

(require 'org-protocol)


(defvar bh/insert-inactive-timestamp t)

(defun bh/toggle-insert-inactive-timestamp ()
  (interactive)
  (setq bh/insert-inactive-timestamp (not bh/insert-inactive-timestamp))
  (message "Heading timestamps are %s" (if bh/insert-inactive-timestamp "ON" "OFF")))

(defun bh/insert-inactive-timestamp ()
  (interactive)
  (org-insert-time-stamp nil t t nil nil nil)
  (insert " ")
  )

(defun bh/insert-heading-inactive-timestamp ()
  (save-excursion
    (when bh/insert-inactive-timestamp
      (org-return)
      (org-cycle)
      (bh/insert-inactive-timestamp))))

(add-hook 'org-insert-heading-hook 'bh/insert-heading-inactive-timestamp 'append)

;; Если мы в начали или конце строчки после ссылки, то вставка перевода строки вместо перехода
(defun bss/my-org-return ()
  "Insert newline if we at beginng or end of line"
  (interactive)
  (deactivate-mark)
  (if (evil-normal-state-p)
	  (progn ;;we in evil mode
		(setq need-return t)
		(setq pos (point))
		(end-of-line)
		;; (message "eol diff: %d, op: %s" (- (point) pos) (> 2 (- (point) pos)))
		(if (> 2 (- (point) pos))
			(progn
			  (evil-open-below 1)
			  (evil-normal-state)
			  (setq need-return nil)))
		(beginning-of-line)
		;; (message "bol diff: %d, op %s" (- pos (point) )(> 1 (- pos (point) )))
		(if (and (> 1 (- pos (point) )) need-return)
			(progn
			  (evil-open-above 1)
			  (evil-normal-state)
			  (setq need-return nil)))
		(goto-char pos)
		(if need-return
			(progn
			  ;; (message "org-return")
			  (org-return)
			  )))
  (if (or (eolp) (bolp))
	  ;; (newline-and-indent)
	  (newline)
	(org-return))))

(add-to-list 'org-file-apps '(directory . emacs))


(defun bh/prepare-meeting-notes ()
  "Prepare meeting notes for email
   Take selected region and convert tabs to spaces, mark TODOs with leading >>>, and copy to kill ring for pasting"
  (interactive)
  (let (prefix)
    (save-excursion
      (save-restriction
        (narrow-to-region (region-beginning) (region-end))
        (untabify (point-min) (point-max))
        (goto-char (point-min))
        (while (re-search-forward "^\\( *-\\\) \\(TODO\\|DONE\\): " (point-max) t)
          (replace-match (concat (make-string (length (match-string 1)) ?>) " " (match-string 2) ": ")))
        (goto-char (point-min))
        (kill-ring-save (point-min) (point-max))))))


(defun bh/mark-next-parent-tasks-todo ()
  "Visit each parent task and change NEXT states to TODO"
  (let ((mystate (or (and (fboundp 'org-state)
                          state)
                     (nth 2 (org-heading-components)))))
    (when mystate
      (save-excursion
        (while (org-up-heading-safe)
          (when (member (nth 2 (org-heading-components)) (list "NEXT"))
            (org-todo "TODO")))))))

(add-hook 'org-after-todo-state-change-hook 'bh/mark-next-parent-tasks-todo 'append)
(add-hook 'org-clock-in-hook 'bh/mark-next-parent-tasks-todo 'append)



(add-hook 'message-mode-hook 'orgstruct++-mode 'append)
(add-hook 'message-mode-hook 'turn-on-auto-fill 'append)
(add-hook 'message-mode-hook 'bbdb-define-all-aliases 'append)
(add-hook 'message-mode-hook 'orgtbl-mode 'append)
(add-hook 'message-mode-hook 'turn-on-flyspell 'append)
(add-hook 'message-mode-hook
          '(lambda () (setq fill-column 72))
          'append)


(defun bh/mail-subtree ()
  (interactive)
  (org-mark-subtree)
  (org-mime-subtree))


(defun bss/org-schedule (arg)
  "selective org-todo"
  (interactive "P")
  (if (equal major-mode 'org-agenda-mode)
	  (org-agenda-schedule arg)
	  (org-schedule arg)
  ))
(defun bss/org-todo ()
  "selective org-todo"
  (interactive)
  (if (equal major-mode 'org-agenda-mode)
	  (org-agenda-todo)
	  (org-todo)
  ))
(defun bss/org-refile ()
  "selective org-refile"
  (interactive)
  (if (equal major-mode 'org-agenda-mode)
	  (org-agenda-refile)
	  (org-refile)
  ))

tags

;;;; Org-tags settings
; Tags with fast selection keys
(setq org-tag-alist (quote ((:startgroup)
                            ("@office" . ?o)
                            ("@home" . ?h)
                            ("@finances" . ?f)
                            ("@Farm" . ?F)
                            (:endgroup)
                            ("WAITING" . ?W)
                            ("HOLD" . ?H)
                            ("PERSONAL" . ?P)
                            ("BOSS" . ?b)
                            ("URGENT" . ?u)
                            ("YEAR" . ?y)
							("КУПИ" . ?k)
                            ("FARM" . ?F)
                            ("crypt" . ?C)
                            ("NOTE" . ?n)
                            ("CANCELLED" . ?c)
                            ("FLAGGED" . ??))))

; Allow setting single tags without the menu
;; (setq org-fast-tag-selection-single-key (quote expert))
(setq org-fast-tag-selection-single-key t)

; For tag searches ignore tasks with scheduled and deadline dates
(setq org-agenda-tags-todo-honor-ignore-options t)

org-clock

(require 'org-clock)
(setq org-clock-clocked-in-display 'frame-title)
;; Turn org-clock sound on
(setq org-clock-sound "~/.emacs.d/manual-addons/tada.wav")
;;(play-sound-file "~/.emacs.d/manual-addons/tada.wav")

org-mac-link

(use-package org-mac-link
:config

;; key to grab mac links
(define-key org-mode-map (kbd "C-c g") 'org-mac-grab-link)

(defun org-as-get-selected-mail ()
  "AppleScript to create links to selected messages in Mail.app."
  (do-applescript
   (concat
    "tell application \"Mail\"\n"
    "set theLinkList to {}\n"
    "set theSelection to selection\n"
    "repeat with theMessage in theSelection\n"
    "set theID to message id of theMessage\n"
    "set theSender to extract name from sender of theMessage\n"
	"set theDateReceived to (date received) of theMessage\n"
	;; "set theDate to (format date (theDateReceived) with format \"%m, %d %Y\")\n"
    ;; "set theLink to \"message://\" & theID & \"::split::\" & theDate & \"(\" & theDateReceived & \") \" & theSubject & \" (\" & theSender & \")\" \n"
    "set theSubject to subject of theMessage\n"
    "set theLink to \"message://\" & theID & \"::split::\" & \"(\" & theDateReceived & \") \" & theSubject & \" (\" & theSender & \")\" \n"
    "if (theLinkList is not equal to {}) then\n"
    "set theLink to \"\n\" & theLink\n"
    "end if\n"
    "copy theLink to end of theLinkList\n"
    "end repeat\n"
    "return theLinkList as string\n"
    "end tell")))

(defun org-as-get-selected-outlook-mail ()
  "AppleScript to create links to selected messages in Microsoft Outlook.app."
  (do-applescript
   (concat
    "tell application \"/Applications/Microsoft Outlook.app\"\n"
    "set msgCount to count current messages\n"
    "if (msgCount < 1) then\n"
    "return\n"
    "end if\n"
    "set theLinkList to {}\n"
    "set theSelection to (get current messages)\n"
    "repeat with theMessage in theSelection\n"
    "set theID to id of theMessage as string\n"
    "set theURL to \"mac-outlook:\" & theID\n"
    "set theSubject to subject of theMessage\n"
	"set theSender to sender of theMessage\n"
	;; "set theDateReceived to date string of (get time sent of item 1 of theSelection)\n"
	"set theDateReceived to date string of (get time sent of theMessage)\n"
    ;; "set theLink to theURL & \"::split::\" & theSubject & \"\n\"\n"
    "set theLink to theURL & \"::split::\" & \"(\" & theDateReceived & \") \" & theSubject & \" (\" & name of theSender & \")\" \n"
    "copy theLink to end of theLinkList\n"
    "end repeat\n"
    "return theLinkList as string\n"
    "end tell")))

(defun org-mac-outlook-message-open (msgid)
  "Open a message in Outlook"
  (do-applescript
   (concat
    "tell application \"/Applications/Microsoft Outlook.app\"\n"
    (format "open message id %s\n" (substring-no-properties msgid))
    "activate\n"
    "end tell")))


(defun org-mac-outlook-message-get-links (&optional select-or-flag)
  "Create links to the messages currently selected or flagged in Microsoft Outlook.app.
This will use AppleScript to get the message-id and the subject of the
messages in Microsoft Outlook.app and make a link out of it.
When SELECT-OR-FLAG is \"s\", get the selected messages (this is also
the default).  When SELECT-OR-FLAG is \"f\", get the flagged messages.
The Org-syntax text will be pushed to the kill ring, and also returned."
  (interactive "sLink to (s)elected or (f)lagged messages: ")
  (setq select-or-flag (or select-or-flag "s"))
  (message "Org Mac Outlook: searching mailboxes...")
  (let* ((as-link-list
          (if (string= select-or-flag "s")
              (org-as-get-selected-outlook-mail)
	    (if (string= select-or-flag "f")
		(org-sh-get-flagged-outlook-mail)
	      (error "Please select \"s\" or \"f\""))))
		 (message "1")
         (link-list
          (mapcar
           (lambda (x) (if (string-match "\\`\"\\(.*\\)\"\\'" x) (setq x (match-string 1 x))) x)
           (split-string as-link-list "[\r\n]+")))
		 (message "2")
         split-link URL description orglink orglink-insert rtn orglink-list)
    (while link-list
      (setq split-link (split-string (pop link-list) "::split::"))
      (setq URL (car split-link))
      (setq description (cadr split-link))
      (when (not (or (string= URL "") (string= URL "\"")))
		(if (string= (substring URL 0 1) "\"")
			(setq URL (substring URL 1 nil)))
		(message URL)
        (setq orglink (org-make-link-string URL description))
        (push orglink orglink-list)))
    (setq rtn (mapconcat 'identity orglink-list "\n"))
    (kill-new rtn)
    rtn))

;; )
)

org-protocol (Windows only outlook integration)

;; (use-package org-protocol)

;; (use-package org-outlook)
;; (setq org-outlook-location (w32-short-file-name "c:/Program Files (x86)/Microsoft Office/OFFICE15/OUTLOOK.exe"))

;;------------------------------------------------------------
;; Run this on install
;; The macro gets the unique id for the email message and writes an Org Mode link to that message to the clip board. When I first ran the macro, I actually got an error saying “Compile error: User-defined type not defined.” That was a little mysterious. In order to fix that error:
;; Macro content: --------------------
;; 'Adds a link to the currently selected message to the clipboard
;; Sub AddLinkToMessageInClipboard()
;;
;;    Dim objMail As Outlook.MailItem
;;    Dim doClipboard As New DataObject
;;
;;    'One and ONLY one message muse be selected
;;    If Application.ActiveExplorer.Selection.Count <> 1 Then
;;        MsgBox ("Select one and ONLY one message.")
;;        Exit Sub
;;    End If
;;
;;    Set objMail = Application.ActiveExplorer.Selection.Item(1)
;;    doClipboard.SetText "[" + Format(objMail.ReceivedTime, "yyyy-mm-dd ddd Hh:Nn") + "] [[outlook:" + objMail.EntryID + "][MESSAGE: " + Replace(Replace(objMail.Subject, "[", "{"), "]", "}") + " (" + objMail.SenderName + ")]]"
;;    doClipboard.PutInClipboard
;;
;; End Sub
;; Macro content: --------------------
;;
;; For install it needed some configuration in outlook macros editor
;; Click “Tools” then “References” in the menu.
;; Check “Microsoft Forms 2.0 Object Library” in the list of available references.
;; This option wasn’t available to me at first so I clicked “Browse”
;; Then I opened “c:\windows\system32\FM20.DLL”
;; Then I clicked “OK”


;; for open link to message directly from org-mode. Check oyour own outlook.exe place, it differs.
;;outlook.reg :
;;Windows Registry Editor Version 5.00
;;
;;[HKEY_CLASSES_ROOT\outlook]
;;"URL Protocol"=""
;;@="URL:Outlook Folders"
;;
;;[HKEY_CLASSES_ROOT\outlook\DefaultIcon]
;;@="\"C:\\Program Files (x86)\\Microsoft Office\\office15\\OUTLOOK.EXE\""
;;
;;[HKEY_CLASSES_ROOT\outlook\shell]
;;@="open"
;;
;;[HKEY_CLASSES_ROOT\outlook\shell\open]
;;@=""
;;
;;[HKEY_CLASSES_ROOT\outlook\shell\open\command]
;;@="\"C:\\Program Files (x86)\\Microsoft Office\\office15\\OUTLOOK.EXE\" /select \"%1\""

org-babel settings

;; Explicitly load required exporters
(require 'ox-html)
(require 'ox-latex)
(require 'ox-ascii)

;; (setq org-src-tab-acts-natively t)
(setq org-edit-src-auto-save-idle-delay 1
      org-edit-src-turn-on-auto-save nil)



(setq org-ditaa-jar-path "~/notes/org-mode/contrib/scripts/ditaa.jar")
(setq org-plantuml-jar-path "~/java/plantuml.jar")

(add-hook 'org-babel-after-execute-hook 'bh/display-inline-images 'append)

; Make babel results blocks lowercase
(setq org-babel-results-keyword "results")

(defun bh/display-inline-images ()
  (condition-case nil
      (org-display-inline-images)
    (error nil)))

(org-babel-do-load-languages
 (quote org-babel-load-languages)
 (quote ((emacs-lisp . t)
         (dot . t)
         (ditaa . t)
         (R . t) ;; sudo apt-get install r-recommended r-doc-info r-doc-pdf r-mathlib r-base-html r-doc-html
         (python . t)
         (ruby . t)
         (gnuplot . t)
         (clojure . t)
         (shell . t)
         (ledger . t)
         (org . t)
         (plantuml . t)
         (latex . t)
		 (calc . t))))

; Do not prompt to confirm evaluation
; This may be dangerous - make sure you understand the consequences
; of setting this -- see the docstring for details
(setq org-confirm-babel-evaluate nil)

; Use fundamental mode when editing plantuml blocks with C-c '
(add-to-list 'org-src-lang-modes (quote ("plantuml" . fundamental)))

;; Don't enable this because it breaks access to emacs from my Android phone
(setq org-startup-with-inline-images nil)

; experimenting with docbook exports - not finished
(setq org-export-docbook-xsl-fo-proc-command "fop %s %s")
(setq org-export-docbook-xslt-proc-command "xsltproc --output %s /usr/share/xml/docbook/stylesheet/nwalsh/fo/docbook.xsl %s")
;
; Inline images in HTML instead of producting links to the image
(setq org-html-inline-images t)
; Do not use sub or superscripts - I currently don't need this functionality in my documents
(setq org-export-with-sub-superscripts nil)
; Use org.css from the norang website for export document stylesheets
(setq org-html-head-extra "<link rel=\"stylesheet\" href=\"http://doc.norang.ca/org.css\" type=\"text/css\" />")
(setq org-html-head-include-default-style nil)
; Do not generate internal css formatting for HTML exports
(setq org-export-htmlize-output-type (quote css))
; Export with LaTeX fragments
(setq org-export-with-LaTeX-fragments t)
; Increase default number of headings to export
(setq org-export-headline-levels 6)

;; fontify code in code blocks
(setq org-src-fontify-natively t)
(setq org-src-tab-acts-natively t)

;; https://lists.gnu.org/archive/html/emacs-orgmode/2013-11/msg00318.html
;; http://emacs-orgmode.gnu.narkive.com/5qo0jqjh/o-patch-make-comment-dwim-in-source-code-blocks-more-dwim-ish
;; allow comment region in the code edit buffer (according to language)
;;ok  (defun my-org-comment-dwim (&optional arg)
;;ok    (interactive "p")
;;ok    ;; (or (org-babel-do-key-sequence-in-edit-buffer (kbd "m-;"))
;;ok    (or (org-babel-do-key-sequence-in-edit-buffer (kbd "<f4>"))
;;ok        (comment-dwim arg)
;;ok    ))
(defun my-org-comment-dwim (&optional arg)
  (interactive "p")
  (or (org-babel-do-key-sequence-in-edit-buffer (kbd "<f4>"))
      (comment-dwim arg)
  ))

;; make `c-c c-v c-x m-;' more convenient
(define-key org-mode-map
  (kbd "M-;") 'my-org-comment-dwim)     ;

;; (define-key evil-normal-state-map (kbd "<f4>") '(lambda () (interactive) (evilnc-comment-or-uncomment-lines 1)))

; List of projects
; norang       - http://www.norang.ca/
; doc          - http://doc.norang.ca/
; org-mode-doc - http://doc.norang.ca/org-mode.html and associated files
; org          - miscellaneous todo lists for publishing
(setq org-publish-project-alist
      ;
      ; http://www.norang.ca/  (norang website)
      ; norang-org are the org-files that generate the content
      ; norang-extra are images and css files that need to be included
      ; norang is the top-level project that gets published
      (quote (("norang-org"
               :base-directory "~/git/www.norang.ca"
               :publishing-directory "/ssh:www-data@www:~/www.norang.ca/htdocs"
               :recursive t
               :table-of-contents nil
               :base-extension "org"
               :publishing-function org-html-publish-to-html
               :style-include-default nil
               :section-numbers nil
               :table-of-contents nil
               :html-head "<link rel=\"stylesheet\" href=\"norang.css\" type=\"text/css\" />"
               :author-info nil
               :creator-info nil)
              ("norang-extra"
               :base-directory "~/git/www.norang.ca/"
               :publishing-directory "/ssh:www-data@www:~/www.norang.ca/htdocs"
               :base-extension "css\\|pdf\\|png\\|jpg\\|gif"
               :publishing-function org-publish-attachment
               :recursive t
               :author nil)
              ("norang"
               :components ("norang-org" "norang-extra"))
              ;
              ; http://doc.norang.ca/  (norang website)
              ; doc-org are the org-files that generate the content
              ; doc-extra are images and css files that need to be included
              ; doc is the top-level project that gets published
              ("doc-org"
               :base-directory "~/git/doc.norang.ca/"
               :publishing-directory "/ssh:www-data@www:~/doc.norang.ca/htdocs"
               :recursive nil
               :section-numbers nil
               :table-of-contents nil
               :base-extension "org"
               :publishing-function (org-html-publish-to-html org-org-publish-to-org)
               :style-include-default nil
               :html-head "<link rel=\"stylesheet\" href=\"/org.css\" type=\"text/css\" />"
               :author-info nil
               :creator-info nil)
              ("doc-extra"
               :base-directory "~/git/doc.norang.ca/"
               :publishing-directory "/ssh:www-data@www:~/doc.norang.ca/htdocs"
               :base-extension "css\\|pdf\\|png\\|jpg\\|gif"
               :publishing-function org-publish-attachment
               :recursive nil
               :author nil)
              ("doc"
               :components ("doc-org" "doc-extra"))
              ("doc-private-org"
               :base-directory "~/git/doc.norang.ca/private"
               :publishing-directory "/ssh:www-data@www:~/doc.norang.ca/htdocs/private"
               :recursive nil
               :section-numbers nil
               :table-of-contents nil
               :base-extension "org"
               :publishing-function (org-html-publish-to-html org-org-publish-to-org)
               :style-include-default nil
               :html-head "<link rel=\"stylesheet\" href=\"/org.css\" type=\"text/css\" />"
               :auto-sitemap t
               :sitemap-filename "index.html"
               :sitemap-title "Norang Private Documents"
               :sitemap-style "tree"
               :author-info nil
               :creator-info nil)
              ("doc-private-extra"
               :base-directory "~/git/doc.norang.ca/private"
               :publishing-directory "/ssh:www-data@www:~/doc.norang.ca/htdocs/private"
               :base-extension "css\\|pdf\\|png\\|jpg\\|gif"
               :publishing-function org-publish-attachment
               :recursive nil
               :author nil)
              ("doc-private"
               :components ("doc-private-org" "doc-private-extra"))
              ;
              ; Miscellaneous pages for other websites
              ; org are the org-files that generate the content
              ("org-org"
               :base-directory "~/git/org/"
               :publishing-directory "/ssh:www-data@www:~/org"
               :recursive t
               :section-numbers nil
               :table-of-contents nil
               :base-extension "org"
               :publishing-function org-html-publish-to-html
               :style-include-default nil
               :html-head "<link rel=\"stylesheet\" href=\"/org.css\" type=\"text/css\" />"
               :author-info nil
               :creator-info nil)
              ;
              ; http://doc.norang.ca/  (norang website)
              ; org-mode-doc-org this document
              ; org-mode-doc-extra are images and css files that need to be included
              ; org-mode-doc is the top-level project that gets published
              ; This uses the same target directory as the 'doc' project
              ("org-mode-doc-org"
               :base-directory "~/git/org-mode-doc/"
               :publishing-directory "/ssh:www-data@www:~/doc.norang.ca/htdocs"
               :recursive t
               :section-numbers nil
               :table-of-contents nil
               :base-extension "org"
               :publishing-function (org-html-publish-to-html)
               :plain-source t
               :htmlized-source t
               :style-include-default nil
               :html-head "<link rel=\"stylesheet\" href=\"/org.css\" type=\"text/css\" />"
               :author-info nil
               :creator-info nil)
              ("org-mode-doc-extra"
               :base-directory "~/git/org-mode-doc/"
               :publishing-directory "/ssh:www-data@www:~/doc.norang.ca/htdocs"
               :base-extension "css\\|pdf\\|png\\|jpg\\|gif\\|org"
               :publishing-function org-publish-attachment
               :recursive t
               :author nil)
              ("org-mode-doc"
               :components ("org-mode-doc-org" "org-mode-doc-extra"))
              ;
              ; http://doc.norang.ca/  (norang website)
              ; org-mode-doc-org this document
              ; org-mode-doc-extra are images and css files that need to be included
              ; org-mode-doc is the top-level project that gets published
              ; This uses the same target directory as the 'doc' project
              ("tmp-org"
               :base-directory "/tmp/publish/"
               :publishing-directory "/ssh:www-data@www:~/www.norang.ca/htdocs/tmp"
               :recursive t
               :section-numbers nil
               :table-of-contents nil
               :base-extension "org"
               :publishing-function (org-html-publish-to-html org-org-publish-to-org)
               :html-head "<link rel=\"stylesheet\" href=\"http://doc.norang.ca/org.css\" type=\"text/css\" />"
               :plain-source t
               :htmlized-source t
               :style-include-default nil
               :auto-sitemap t
               :sitemap-filename "index.html"
               :sitemap-title "Test Publishing Area"
               :sitemap-style "tree"
               :author-info t
               :creator-info t)
              ("tmp-extra"
               :base-directory "/tmp/publish/"
               :publishing-directory "/ssh:www-data@www:~/www.norang.ca/htdocs/tmp"
               :base-extension "css\\|pdf\\|png\\|jpg\\|gif"
               :publishing-function org-publish-attachment
               :recursive t
               :author nil)
              ("tmp"
               :components ("tmp-org" "tmp-extra")))))

; I'm lazy and don't want to remember the name of the project to publish when I modify
; a file that is part of a project.  So this function saves the file, and publishes
; the project that includes this file
;
; It's bound to C-S-F12 so I just edit and hit C-S-F12 when I'm done and move on to the next thing
(defun bh/save-then-publish (&optional force)
  (interactive "P")
  (save-buffer)
  (org-save-all-org-buffers)
  (let ((org-html-head-extra)
        (org-html-validation-link "<a href=\"http://validator.w3.org/check?uri=referer\">Validate XHTML 1.0</a>"))
    (org-publish-current-project force)))

(global-set-key (kbd "C-s-<f12>") 'bh/save-then-publish)

(setq org-latex-listings t)

(setq org-html-xml-declaration (quote (("html" . "")
                                       ("was-html" . "<?xml version=\"1.0\" encoding=\"%s\"?>")
                                       ("php" . "<?php echo \"<?xml version=\\\"1.0\\\" encoding=\\\"%s\\\" ?>\"; ?>"))))

(setq org-export-allow-BIND t)

org-time-budgets

Org-mode agenda WEEKLY BUDGETS time budgets in agenda: org-time-budgets https://github.com/leoc/org-time-budgets agenda need this addon (setq org-agenda-custom-commands (quote ((” ” “Agenda” ((agenda “” ((org-agenda-skip-function ‘(zin/org-agenda-skip-tag “ROUTINE” ‘nil)))) ;; WEEKLY BUDGETS dont forget add this ------> (bss/org-time-budgets-in-agenda)

;; (setq org-time-budgets-enabled t)
(setq org-time-budgets-enabled nil)
(setq org-habit-show-habits t)
(defun bss/org-toggle-budgets-and-habits ()
  (interactive)
  ;; (setq org-time-budgets-enabled (not org-time-budgets-enabled))
  (setq org-time-budgets-enabled (not org-habit-show-habits))
  (org-habit-toggle-habits)
  (message "Budgets and habits turned %s"
		   (if org-time-budgets-enabled "on" "off"))
  )

(use-package org-time-budgets)
(setq org-time-budgets '((:title "Служебные проекты" :tags "+@office+project" :budget "20:00" :block workweek)
						 (:title "Личные проекты" :tags "+@personal+project" :budget "14:00" :block week)
						 ))
(defun bss/org-time-budgets-in-agenda (arg)
  "Inhibit read-only and return the `org-time-budget-table'."
  (if org-time-budgets-enabled
	  (org-time-budgets-in-agenda arg)))

(if org-time-budgets-enabled
    (progn
      (run-at-time "6:00" 86400 '(lambda ()
                                   (setq org-habit-show-habits nil)
                                   ;; (setq org-time-budgets-enabled t)
                                   (condition-case nil
                                       (progn
                                         (org-agenda-filter-remove-all)
                                         (org-habit-toggle-habits)
                                         )
                                     (error nil))
                                   ))

      (run-at-time "17:00" 86400 '(lambda ()
                                    (setq org-habit-show-habits nil)
                                    ;; (setq org-time-budgets-enabled t)
                                    (condition-case nil
                                        (progn
                                          (org-agenda-filter-remove-all)
                                          (org-habit-toggle-habits)
                                          )
                                      (error nil))
                                    ))
      ))

appointments settings

;;;; Org-mode appointments setting

; Erase all reminders and rebuilt reminders for today from the agenda
(defun bh/org-agenda-to-appt ()
  (interactive)
  (setq appt-time-msg-list nil)
  (org-agenda-to-appt))

; Rebuild the reminders everytime the agenda is displayed
(add-hook 'org-finalize-agenda-hook 'bh/org-agenda-to-appt 'append)

; This is at the end of my .emacs - so appointments are set up when Emacs starts
(bh/org-agenda-to-appt)

; Activate appointments so we get notifications
(appt-activate t)

; If we leave Emacs running overnight - reset the appointments one minute after midnight
(run-at-time "24:01" nil 'bh/org-agenda-to-appt)



;;---------------
;; add notify via notify-send
;; http://emacs-fu.blogspot.ru/2009/11/showing-pop-ups.html

(defun djcb-popup (title msg &optional icon sound)
  "Show a popup if we're on X, or echo it otherwise; TITLE is the title
of the message, MSG is the context. Optionally, you can provide an ICON and
a sound to be played"

  (interactive)
  (when sound (shell-command (concat "mplayer -really-quiet " sound " 2> /dev/null")))
  (if (eq window-system 'x)
    (shell-command (concat "notify-send -t 0 " (if icon (concat "-i " icon) "") " '" title "' '" msg "'")) (message (concat title ": " msg)))
  (if (or (eq window-system 'ns) (eq window-system 'mac))
    (shell-command (concat "/usr/local/bin/terminal-notifier -activate org.gnu.Emacs -sound default -title '" title "' -message '" msg "'")) (message (concat title ": " msg)))
  )

;; sample message
;; (djcb-popup "Warning" "The end is near"
			;; "/usr/share/icons/test.png"
			;; "~/.emacs.d/manual-addons/sounds/phone-incoming-call.oga")

;; our little façade-function for djcb-popup
(if (or (eq system-type 'gnu/linux) (eq system-type 'darwin))
	(progn
	  (defun djcb-appt-display (min-to-app new-time msg)
		(djcb-popup (format "Appointment in %s minute(s)" min-to-app) msg
					"~/.emacs.d/manual-addons/my-appt-sounds/appointment-soon.png"
					"~/.emacs.d/manual-addons/my-appt-sounds/phone-incoming-call.oga"))
	  (setq appt-disp-window-function (function djcb-appt-display))))

org-table

;;table preferences
(setq org-table-use-standard-references (quote from))

;;----------------------------------------
;;http://stackoverflow.com/questions/4673100/how-to-specify-big-multi-line-tables
(use-package table)
;; To convert back & forth between the two types of tables, do Ctrl-C ~
;; Create an empty file or buffer, type
;; M-x table-insert RET
;; You can get some documentation with

;; C-h f table-insert RET
;; To find more documentation, you'll need to locate the source code. Start with

;; M-x locate-library RET table RET
;; This will show you the location of the byte-compiled lisp file for table-mode, and in that same directory you should fine table.el or table.el.gz, which will contain documentation you'll need to at least skim. Most linux systems (foolishly) do not install the .el files by default, so you'll have to go rooting around with the package manager to get them.

;; I was fairly sure that org-mode knew how to parse table-mode tables and format them for you, but I can't seem to find that written down anywhere right now.

encryption

; GPG key to use for encryption
(require 'epa-file)
(epa-file-enable)
;;(setq org-crypt-disable-auto-save nil)


(require 'org-crypt)
; Encrypt all entries before saving
(org-crypt-use-before-save-magic)
(setq org-tags-exclude-from-inheritance (quote ("crypt")))
(setq org-crypt-disable-auto-save 'encrypt)
(setq org-crypt-key nil)
;; http://emacs.stackexchange.com/questions/12212/how-to-type-the-password-of-a-gpg-file-only-when-opening-it
;;(setq org-crypt-key "F581B488")
(setq epa-file-cache-passphrase-for-symmetric-encryption t)

;; ;; Enable encryption
;; (setq org-mobile-use-encryption t)
;; ;; Set a password
;; (setq org-mobile-encryption-password "mypassword)(&*(#@(%#*^%!*&#@^%($)!&^$)")

agenda settings

Custom agenda command definitions

;; фильтр по-умолчанию отключает дачу и личное
(defun bh/org-auto-exclude-function (tag)
  "Automatic task exclusion in the agenda with / RET"
  (and (cond
        ;; ((string= tag "hold") t)
        ((string= tag "@farm") t)
        ((string= tag "@personal") t))
       (concat "-" tag)))
(setq org-agenda-auto-exclude-function 'bh/org-auto-exclude-function)



(setq org-agenda-custom-commands
      (quote (("N" "Notes" tags "NOTE"
               ((org-agenda-overriding-header "Notes")
                (org-tags-match-list-sublevels t)))
              ("h" "Habits" tags-todo "STYLE=\"habit\""
               ((org-agenda-overriding-header "Habits")
                (org-agenda-sorting-strategy
                 '(todo-state-down effort-up category-keep))))
              (" " "Agenda"
               (;;(agenda "" nil)
				;; Исключаем из повестки задачи с тэгом "Текучка", чтобы они не получали приоритета перед NEXT Task. См. http://stackoverflow.com/questions/10074016/org-mode-filter-on-tag-in-agenda-view
				;; WEEKLY BUDGETS
				(bss/org-time-budgets-in-agenda)
				(agenda ""
                  ((org-agenda-skip-function '(zin/org-agenda-skip-tag "ROUTINE" 'nil))))
                (tags "REFILE"
                      ((org-agenda-overriding-header "Tasks to Refile")
                       (org-tags-match-list-sublevels nil)))

                (tags-todo "-HOLD-CANCELLED/!"
                           ((org-agenda-overriding-header "Stuck Projects")
                            (org-agenda-skip-function 'bh/skip-non-stuck-projects)
                            (org-agenda-sorting-strategy
                             '(category-keep))))

				(tags-todo "-HOLD+YEAR"
                           ((org-agenda-overriding-header (concat "Year Tasks"
                                                                  (if bh/hide-scheduled-and-waiting-next-tasks
																	  ""
                                                                    " (including WAITING and SCHEDULED tasks)")))
							(org-agenda-skip-function 'bss/show-project-next-tasks-and-standalone)
                            (org-agenda-todo-ignore-scheduled bh/year-tasks-sheduled)
                            (org-agenda-todo-ignore-deadlines bh/year-tasks-deadline)
							(org-tags-match-list-sublevels 'indented)
							))

				(tags-todo "-HOLD-CANCELLED-КУПИ/!"
				 ((org-agenda-overriding-header (concat "Priority #A and BOSS or URGENT tasks"
                                                                  (if bh/hide-scheduled-and-waiting-next-tasks
                                                                      ""
                                                                    " (including WAITING and SCHEDULED tasks)")))
                  (org-agenda-todo-ignore-scheduled bh/boss-tasks-sheduled)
                  (org-agenda-todo-ignore-deadlines bh/boss-tasks-deadline)
				  (org-tags-match-list-sublevels 'indented)
				  (org-agenda-skip-function 'bss/skip-low-priority-tasks)
				  ))

				(tags "+КУПИ-CANCELLED-HOLD/!"
                           ((org-agenda-overriding-header (concat "Купить:"
                                                                  (if bh/hide-scheduled-and-waiting-next-tasks
                                                                      ""
                                                                    " (including WAITING and SCHEDULED tasks)")))
							;;(org-agenda-skip-function '(org-agenda-skip-entry-if 'nottimestamp))
                            (org-agenda-todo-ignore-scheduled bh/hide-scheduled-tasks)
                            (org-agenda-todo-ignore-deadlines bh/hide-deadlined-tasks)
							(org-agenda-todo-ignore-with-date nil)
                            (org-agenda-sorting-strategy
                             '(category-keep))))

				(tags "+ROUTINE-REFILE-CANCELLED-WAITING-HOLD/!"
					  ((org-agenda-overriding-header (concat "Sheduled ROUTINE Tasks"
															 (if bh/hide-scheduled-and-waiting-next-tasks
																 ""
															   " (including WAITING and SCHEDULED tasks)")))
					   (org-agenda-skip-function '(org-agenda-skip-entry-if 'nottimestamp))
					   (org-agenda-todo-ignore-scheduled bh/hide-scheduled-tasks)
					   (org-agenda-todo-ignore-deadlines bh/hide-deadlined-tasks)
					   (org-agenda-todo-ignore-with-date nil)
					   (org-agenda-sorting-strategy
						'(category-keep))))



                (tags-todo "-CANCELLED-HOLD/!NEXT"
                           ((org-agenda-overriding-header (concat "Project Next Tasks"
                                                                  (if bh/hide-scheduled-and-waiting-next-tasks
                                                                      ""
                                                                    " (including WAITING and SCHEDULED tasks)")))
                            (org-agenda-skip-function 'bh/skip-projects-and-habits-and-single-tasks)
                            ;;(org-tags-match-list-sublevels t)
							(org-tags-match-list-sublevels 'indented)
                            (org-agenda-todo-ignore-scheduled bh/hide-scheduled-tasks)
                            (org-agenda-todo-ignore-deadlines bh/hide-deadlined-tasks)
							(org-agenda-todo-ignore-with-date nil)
                            (org-agenda-sorting-strategy
                             '(todo-state-down effort-up category-keep))))


                ;; (tags-todo "-REFILE-CANCELLED-WAITING-HOLD/!"
                ;;            ((org-agenda-overriding-header (concat "Project Subtasks"
                ;;                                                   (if bh/hide-scheduled-and-waiting-next-tasks
                ;;                                                       ""
                ;;                                                     " (including WAITING and SCHEDULED tasks)")))
                ;;             (org-agenda-skip-function 'bh/skip-non-project-tasks)
                ;;             (org-agenda-todo-ignore-scheduled bh/hide-scheduled-and-waiting-next-tasks)
                ;;             (org-agenda-todo-ignore-deadlines bh/hide-scheduled-and-waiting-next-tasks)
                ;;             (org-agenda-todo-ignore-with-date bh/hide-scheduled-and-waiting-next-tasks)
                ;;             (org-agenda-sorting-strategy
                ;;              '(category-keep))))

                (tags-todo "-REFILE-CANCELLED-WAITING-HOLD-BOSS/!"
                           ((org-agenda-overriding-header (concat "Standalone Tasks"
                                                                  (if bh/hide-scheduled-and-waiting-next-tasks
                                                                      ""
                                                                    " (including WAITING and SCHEDULED tasks)")))
                            (org-agenda-skip-function 'bh/skip-project-tasks)
                            (org-agenda-todo-ignore-scheduled bh/hide-scheduled-tasks)
                            (org-agenda-todo-ignore-deadlines bh/hide-deadlined-tasks)
							(org-agenda-todo-ignore-with-date nil)
                            (org-agenda-sorting-strategy
                             '(category-keep))))

                (tags-todo "-HOLD-CANCELLED/!"
                           ((org-agenda-overriding-header "Projects")
                            (org-agenda-skip-function 'bh/skip-non-projects)
                            (org-tags-match-list-sublevels 'indented)
                            (org-agenda-sorting-strategy
                             '(category-keep))))

                ;; (tags-todo "-CANCELLED+WAITING|HOLD/!"
                ;;            ((org-agenda-overriding-header (concat "Waiting and Postponed Tasks"
                ;;                                                   (if bh/hide-scheduled-and-waiting-next-tasks
                ;;                                                       ""
                ;;                                                     " (including WAITING and SCHEDULED tasks)")))
                ;;             (org-agenda-skip-function 'bh/skip-non-tasks)
				;; 			(org-tags-match-list-sublevels 'indented)
                ;;             (org-agenda-todo-ignore-scheduled bh/hide-scheduled-tasks)
                ;;             (org-agenda-todo-ignore-deadlines bh/hide-deadlined-tasks)
				;; 			(org-agenda-todo-ignore-with-date nil)
				;; 			))

				 (tags "-REFILE/"
                      ((org-agenda-overriding-header "Tasks to Archive")
                       (org-agenda-skip-function 'bh/skip-non-archivable-tasks)
                       (org-tags-match-list-sublevels nil)))
               nil)))))



;; Limit restriction lock highlighting to the headline only
(setq org-agenda-restriction-lock-highlight-subtree nil)

;; Always hilight the current agenda line
(add-hook 'org-agenda-mode-hook
          '(lambda () (hl-line-mode 1))
          'append)

;; Keep tasks with dates on the global todo lists
(setq org-agenda-todo-ignore-with-date nil)

;; Keep tasks with deadlines on the global todo lists
(setq org-agenda-todo-ignore-deadlines nil)

;; Keep tasks with scheduled dates on the global todo lists
(setq org-agenda-todo-ignore-scheduled nil)

;; Keep tasks with timestamps on the global todo lists
(setq org-agenda-todo-ignore-timestamp nil)

;; Remove completed deadline tasks from the agenda view
(setq org-agenda-skip-deadline-if-done t)

;; Remove completed scheduled tasks from the agenda view
(setq org-agenda-skip-scheduled-if-done t)

;; Remove completed items from search results
(setq org-agenda-skip-timestamp-if-done t)

(setq org-agenda-include-diary nil)
;; (setq org-agenda-diary-file "~/notes/org-mode/diary.org")
(setq org-agenda-diary-file "~/notes/org-mode/diary.org.gpg")

(setq org-agenda-insert-diary-extract-time nil)

;; Include agenda archive files when searching for things
(setq org-agenda-text-search-extra-files (quote (agenda-archives)))

;; Show all future entries for repeating tasks
(setq org-agenda-repeating-timestamp-show-all t)

;; Show all agenda dates - even if they are empty
(setq org-agenda-show-all-dates t)

;; Sorting order for tasks on the agenda
(setq org-agenda-sorting-strategy
      (quote ((agenda habit-down time-up user-defined-up effort-up category-keep)
              (todo category-up effort-up)
              (tags category-up effort-up)
              (search category-up))))


;; ((agenda habit-down time-up priority-down category-keep)
;;  (todo priority-down category-keep)
;;  (tags priority-down category-keep)
;;  (search category-keep))

;; Start the weekly agenda on Monday
(setq org-agenda-start-on-weekday 1)

;; Enable display of the time grid so we can see the marker for the current time
;; (setq org-agenda-time-grid (quote ((daily today remove-match)
;;                                    #("----------------" 0 16 (org-heading t))
;;                                    (0900 1100 1300 1500 1700)
;;                                    )))

(setq org-agenda-time-grid (quote
                            ((daily today require-timed require-timed)
                             (0900 1100 1300 1500 1700)
                             "......" "----------------")
                            ))

;; Display tags farther right
;; tags column
;;(setq org-agenda-tags-column -102)
;; Place tags close to the right-hand side of the window
(add-hook 'org-finalize-agenda-hook 'place-agenda-tags)
(defun place-agenda-tags ()
  "Put the agenda tags by the right border of the agenda window."
  (setq org-agenda-tags-column (- 0 (window-width)))
  (org-agenda-align-tags))


;;
;; Agenda sorting functions
;;
(setq org-agenda-cmp-user-defined 'bh/agenda-sort)

(defun bh/agenda-sort (a b)
  "Sorting strategy for agenda items.
Late deadlines first, then scheduled, then non-late deadlines"
  (let (result num-a num-b)
    (cond
     ; time specific items are already sorted first by org-agenda-sorting-strategy

     ; non-deadline and non-scheduled items next
     ((bh/agenda-sort-test 'bh/is-not-scheduled-or-deadline a b))

     ; deadlines for today next
     ((bh/agenda-sort-test 'bh/is-due-deadline a b))

     ; late deadlines next
     ((bh/agenda-sort-test-num 'bh/is-late-deadline '> a b))

     ; scheduled items for today next
     ((bh/agenda-sort-test 'bh/is-scheduled-today a b))

     ; late scheduled items next
     ((bh/agenda-sort-test-num 'bh/is-scheduled-late '> a b))

     ; pending deadlines last
     ((bh/agenda-sort-test-num 'bh/is-pending-deadline '< a b))

     ; finally default to unsorted
     (t (setq result nil)))
    result))

(defmacro bh/agenda-sort-test (fn a b)
  "Test for agenda sort"
  `(cond
    ; if both match leave them unsorted
    ((and (apply ,fn (list ,a))
          (apply ,fn (list ,b)))
     (setq result nil))
    ; if a matches put a first
    ((apply ,fn (list ,a))
     (setq result -1))
    ; otherwise if b matches put b first
    ((apply ,fn (list ,b))
     (setq result 1))
    ; if none match leave them unsorted
    (t nil)))

(defmacro bh/agenda-sort-test-num (fn compfn a b)
  `(cond
    ((apply ,fn (list ,a))
     (setq num-a (string-to-number (match-string 1 ,a)))
     (if (apply ,fn (list ,b))
         (progn
           (setq num-b (string-to-number (match-string 1 ,b)))
           (setq result (if (apply ,compfn (list num-a num-b))
                            -1
                          1)))
       (setq result -1)))
    ((apply ,fn (list ,b))
     (setq result 1))
    (t nil)))

(defun bh/is-not-scheduled-or-deadline (date-str)
  (and (not (bh/is-deadline date-str))
       (not (bh/is-scheduled date-str))))

(defun bh/is-due-deadline (date-str)
  (string-match "Deadline:" date-str))

(defun bh/is-late-deadline (date-str)
  (string-match "\\([0-9]*\\) d\. ago:" date-str))

(defun bh/is-pending-deadline (date-str)
  (string-match "In \\([^-]*\\)d\.:" date-str))

(defun bh/is-deadline (date-str)
  (or (bh/is-due-deadline date-str)
      (bh/is-late-deadline date-str)
      (bh/is-pending-deadline date-str)))

(defun bh/is-scheduled (date-str)
  (or (bh/is-scheduled-today date-str)
      (bh/is-scheduled-late date-str)))

(defun bh/is-scheduled-today (date-str)
  (string-match "Scheduled:" date-str))

(defun bh/is-scheduled-late (date-str)
  (string-match "Sched\.\\(.*\\)x:" date-str))

;; Use sticky agenda's so they persist
;;(setq org-agenda-sticky t)
;;norang;;
(setq org-agenda-sticky nil)



pomodoro

tomatinho

[2017-03-23 Thu 13:24]
;;(use-package pomodoro)
(use-package tomatinho
 :disabled t
)



pomidor

[2017-03-23 Thu 13:23]

;; Pomidor: https://github.com/TatriX/pomidor/
(add-to-list 'load-path "~/.emacs.d/manual-addons/pomidor")
(use-package pomidor
:disabled
:config
(global-set-key (kbd "<s-f11>") #'pomidor)
(push '("\\*pomidor\\*" . emacs) evil-buffer-regexps)

(if (eq system-type 'darwin)
    (defun pomidor-play-sound-file-async (file)
      "Play FILE with some overhead, but at least doesn't freeze Emacs."
      (when file
	;; (message (format "pomidor play sound file %s" file))
	;; (start-process-shell-command "my-sound" nil (format "mplayer %s" file))
	(start-process-shell-command "my-sound" nil (format "afplay %s" file)))
      ))
)

org-pomodoro

[2017-03-23 Thu 13:23]
;; see https://github.com/lolownia/org-pomodoro
;; and use case from http://headhole.org/organisation/2012/08/22/org-mode-gtd-and-the-pomodoro-technique/
(use-package org-pomodoro
  :config

  (global-set-key (kbd "M-<f11>") 'org-pomodoro)
  (global-set-key (kbd "s-<f11>") 'org-pomodoro)

  ;; (global-set-key (kbd "C-c C-x C-i") 'org-pomodoro)
  ;; (global-set-key (kbd "C-c C-x C-o") 'org-pomodoro)

  ;; (defun bss/custom-org-agenda-mode-defaults ()
  ;;   (org-defkey org-agenda-mode-map "I" 'org-pomodoro)
  ;;   (org-defkey org-agenda-mode-map "O" 'org-pomodoro)
  ;;   (org-defkey org-agenda-mode-map (kbd "C-c C-x C-i") 'org-pomodoro)
  ;;   (org-defkey org-agenda-mode-map (kbd "C-c C-x C-o") 'org-pomodoro))

  ;; (add-hook 'org-agenda-mode-hook 'bss/custom-org-agenda-mode-defaults 'append)

  (setq org-pomodoro-play-sounds t
        org-pomodoro-start-sound-p t
        org-pomodoro-finished-sound-p t
        org-pomodoro-killed-sound-p t
        org-pomodoro-short-break-sound-p t
        org-pomodoro-long-break-sound-p t
        org-pomodoro-finished-sound (expand-file-name "~/.emacs.d/manual-addons/sounds/end.wav")
        ;; org-pomodoro-finished-sound ""
        org-pomodoro-short-break-sound (expand-file-name "~/.emacs.d/manual-addons/sounds/horn_attack.wav")
        org-pomodoro-long-break-sound (expand-file-name "~/.emacs.d/manual-addons/sounds/horn_attack.wav")
        org-pomodoro-ticking-sound (expand-file-name "~/.emacs.d/manual-addons/pomidor/tick.wav")
        org-pomodoro-ticking-sound-p t)

;; dirty hack: disable slow (org-agenda-maybe-redo)
;; (defun org-pomodoro-finished ()
;;   "Is invoked when a pomodoro was finished successfully.
;; This may send a notification, play a sound and start a pomodoro break."
;;   (unless org-pomodoro-clock-break
;;       (org-clock-out nil t))
;;   (org-pomodoro-maybe-play-sound :pomodoro)
;;   (setq org-pomodoro-count (+ org-pomodoro-count 1))
;;   (if (zerop (mod org-pomodoro-count org-pomodoro-long-break-frequency))
;;       (org-pomodoro-start :long-break)
;;     (org-pomodoro-start :short-break))
;;   (org-pomodoro-notify "Pomodoro completed!" "Time for a break.")
;;   (org-pomodoro-update-mode-line)
;;   ;; (org-agenda-maybe-redo)
;;   (run-hooks 'org-pomodoro-finished-hook))


  ;; platform-specific settings
  (cond ((eq system-type 'darwin)
	 (setq org-pomodoro-audio-player "/usr/bin/afplay")
	 )
	((eq system-type 'windows-nt)
	 ;;(add-to-list 'exec-path "C:/emacs/mplayer/")
	 (setq org-pomodoro-audio-player "C:/emacs/bin/swavplayer.exe"
	       org-pomodoro-start-sound-args ""
	       org-pomodoro-finished-sound-args ""
	       org-pomodoro-killed-sound-args ""
	       pomodoro-short-break-sound-args ""
	       pomodoro-long-break-sound-args ""
	       pomodoro-ticking-sound-args ""))
	(t (setq org-pomodoro-audio-player "/usr/bin/aplay")))




  ;;--------------------------------------------------
  (setq org-pomodoro-plus-enabled t
	pomodoro-kicker-timer nil ;; "Actual timer for pomodoro-kicker-timer."
	)

  ;; replace original sound play
  (if org-pomodoro-plus-enabled
    (setq org-pomodoro-play-sounds nil
	  ;; (setq org-pomodoro-play-sounds t) ;; debug
	  pomodoro-kicker-timer-idle-minutes 10   ;; "Maximum idle time for procrastination, minutes"
	  ;; (setq pomodoro-kicker-timer-idle-minutes 1) ; debug
          org-pomodoro-plus-kicker-enabled t
	  org-pomodoro-plus-sound-enabled t ;; "use long sound file instead tick every second"
	  org-pomodoro-plus-break-ticking-volume "0.1" ;; macos only
	  org-pomodoro-plus-main-ticking-volume "0.3"  ;; macos only
	  org-pomodoro-1h-ticking-sound (expand-file-name "~/.emacs.d/manual-addons/sounds/ticktack1h.mp3")
          org-pomodoro-plus-go-to-work-sound (expand-file-name "~/.emacs.d/manual-addons/sounds/horn_attack.wav")
	  org-pomodoro-stop-procrastination-sound (expand-file-name "~/.emacs.d/manual-addons/sounds/horn_attack.wav")
	  org-pomodoro-plus-end-sound (expand-file-name "~/.emacs.d/manual-addons/sounds/end.wav")
	  org-pomodoro-plus-ticktack-process-name (format "org-pomodoro plus play %s"
							  (file-name-nondirectory org-pomodoro-1h-ticking-sound ))
	  org-pomodoro-finished-sound "" ;; disable original org-pomodoro sound

	  ;; Текст всплывающих сообщений
          ;; org-poodoro-plus-pomodoro-finished-msg-title (format "Pomodoro: перерыв %s минут" (format-seconds "%m" org-pomodoro-countdown))
          org-pomodoro-plus-pomodoro-finished-msg-title "Pomodoro: перерыв %s минут"
          org-pomodoro-plus-pomodoro-finished-msg-text "Сделай перерыв, иначе закопаешься в неважном!"

          org-pomodoro-plus-pomodoro-stopped-msg-title "Pomodoro: к станку, вечер близко!"
          org-pomodoro-plus-pomodoro-stopped-msg-text "Ограничь каждую активность timebox-ом, делай MVP, обеспечь перерывы."
                ;; "Делай MVP, переключайся между важным и вовремя останавливайся.")

          org-pomodoro-plus-pomodoro-kicker-msg-title "Pomodoro: что ты сейчас делаешь?"
	  org-pomodoro-plus-pomodoro-kicker-msg-text  "Зачем ты это делаешь?\nНе отлыниваешь ли ты от задачи?"

	  )
    )
  ;; debug helping commands
  ;; (setq org-pomodoro-length 25)
  ;; (setq org-pomodoro-length 1)
  ;; (setq org-pomodoro-short-break-length 5)
  ;; (setq org-pomodoro-short-break-length 1)
  ;; (setq org-pomodoro-long-break-length 20)
  ;; (setq org-pomodoro-long-break-length 1)


  (defun org-pomodoro-plus-play-sound (snd)
    ;; (interactive)
    (setq procname (format "org-pomodoro plus play %s" (file-name-nondirectory snd)))

    (cond ((eq system-type 'darwin)
	   (setq org-pomodoro-plus-needed-volume org-pomodoro-plus-main-ticking-volume)
	   (if (or (eq org-pomodoro-state :short-break)
	   	   (eq org-pomodoro-state :long-break))
	       (setq org-pomodoro-plus-needed-volume org-pomodoro-plus-break-ticking-volume))
	   (start-process procname "mybufname" org-pomodoro-audio-player "-v" org-pomodoro-plus-needed-volume snd)
  	 )
  	(t (start-process procname nil org-pomodoro-audio-player snd)))

    (if (get-process procname )
	(set-process-query-on-exit-flag (get-process procname) nil))
    )


  ;; ------------------ Begin pomodoro kicker ------------------
(defun pomodoro-kicker-timer-mode-start ()
  "Start pomodoro kicker timer mode"
  (interactive)
  (setq org-pomodoro-plus-kicker-enabled t)
  ;; стартуем таймер прокрастинации только если нет активного pomodoro, который я уже запустил
  ;;  _k_icker state: %(if org-pomodoro-plus-kicker-enabled \"Enabled\" \"Disabled\")
  ;;  _t_icking state: %(if (get-process org-pomodoro-plus-ticktack-process-name) \"Enabled\" \"Disabled\")
  ;;    ("t" (if (get-process org-pomodoro-plus-ticktack-process-name) (org-pomodoro-plus-stop-ticking) (org-pomodoro-plus-restore-ticking)))
  ;;    ("k" (if org-pomodoro-plus-kicker-enabled (pomodoro-kicker-timer-mode-stop) (pomodoro-kicker-timer-mode-start)))
  (when (not (org-pomodoro-active-p))
    (pomodoro-kicker-start-timer)
    )
  )

  (defun pomodoro-kicker-timer-mode-stop ()
    "Stop pomodoro kicker timer mode"
    (interactive)
    (setq org-pomodoro-plus-kicker-enabled nil)
    (pomodoro-kicker-stop-timer)
    )


  (defun pomodoro-kicker-timer-alert()
    "Alert for antiprocrastination"
    (interactive)
    (when org-pomodoro-plus-kicker-enabled
      (org-pomodoro-plus-play-sound org-pomodoro-stop-procrastination-sound)
      (message "Procrastination limit reached. Go to pomodoro!")
      (djcb-popup org-pomodoro-plus-pomodoro-kicker-msg-title
		  org-pomodoro-plus-pomodoro-kicker-msg-text)
      (pomodoro-kicker-start-timer)
      )
    )

  (defun pomodoro-kicker-start-timer()
    "start procrastination idle timer"
    ;; (interactive)
    ;; stop previous if exist
    (when (timerp pomodoro-kicker-timer)
      (cancel-timer pomodoro-kicker-timer))
    (when org-pomodoro-plus-kicker-enabled
      (message (format "Procrastination timer started %s"
     		     (format-time-string "%a %H:%M:%S" (current-time))))

      (setq pomodoro-kicker-timer (run-with-timer (* 60 pomodoro-kicker-timer-idle-minutes) nil 'pomodoro-kicker-timer-alert))
      )
    )

  (defun pomodoro-kicker-stop-timer()
    "stop procrastination idle timer"
    ;; (interactive)
    (when (timerp pomodoro-kicker-timer)
      (cancel-timer pomodoro-kicker-timer))
    )
  ;; ------------------ End pomodoro kicker ------------------

  (defun bss/is-workday-p ()
    "Is today a workday?"
    (interactive)
    (let ((day-of-week (nth 6 (decode-time (current-time)))))
      (if (member day-of-week
		  ;; Mon Tue Wed Thu Fri
		  '(1 2 3 4 5))
	  ;; (message "Today is a workday")
	  )
      ))


  ;; ---------- org-pomodoro-plus sound management replacement ----------
  (setq org-pomodoro-plus-end-timer nil)
  (defun org-pomodoro-plus-end-signal ()
    ;; (interactive)
    (org-pomodoro-plus-play-sound org-pomodoro-plus-end-sound)
    )

  (defun org-pomodoro-plus-go-to-work-signal ()
    "Breack ended. Go to work!"
    ;; (interactive)
    (org-pomodoro-plus-play-sound org-pomodoro-plus-go-to-work-sound)
    )


;; (defun org-pomodoro-plus-around (orig-fun &rest args)
;;     (apply orig-fun args)))
;; (advice-add 'evil-next-line :around 'evil-next-line--check-visual-line-mode)

  (defun org-pomodoro-plus-pomodoro-started-hook ()
    (interactive)
    ;; stop procrastination timer to pomodoro break end
    (pomodoro-kicker-stop-timer)
    ;; start background playing long ticktack file
    (if (get-process org-pomodoro-plus-ticktack-process-name )
	(delete-process org-pomodoro-plus-ticktack-process-name ))

    (when (timerp org-pomodoro-plus-end-timer)
      (cancel-timer org-pomodoro-plus-end-timer))

    (setq org-pomodoro-plus-end-timer (run-with-timer (- (* 60 org-pomodoro-length) 6) nil 'org-pomodoro-plus-end-signal))

    (org-pomodoro-plus-play-sound org-pomodoro-1h-ticking-sound)
    )

  (defun org-pomodoro-plus-pomodoro-stopped-hook ()
    (interactive)
    ;; start procrastination timer
    (pomodoro-kicker-start-timer)
    ;; stop background playing long ticktack file
    (if (get-process org-pomodoro-plus-ticktack-process-name )
        (delete-process org-pomodoro-plus-ticktack-process-name ))
    ;; say user to go to work
    (djcb-popup org-pomodoro-plus-pomodoro-stopped-msg-title
		org-pomodoro-plus-pomodoro-stopped-msg-text)
    )


  (defun org-pomodoro-plus-pomodoro-finished-hook ()
    "play 5s end sound"
    (interactive)
    (org-pomodoro-plus-play-sound org-pomodoro-finished-sound)
    ;; say user to get break
    (djcb-popup (format org-pomodoro-plus-pomodoro-finished-msg-title (format-seconds "%m" org-pomodoro-countdown))
                org-pomodoro-plus-pomodoro-finished-msg-text)
    ;; restart ticking process with different volume
    (if (get-process org-pomodoro-plus-ticktack-process-name )
        (delete-process org-pomodoro-plus-ticktack-process-name ))
    (org-pomodoro-plus-play-sound org-pomodoro-1h-ticking-sound)
    )

  (defun org-pomodoro-plus-pomodoro-killed-hook ()
    "stop any sounds"
    (interactive)
    ;; (message (format "pomodoro-kicker-killed-hook() called at %s"
    ;; 		     (format-time-string "%a %H:%M:%S" (current-time))))
    (if (get-process org-pomodoro-plus-ticktack-process-name )
	(delete-process org-pomodoro-plus-ticktack-process-name ))
    ;; start procrastination timer
    (pomodoro-kicker-start-timer)
    )

  (defun org-pomodoro-plus-stop-ticking ()
    "stop ticking for this pomodoro"
    (interactive)
    (if (get-process org-pomodoro-plus-ticktack-process-name )
	(delete-process org-pomodoro-plus-ticktack-process-name ))
    )



  (defun org-pomodoro-plus-restore-ticking ()
    "restore ticking for this pomodoro"
    (interactive)
    (if (get-process org-pomodoro-plus-ticktack-process-name )
	(delete-process org-pomodoro-plus-ticktack-process-name ))
    (if (not (eq org-pomodoro-state :none))
	(org-pomodoro-plus-play-sound org-pomodoro-1h-ticking-sound))
    )

  (if org-pomodoro-plus-enabled
      (progn
	(add-hook 'org-pomodoro-started-hook #'org-pomodoro-plus-pomodoro-started-hook)
	(add-hook 'org-pomodoro-finished-hook #'org-pomodoro-plus-pomodoro-finished-hook)
	(add-hook 'org-pomodoro-break-finished-hook #'org-pomodoro-plus-go-to-work-signal)
	(add-hook 'org-pomodoro-short-break-finished-hook #'org-pomodoro-plus-pomodoro-stopped-hook)
	(add-hook 'org-pomodoro-long-break-finished-hook #'org-pomodoro-plus-pomodoro-stopped-hook)
	(add-hook 'org-pomodoro-killed-hook #'org-pomodoro-plus-pomodoro-killed-hook)

    ;; autostart kicker mode at 9:300 every workday
    (run-at-time "9:30" 86400 '(lambda ()
                                 (if (and org-pomodoro-plus-enabled ;; may be not enabled at timer run time
                                          (member (nth 6 (decode-time (current-time))) '(1 2 3 4 5))
                                          (not (eq org-pomodoro-state :none)) ;; we may be already in pomodoro
                                          ;; (eq org-pomodoro-state :none) ;; we may be already in pomodoro
                                          ) ;; check if workday
                                     (progn
                                       ;; reset pomodoro count
                                       (when (not (org-pomodoro-active-p))
                                         (bss/org-pomodoro-reset))
                                       (pomodoro-kicker-timer-mode-start)
                                       )
                                   )))

    ;; stop kicker
	(run-at-time "17:30" 86400 '(lambda ()
				     (if (and org-pomodoro-plus-enabled ;; may be not enabled at timer run time
					      (member (nth 6 (decode-time (current-time))) '(1 2 3 4 5))) ;; check if workday

                         (progn
                          ;; reset pomodoro count
                          (when (not (org-pomodoro-active-p))
                            (pomodoro-kicker-timer-mode-stop)
                            (bss/org-pomodoro-reset))
                          ;; (bss/org-pomodoro-reset)
                          )
                       )))
	)
    )
  ;; ---------- org-pomodoro-plus sound management replacement ----------


;; --------------------------------------------------
;; add pomodoro modeline in frame title when we in pomodoro
;; https://lists.gnu.org/archive/html/emacs-orgmode/2012-02/msg00854.html
;;
;; Well I just went ahead and wrote the hack anyway and it seems to work
;; for me, here is what I did:

;; show clock and timer stuff in the frame title

(defvar bss/plain-frame-title-format frame-title-format)



(defun bss/clock-in-frame-title ()
  (interactive)
  (if (or (org-clocking-p) (eq org-pomodoro-state :pomodoro) (eq org-pomodoro-state :break) (eq org-pomodoro-state :long-break))
      (setq frame-title-format (list (concat
                                      ;; (car bss/plain-frame-title-format)

                                      ;; (concat (when (file-remote-p default-directory)
                                      ;;                  (let ((user (file-remote-p default-directory 'user))
                                      ;;                        (host (file-remote-p default-directory 'host)))
                                      ;;                    (format "%s@%s:" user host)))
                                      ;;                (or
                                      ;;                 (buffer-name) buffer-file-truename dired-directory))

                                      (bss/default-frame-title-format)

                                      (when (org-clocking-p)
                                        (format " :: Clocked in: %s "
                                                (org-clock-get-clock-string)))

                                      (when (eq org-pomodoro-state :pomodoro)
                                        (format " :: Pomodoro: %s"
                                                (org-pomodoro-format-seconds))
                                        )

                                      (when (or (eq org-pomodoro-state :break)
                                                (eq org-pomodoro-state :long-break))
                                        (format " :: Pomodoro break: %s"
                                                (org-pomodoro-format-seconds))
                                        )

                                      )))

    ;; (setq frame-title-format bss/plain-frame-title-format)
    (setq frame-title-format '(:eval (bss/default-frame-title-format)))
    )
  )


(run-at-time t 1 'bss/clock-in-frame-title)
(add-hook 'org-clock-in-hook 'bss/clock-in-frame-title)
(add-hook 'org-clock-out-hook 'bss/clock-in-frame-title)
(add-hook 'org-clock-cancel-hook 'bss/clock-in-frame-title)
;; --------------------------------------------------





  ;; HACK: disable agenda updates. Override functions from org-pomodoro.el: commented long-time function (org-agenda-maybe-redo)
(defun org-pomodoro-reset ()
  "Reset the org-pomodoro state. Stop external ticking process."
  (interactive)
  (when org-pomodoro-timer
    (cancel-timer org-pomodoro-timer))
  (setq org-pomodoro-state :none
        org-pomodoro-countdown 0)
  (org-pomodoro-update-mode-line)
  ;; (org-agenda-maybe-redo)
  (if (get-process org-pomodoro-plus-ticktack-process-name )
      (delete-process org-pomodoro-plus-ticktack-process-name ))
  )

  (defun org-pomodoro-start (&optional state)
  "Start the `org-pomodoro` timer.
The argument STATE is optional.  The default state is `:pomodoro`."
  (when org-pomodoro-timer (cancel-timer org-pomodoro-timer))

  ;; ;; add the org-pomodoro-mode-line to the global-mode-string
  ;; (unless global-mode-string (setq global-mode-string '("")))
  ;; (unless (memq 'org-pomodoro-mode-line global-mode-string)
  ;;   (setq global-mode-string (append global-mode-string
  ;;                                    '(org-pomodoro-mode-line))))

  (org-pomodoro-set (or state :pomodoro))

  (when (eq org-pomodoro-state :pomodoro)
    (org-pomodoro-maybe-play-sound :start)
    (run-hooks 'org-pomodoro-started-hook))
  (org-pomodoro-update-mode-line)
  ;; (org-agenda-maybe-redo)
  )

(defun bss/org-pomodoro-reset ()
  "Reset the org-pomodoro state."
  (when org-pomodoro-timer
    (cancel-timer org-pomodoro-timer))
  (setq org-pomodoro-state :none
        org-pomodoro-countdown 0)
  (org-pomodoro-update-mode-line)
  ;; (org-agenda-maybe-redo)
  )


(defun org-pomodoro-finished ()
  "Is invoked when a pomodoro was finished successfully.
This may send a notification, play a sound and start a pomodoro break."
  (unless org-pomodoro-clock-break
      (org-clock-out nil t))
  (org-pomodoro-maybe-play-sound :pomodoro)
  (setq org-pomodoro-count (+ org-pomodoro-count 1))
  (if (zerop (mod org-pomodoro-count org-pomodoro-long-break-frequency))
      (org-pomodoro-start :long-break)
    (org-pomodoro-start :short-break))
  (org-pomodoro-notify "Pomodoro completed!" "Time for a break.")
  (org-pomodoro-update-mode-line)
  ;; (org-agenda-maybe-redo)
  (run-hooks 'org-pomodoro-finished-hook))


  )

archive

(defun org-pomodoro-play-sound (type) “Play an audio file specified by TYPE (:pomodoro, :short-break, :long-break).” (let ((sound (org-pomodoro-sound type)) (args (org-pomodoro-sound-args type))) (cond ((and (fboundp ‘sound-wav-play) org-pomodoro-play-sounds sound) (sound-wav-play sound)) ((and org-pomodoro-audio-player org-pomodoro-play-sounds sound) (if (and (eq type :tick) (eq system-type ‘darwin)) (if (not (file-exists-p bss-external-pomodoro-file)) ;; (write-region “” nil bss-external-pomodoro-file)) ;; (write-region org-pomodoro-state nil bss-external-pomodoro-file)) (write-region (format “%s” org-pomodoro-state) nil bss-external-pomodoro-file)) (start-process-shell-command “org-pomodoro-audio-player” nil (mapconcat ‘identity `(,org-pomodoro-audio-player ,@(delq nil (list args (shell-quote-argument (expand-file-name sound))))) ” “)) ) ) )))

;; (setq bss-external-pomodoro-file (format “%s.need_tick” emacs-tmp-dir)) ;; (setq bss-pomodoro-ticktack (format “#!/bin/bash

;; tick_file="%s" ;; play_seconds=10 ;; play_volume=0.5

;; /bin/rm -f $tick_file ;; while true ;; do ;; mystate=`cat $tick_file` ;; if [ "$mystate" = ":short-break" ] || [ "$mystate" = ":long-break" ] ;; then ;; # echo "Break! Volume decreased" ;; play_volume=0.2 ;; else ;; play_volume=0.5 ;; fi

;; if [ -e "$tick_file" ]; then ;; # echo "$tick_file found. Call play ticktack for $play_seconds sec" ;; bin/rm -f $tick_file ;; afplay -v $play_volume -t $play_seconds ~.emacs.d/manual-addons/sounds/ticktack.mp3 ;; else ;; # dont be cpu hungry! ;; sleep 1 ;; fi ;; done ;; ” bss-external-pomodoro-file)) ;; (setq bss-pomodoro-workaround-file (expand-file-name “~/.emacs.d/manual-addons/pomodoro.sh”)) ;; (write-region bss-pomodoro-ticktack nil bss-pomodoro-workaround-file)

;; (defun bss-pomodoro-workaround-start () ;; “workaround for macos bug https://www.reddit.com/r/emacs/comments/61kfh0/pomodoro_sound_under_macos_unusable/” ;; (interactive) ;; (if (not (get-process “* macos pomodoro workaround *”)) ;; (progn ;; (start-process “* macos pomodoro workaround *” nil ;; “/bin/bash” ;; bss-pomodoro-workaround-file ;; “&”) ;; (set-process-query-on-exit-flag (get-process “* macos pomodoro workaround *”) nil) ;; ) ;; (message “Process already started!”) ;; ) ;; )

;; (if (eq system-type ‘darwin) ;; (bss-pomodoro-workaround-start))

;; (defun bss-pomodoro-workaround-kill () ;; “” ;; (interactive) ;; (if (get-process “* macos pomodoro workaround ”) ;; (delete-process ” macos pomodoro workaround *”) ;; (message “Process not started!”) ;; ) ;; ) ;; ;; (add-hook ‘kill-emacs-hook (lambda () (bss-pomodoro-workaround-kill)))

;; (defun bss-pomodoro-workaround-check () ;; “” ;; (interactive) ;; (if (not (get-process “* macos pomodoro workaround *”)) ;; (message “Process not found”) ;; (message “Process existed”) ;; ) ;; )

hooks

выравнивание в agenda

;; включаем выравнивание
(add-hook 'org-agenda-mode-hook
          (lambda ()
            (visual-line-mode -1)
            (toggle-truncate-lines 1)))

Remove empty LOGBOOK drawers on clock out

(defun bh/remove-empty-drawer-on-clock-out ()
  (interactive)
  (save-excursion
    (beginning-of-line 0)
	;; (org-remove-empty-drawer-at "LOGBOOK" (point))))
    (org-remove-empty-drawer-at (point)))) ; fix from http://stackoverflow.com/questions/21767471/org-capture-and-time-clocking-misbehaving

(add-hook 'org-clock-out-hook 'bh/remove-empty-drawer-on-clock-out 'append)

auto-save every hour for git commit by:

;; auto-save every hour for git commit by:
;; 0 * * * * ~/bin/org-git-sync.sh >/dev/null
(run-at-time "00:59" 3600 'org-save-all-org-buffers)


wtf?

(eval-after-load "org-agenda"
      '(defun org-encode-for-stdout (s) s))


(defun my-org-clocktable-indent-string (level)
  (if (= level 1)
      ""
    (let ((str "^"))
      (while (> level 2)
        (setq level (1- level)
              str (concat str "--")))
      (concat str "-> "))))

(advice-add 'org-clocktable-indent-string :override #'my-org-clocktable-indent-string)

mobile-org

;; #+begin_src emacs-lisp ;; https://github.com/steckerhalter/org-mobile-sync (setq org-mobile-directory “~/notes/MobileOrg/”) (setq org-mobile-inbox-for-pull “~/notes/MobileOrg/mobileorg-pull.org”) (setq org-mobile-capture-file “mobileorg-pull.org”)

;;(use-package filenotify) ;;(use-package org-mobile-sync) ;;(org-mobile-sync-mode 1)

;; Fork the work of pushing to mobile (use-package async) (defun fork-org-push-mobile () (interactive) (async-start ;; What to do in the child process `(lambda () (interactive) ;; (load-file “~/.emacs”) (use-package org) (use-package org-mobile) (use-package async) (setq org-agenda-files (quote (“~/notes/org-mode/work.org” “~/notes/org-mode/personal.org” “~/notes/org-mode/farm.org” “~/notes/org-mode/notes.org” “~/notes/org-mode/diary.org” “~/notes/org-mode/refile.org” “~/notes/org-mode/common.org”))) (setq org-mobile-directory “~/notes/MobileOrg/”) (setq org-mobile-inbox-for-pull “~/notes/MobileOrg/mobileorg-pull.org”) (setq org-mobile-capture-file “mobileorg-pull.org”) (setq org-directory “~/notes/org-mode”) (setq org-default-notes-file “~/notes/org-mode/refile.org”) (setq org-mobile-files ‘(org-agenda-files))

;; ,(async-inject-variables “org-directory”) ;; ,(async-inject-variables “org-mobile-directory”) ;; ,(async-inject-variables “org-mobile-files”) ;; ,(async-inject-variables “org-\(mobile-\|directory\)”) ;; (message “File list: %s” (org-agenda-files ‘UNRESTRICTED)) ,(async-inject-variables “org-directory\|org-mobile-.*\|org-agenda-files”) (org-mobile-push))

; What to do when it finishes (lambda (result) ;;(notify-push result) (message result) )))

;; Define a timer variable (defvar org-mobile-push-timer nil “Timer that `org-mobile-push-timer’ used to reschedule itself, or nil.”)

;; Push to mobile when the idle timer runs out (defun org-mobile-push-with-delay (secs) (when org-mobile-push-timer (cancel-timer org-mobile-push-timer)) (setq org-mobile-push-timer (run-with-idle-timer (* 1 secs) nil ‘fork-org-push-mobile)))

; After saving files, start a 30 seconds idle timer after which we ; are going to push (add-hook ‘after-save-hook ‘bss/org-save-hook )

(defun bss/org-save-hook () (interactive) (use-package org) (use-package org-mobile) (when (eq major-mode ‘org-mode) ;; (message (file-truename (buffer-file-name))) (dolist (file (org-mobile-files-alist)) ;; (message (file-truename (expand-file-name (car file)))) (if (string= (file-truename (expand-file-name (car file))) (file-truename (buffer-file-name))) (progn (org-mobile-push-with-delay 30) ;; (message “MobileOrg push sheduled in 30 seconds”) ) )) ))

; At least run it once a day, but no need for a delay this time (run-at-time “00:05” 86400 ‘(lambda () (org-mobile-push-with-delay 1))) (add-hook ‘kill-emacs-hook (lambda () (fork-org-push-mobile)))

;; #+end_src

keybindings

Standard key bindings

(global-set-key "\C-cl" 'org-store-link)
(global-set-key "\C-ca" 'org-agenda)
;; (global-set-key "\C-cb" 'org-iswitchb)
(global-set-key (kbd "C-c c") 'org-capture)

Custom Key Bindings from norang

(global-set-key (kbd "<f11>") 'org-clock-goto)
(global-set-key (kbd "C-<f11>") 'org-clock-in)
;; (global-set-key (kbd "M-<f11>") 'org-pomodoro)
(global-set-key (kbd "<f12>") 'org-agenda)
(global-set-key (kbd "<f5>") 'bh/org-todo)
(global-set-key (kbd "<S-f5>") 'bh/widen)
(global-set-key (kbd "<f9> <f9>") 'bh/show-org-agenda)
(global-set-key (kbd "<f9> b") 'bbdb)
(global-set-key (kbd "<f9> c") 'calendar)
(global-set-key (kbd "<f9> f") 'boxquote-insert-file)
(global-set-key (kbd "<f9> g") (lambda () (interactive)(org-id-goto "9f881541-3378-4357-b0cf-030f9a243c2a")))
(global-set-key (kbd "<f9> h") 'bss/hide-other)
(global-set-key (kbd "<f9> n") 'bh/toggle-next-task-display)
(global-set-key (kbd "<f9> w") 'bh/toggle-next-task-display)
(global-set-key (kbd "<f9> I") 'bh/punch-in)
(global-set-key (kbd "<f9> O") 'bh/punch-out)
(global-set-key (kbd "<f9> o") 'bh/make-org-scratch)
(global-set-key (kbd "<f9> r") 'boxquote-region)
(global-set-key (kbd "<f9> s") 'bh/switch-to-scratch)
(global-set-key (kbd "<f9> t") 'bh/insert-inactive-timestamp)
(global-set-key (kbd "<f9> T") 'bh/toggle-insert-inactive-timestamp)
(global-set-key (kbd "<f9> v") 'visible-mode)
(global-set-key (kbd "<f9> l") 'org-toggle-link-display)
(global-set-key (kbd "<f9> SPC") 'bh/clock-in-last-task)
(global-set-key (kbd "C-<f9>") 'previous-buffer)
(global-set-key (kbd "M-<f9>") 'org-toggle-inline-images)
(global-set-key (kbd "C-x n r") 'narrow-to-region)
(global-set-key (kbd "C-<f10>") 'next-buffer)
(global-set-key (kbd "C-s-<f12>") 'bh/save-then-publish)
(global-set-key (kbd "C-c c") 'org-capture)
(global-set-key (kbd "<f9> p") 'bh/phone-call)

org-goto быстрый переход в секции Org-Mode-файлов по <F8>

Org-mode quick goto to section <F8>

https://github.com/abo-abo/hydra

(defhydra hydra-org-goto (:hint nil :exit t)
"
Разделы задач и заметок Org-mode:
[_w_] Работа [_p_] Личное [_n_] Заметки [_d_] Дневник/Цели [_c_] tasks for _c_locking

Org-mode features:
[_l_] c_l_ocking functions
[_v_] toggle displaying in_v_isible link contents
[_t_] toggle insert inactive _t_imestamp in new header
"
    ("w" hydra-org-goto-work/body)
    ("p" hydra-org-goto-personal/body)
    ("n" hydra-org-goto-notes/body)
    ("d" hydra-org-goto-diary/body)
    ("c" (bss/my-org-goto "DFDEA38F-50FC-4D67-840D-10CE1DCC486B")) ; personal: задачи для клокинга


    ("l" hydra-org-clock/body)
    ("v" visible-mode)
    ("t" bh/toggle-insert-inactive-timestamp)

)

(global-set-key (kbd "<f8>") 'hydra-org-goto/body)

(defhydra hydra-org-goto-work (:hint nil :exit t)
"
Работа:
[_s_] Персонал: [_a_] Сведения
[_p_] Проекты:  [_1_] Скилловый начальник [_2_] Мониторинг [_3_] MQ [_4_] Nginx
                [_h_] Замороженные [_w_] под наблюдением
[_i_] Текучка   [_u_] Развитие
[_m_] Архив МТС [_r_] Архив РТК
"
    ("p" (bss/my-org-goto "C7DD34F3-7090-4737-89A6-E773F439D859")) ; work: Проекты
    ("s" (bss/my-org-goto "05500055-6cfb-4278-95c6-7d8191c357f2")) ; work: Персонал и всё связанное
    ("m" (bss/my-org-goto "5f62bddd-c840-44d8-8118-595b0cd0bb89")) ; work: Архив информации о МТС
    ("r" (bss/my-org-goto "64DB5E8D-67B0-4F56-AC3B-D0A09DC18E61")) ; work: Архив информации о РТК
    ("1" (bss/my-org-goto "6e6151b4-8dbe-4c42-a7fb-e7f96f328427")) ; work: Проект "Скилловый начальник"
    ("2" (bss/my-org-goto "ac5f3c87-0826-4f41-81b5-77e6df16e708")) ; work: Проект "Мониторинг и всё связанное"
    ("3" (bss/my-org-goto "CD30F82B-7DDD-48EA-8DA8-89C8058A9847")) ; work: Проект "Переход на новый MQ"
    ("4" (bss/my-org-goto "A998D4E1-3B2E-4B9D-A35E-190B81CB5BCE")) ; work: проект "Модернизация Nginx"
    ("h" (bss/my-org-goto "30f2478f-fc30-4279-9dd5-71f7db45d097")) ; work: Проекты под заморозкой
    ("w" (bss/my-org-goto "0A1C1087-BFA5-41E0-B20D-D24D2940A118")) ; work: Проекты под наблюдением
    ("a" (bss/my-org-goto "a6a7e909-cd91-42c7-9009-70598e976b9f")) ; work: архив сведений о персонале
    ("i" (bss/my-org-goto "1833B4DF-6F6C-44BB-B027-45BA1420E577")) ; work: рТекучка
    ("u" (bss/my-org-goto "5ACE1273-0166-44C3-8CBA-9BE5F342DD9B")) ; work: рРазвитие
)

(defhydra hydra-org-goto-personal (:hint nil :exit t)
"
Личное:
[_I_] Идеи        [_m_] Бэклог

[_p_] Проекты:    [_e_] Emacs
                  [_h_] Здоровье
                  [_n_] Английский
                  [_C_] Карьера

[_g_] GTD         [_c_] Задачи для клокинга

[_i_] лТекучка    [_u_] лРазвитие

[_F_] Семья [_a_] Андрюша [_o_] Оля [_f_] Финансы [_b_] Семейный бюджет [_H_] Дом [_k_] Машина

[_r_] Отдых и развлечения
"
    ("i" (bss/my-org-goto "c8c607e6-ebe2-4b96-9bc4-162b97740c21")) ; personal: лТекучка
    ("u" (bss/my-org-goto "A60174CF-DBF2-4A67-9230-57DBC226B2EA")) ; personal: лРазвитие
    ("g" (bss/my-org-goto "f97e7daa-05e3-428c-9cfa-99757a3beb43")) ; personal: GTD
    ("c" (bss/my-org-goto "DFDEA38F-50FC-4D67-840D-10CE1DCC486B")) ; personal: Задачи для клокинга
    ("p" (bss/my-org-goto "9f782078-28a3-483d-9c0b-98416fa0410c")) ; personal: Проекты
    ("e" (bss/my-org-goto "6403c53e-5dc1-4905-93b4-9715be4ec961")) ; personal: Emacs
    ("h" (bss/my-org-goto "d93beec4-7472-4274-870f-c85eb36dcee0")) ; personal: Здоровье
    ("n" (bss/my-org-goto "fbb669ba-4aae-406f-9f98-a79a63aeccc4")) ; personal: Английский
    ("C" (bss/my-org-goto "b8ee0ebd-cc59-4cbc-b85d-fc273cbf5093")) ; personal: Карьера
    ("f" (bss/my-org-goto "91f4ebb1-5bea-4ee0-a283-3719954893f9")) ; personal: Финансы
    ("b" (bss/my-org-goto "0a3d22ec-0a77-4baf-8ffd-bd731f7527ed")) ; personal: Семейный бюджет
    ("F" (bss/my-org-goto "4a717845-336d-41ac-b9c4-55e82b4b01ce")) ; personal: Семья
    ("a" (bss/my-org-goto "b41bf892-43ff-4dc0-b238-6628c454a7b9")) ; personal: Андрюша
    ("o" (bss/my-org-goto "e727d39b-3028-4c8c-a4c2-7f6232a6df8a")) ; personal: Оля
    ("H" (bss/my-org-goto "9620fc4e-8c6a-4e05-a16a-7cbd5c478bb0")) ; personal: Дом
    ("k" (bss/my-org-goto "7EC6614C-38F0-488C-8C1F-C8C82736707F")) ; personal: Машина
    ("r" (bss/my-org-goto "3ea0fa3e-0a16-481a-8485-ff80b61eb217")) ; personal: Отдых и развлечения
    ("m" (bss/my-org-goto "328AEA3B-E3EF-4911-ADF6-53CFD61BABBB")) ; personal: Бэклог
    ("I" (bss/my-org-goto "9426e93a-a64b-47ea-8800-7a3c19408af2")) ; personal: Идеи
)

(defhydra hydra-org-goto-notes (:hint nil :exit t)
"
Заметки:
[_g_] GTD [_i_] Inbox
[_I_] IT
    [_e_] Emacs [_m_] macos [_l_] Linux [_d_] Devops [_w_] Windows [_z_] Zabbix [_p_] Программирование [_H_] Железо
[_F_] Развлечения
[_h_] Здоровье
[_b_] Бизнес [_f_] Финансы [_o_] Дом [_B_] Стройка [_t_] Транспорт
[_L_] Обучающие материалы
"
    ("e" (bss/my-org-goto "11530b53-b0f6-4ef3-942c-53228c996175")) ; notes: Emacs
    ("i" (bss/my-org-goto "b09dcf28-383f-4122-b46b-0811e41ef497")) ; notes: Inbox
    ("g" (bss/my-org-goto "2f42b181-b773-445a-9f9d-5b0220c5da3c")) ; notes: GTD
    ("I" (bss/my-org-goto "5eca1aa6-f38e-427b-9aa2-8f2990f6ef4b")) ; notes: IT
    ("m" (bss/my-org-goto "32602040-DEF9-4D6B-8FB5-034A7A3880E2")) ; notes: macos
    ("l" (bss/my-org-goto "950d42c7-9b8e-45ce-8d7b-dc4126113573")) ; notes: Linux
    ("d" (bss/my-org-goto "4EC51C39-854B-455F-95B5-1F9026A292CC")) ; notes: Devops
    ("w" (bss/my-org-goto "ef2ee965-5ee6-4117-a157-8f7aba611e43")) ; notes: Windows
    ("z" (bss/my-org-goto "ad25fc5b-93fd-4a13-95f6-e98c1a9432b6")) ; notes: Zabbix
    ("p" (bss/my-org-goto "7ad7c489-ab96-4dfe-b2fe-c54a9ea61dd9")) ; notes: Программирование
    ("H" (bss/my-org-goto "e8f1aa70-0db5-44c7-8da5-15a58f12452f")) ; notes: Железо
    ("F" (bss/my-org-goto "45398c26-d499-49c2-94a2-5281eeda34e2")) ; notes: Развлечения
    ("h" (bss/my-org-goto "f56def07-abe8-4fda-84cc-b5e001b15f2f")) ; notes: Здоровье
    ("b" (bss/my-org-goto "533876BB-BFE6-4E8F-97C6-193606D8C13C")) ; notes: Бизнес
    ("f" (bss/my-org-goto "65da37f4-f9aa-4450-8df5-6cbf76963d64")) ; notes: Финансы
    ("o" (bss/my-org-goto "5882f91e-82da-4142-814b-31454f424744")) ; notes: Дом
    ("t" (bss/my-org-goto "4761bbf3-eba4-4732-81c8-8b89d838e9af")) ; notes: Транспорт
    ("B" (bss/my-org-goto "3317c1f4-ae88-409b-a876-47a5ecdf682b")) ; notes: Стройка
    ("L" (bss/my-org-goto "1caf490f-a82f-483b-bc18-b277c8d23b32")) ; notes: Обучающие материалы
)

гидра целей org-mode

[2017-04-03 Mon 10:25]
(defhydra hydra-org-goto-diary (:hint nil :exit t)
"
Дневник:
[_y_] Цели года
[_m_] Цели месяца
[_w_] Цели недели
"
    ("y" (bss/my-org-goto "276E0846-9091-45D7-B0D1-834106751BE7")) ; diary: Цели года
    ("m" (bss/my-org-goto "9F9B8B18-5798-40BC-8D23-3677CA9AB812")) ; diary: Цели месяца
    ("w" (bss/my-org-goto "71AE0EA5-B9A4-4E87-A5D9-1276EB4CF315")) ; diary: Цели недели
)

тюнинг

(define-key org-agenda-mode-map (kbd "C-j") 'org-agenda-switch-to)
;; (define-key org-agenda-mode-map (kbd "<tab>") 'org-agenda-goto)
(define-key org-agenda-mode-map (kbd "<tab>") 'bss/agenda-tab-replace)
(define-key org-agenda-mode-map (kbd "SPC") 'bss/agenda-spc-replace)


(define-key org-mode-map (kbd "<return>") 'bss/my-org-return)
(define-key org-mode-map (kbd "C-j") 'bss/my-org-return)
(define-key org-mode-map (kbd "s-j") 'org-meta-return)
(define-key org-mode-map (kbd "s-k") 'org-insert-todo-heading)

;;   "Archive current node content into subnote with name Archive"
(fset 'bss/org-archive-current-node-content
   [?m ?m C-return ?2 ?d ?d ?` ?m ?p M-S-right ?A])
(define-key org-mode-map (kbd "s-a") 'bss/org-archive-current-node-content)


;; Disable keys in org-mode
;;    C-c [
;;    C-c ]
;;    C-c ;
;;    C-c C-x C-q  cancelling the clock (we never want this)
(add-hook 'org-mode-hook
          '(lambda ()
             ;; Undefine C-c [ and C-c ] since this breaks my
             ;; org-agenda files when directories are include It
             ;; expands the files in the directories individually
             (org-defkey org-mode-map "\C-c[" 'undefined)
             (org-defkey org-mode-map "\C-c]" 'undefined)
             (org-defkey org-mode-map "\C-c;" 'undefined)
             (org-defkey org-mode-map "\C-c\C-x\C-q" 'undefined)
             (org-defkey org-mode-map "\C-c," 'undefined)
			 ;;(local-set-key (kbd "C-.") 'ace-jump-mode)
			 (local-set-key (kbd "C-c M-o") 'bh/mail-subtree)
		  )
          'append)

agenda keybindings

(define-key org-agenda-mode-map "s" 'org-agenda-schedule)
(define-key org-agenda-mode-map "r" 'org-agenda-refile)
(define-key org-agenda-mode-map "t" 'org-agenda-todo)
(define-key org-agenda-mode-map "j"  'org-agenda-next-line)
(define-key org-agenda-mode-map "k"  'org-agenda-previous-line)
(define-key org-agenda-mode-map "l" 'forward-char)
(define-key org-agenda-mode-map "h" 'backward-char)
(define-key org-agenda-mode-map "d" 'org-agenda-deadline)
(define-key org-agenda-mode-map  "H" 'bss/org-toggle-budgets-and-habits)
(define-key org-agenda-mode-map "b" 'org-agenda-bulk-action)

speed commands

(setq org-use-speed-commands t)


;; override org-speed-commands-default variable
(setq org-speed-commands-user (quote (("0" . (org-content))
                                      ("1" . (org-content 1))
                                      ("2" . (org-content 2))
                                      ("3" . (org-content 3))
                                      ("4" . (org-content 4))
                                      ("5" . ignore)
                                      ("6" . ignore)
                                      ("7" . ignore)
                                      ("8" . ignore)
                                      ("9" . ignore)

                                      ("a" . ignore)
                                      ("d" . ignore)
                                      ("h" . bh/hide-other)
                                      ("i" progn
                                       (forward-char 1)
                                       (call-interactively 'org-insert-heading-respect-content))
									  ("j" . ded/org-show-next-heading-tidily)
                                      ("k" . org-kill-note-or-show-branches)
                                      ("l" . ded/org-show-previous-heading-tidily)
                                      ("m" . ignore)
                                      ("q" . bh/show-org-agenda)
                                      ("r" . ignore)
                                      ("s" . org-save-all-org-buffers)
                                      ("w" . org-refile)
                                      ("x" . ignore)
                                      ("y" . ignore)
                                      ("z" . org-add-note)

                                      ("A" . ignore)
                                      ("B" . ignore)
                                      ("E" . ignore)
                                      ("F" . bh/restrict-to-file-or-follow)
                                      ("G" . ignore)
                                      ("H" . ignore)
                                      ("I" . org-pomodoro)
                                      ("J" . org-clock-goto)
                                      ("K" . ignore)
                                      ("L" . ignore)
                                      ("M" . ignore)
                                      ("N" . bh/narrow-to-org-subtree)
                                      ("O" . org-pomodoro)
                                      ("P" . bh/narrow-to-org-project)
                                      ("Q" . ignore)
                                      ("R" . ignore)
                                      ("S" . ignore)
                                      ("T" . bh/org-todo)
                                      ("U" . bh/narrow-up-one-org-level)
                                      ("V" . ignore)
                                      ("W" . bh/widen)
                                      ("X" . ignore)
                                      ("Y" . ignore)
                                      ("Z" . ignore))))

helm

helm

;;;; Helm plugin
;; http://tuhdo.github.io/helm-intro.html
(ido-mode -1) ;; Turn off ido mode in case I enabled it accidentally

(defun bss/copy ()
  (interactive)
  (kill-ring-save (region-beginning) (region-end)))

(use-package helm
  :init
  (require 'helm-config)
  :bind (
         ("M-x" . helm-M-x)
         ;; ("M-y" . helm-show-kill-ring)
         ("C-M-v" . helm-show-kill-ring)
         ("M-p" . helm-show-kill-ring)
         ("M-V" . helm-show-kill-ring)
         ("M-v" . yank)
         ("M-c" . bss/copy)
         ("C-x b" . helm-mini)
         ("C-x C-f" . helm-find-files)
         ("C-c h o" . helm-occur)
         ("H-o" .       helm-occur)
         ("C-h a" . helm-apropos) ;; describe commands, functions, variables and faces - all in one command
         ("C-c h x" . helm-register)
         ("C-c h" . helm-command-prefix)
         ("S-<f2>" . helm-org-agenda-files-headings)
         ;; ("C-x v" . helm-projectile)
         ;; ("C-x c p" . helm-projectile-ag)

         :map helm-map
         ("<tab>" . helm-execute-persistent-action) ; rebind tab to run persistent action
         ("C-i" . helm-execute-persistent-action) ; make TAB works in terminal
         ("C-z" . helm-select-action) ; list actions using C-z
         ("M-j" . helm-next-line)
         ("M-k" . helm-previous-line)
         ("M-h" . helm-previous-source)
         ("M-l" . helm-next-source)
         ("C-j" . helm-maybe-exit-minibuffer)
         )
  :config




  (define-key helm-map (kbd "M-SPC") 'toggle-input-method)
  (setq helm-split-window-in-side-p           t ; open helm buffer inside current window, not occupy whole other window
        helm-split-window-default-side 'below
        helm-move-to-line-cycle-in-source     t ; move to end or beginning of source when reaching top or bottom of source.
        helm-ff-search-library-in-sexp        t ; search for library in `require' and `declare-function' sexp.
        helm-scroll-amount                    8 ; scroll 8 lines other window using M-<next>/M-<prior>
        ;; helm-idle-delay 0.0
        ;; helm-input-idle-delay 0.01
        ;; helm-quick-update t
        helm-ff-skip-boring-files t
        helm-ff-file-name-history-use-recentf t
        helm-ff-transformer-show-only-basename nil
        helm-adaptive-history-file             "~/.emacs.d/helm-history"
        helm-yank-symbol-first                 t
        helm-buffers-fuzzy-matching            t
        helm-M-x-fuzzy-match t ;; optional fuzzy matching for helm-M-x
        helm-semantic-fuzzy-match t
        helm-imenu-fuzzy-match    t
        helm-apropos-fuzzy-match t
        helm-ff-auto-update-initial-value      t)

  (custom-set-variables
   '(helm-follow-mode-persistent t))

  (helm-mode 1)
  (helm-adaptive-mode t)
  (helm-autoresize-mode 1)

  ;; The default "C-x c" is quite close to "C-x C-c", which quits Emacs.
  ;; Changed to "C-c h". Note: We must set "C-c h" globally, because we
  ;; cannot change `helm-command-prefix-key' once `helm-config' is loaded.
  (global-unset-key (kbd "C-x c"))

  ;; shell autocomplete
  (add-hook 'eshell-mode-hook
            #'(lambda()
                (define-key eshell-mode-map [remap eshell-pcomplete] 'helm-esh-pcomplete)
                (define-key eshell-mode-map (kbd "M-p") 'helm-eshell-history)))
  (add-hook 'shell-mode-hook
            #'(lambda() (define-key shell-mode-map [remap comint-history-isearch-backward-regexp] 'helm-comint-input-ring)))

;; --------------------------------------------------
;; ;; ;; чиним input method в helm https://github.com/emacs-helm/helm/issues/797  https://groups.google.com/forum/#!topic/emacs-helm/fuowJvLiNtM
;; ;; toggle russian in org-agenda-refile
;; (defun bss/set-input-method-in-helm ()
;;   "set default input method in some helm modes"
;;   (if (member major-mode '(org-agenda-mode org-capture-mode org-mode helm-mode-org-capture))
;;       (helm-set-local-variable
;;        'current-input-method
;;        russian-input-method)))
;; (add-hook 'helm-before-initialize-hook 'bss/set-input-method-in-helm)
;; ;; (setq helm-before-initialize-hook nil)
;; --------------------------------------------------



(when (executable-find "curl")
  (setq helm-google-suggest-use-curl-p t))


)

(use-package helm-ag)

(use-package helm-git-grep
 :disabled
)


(use-package helm-projectile
  :config
)

(use-package helm-descbinds
  :defer t
  :bind (("C-h b" . helm-descbinds)
         ("C-h w" . helm-descbinds)))

;; (use-package helm-git-grep)

(use-package helm-swoop
  :bind (
         ("s-o" . helm-swoop)
         ("s-O" . helm-swoop-back-to-last-point)
         ("C-c H-o" . helm-multi-swoop)
         ("C-x H-o" . helm-multi-swoop-all)
         :map isearch-mode-map
         ( "M-s" . helm-swoop-from-isearch) ;; When doing isearch, hand the word over to helm-swoop
         ( "H-o" . helm-swoop-from-isearch) ;; When doing isearch, hand the word over to helm-swoop
         :map helm-swoop-map
         ("H-o" . helm-multi-swoop-all-from-helm-swoop)
         ("M-j" . helm-next-line)
         ("M-k" . helm-previous-line)
         ("M-h" . helm-previous-source)
         ("M-l" . helm-next-source)
         )
  :config
  (setq helm-multi-swoop-edit-save t ;; Save buffer when helm-multi-swoop-edit complete
        helm-swoop-split-with-multiple-windows nil ;; If this value is t, split window inside the current window
        helm-swoop-split-direction 'split-window-vertically ;; Split direction. 'split-window-vertically or 'split-window-horizontally
        helm-swoop-speed-or-color nil ;; If nil, you can slightly boost invoke speed in exchange for text color
        helm-swoop-move-to-line-cycle t ;; Go to the opposite side of line from the end or beginning of line
        helm-swoop-use-line-number-face t)

  ;; Helm Swoop Edit
  ;; While doing helm-swoop, press keybind [C-c C-e] to move to edit buffer.
  ;; Edit the list and apply by [C-x C-s]. If you'd like to cancel, [C-c C-g]
  )

https://github.com/bbatsov/projectile

hotspots

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; HOTSPOTS
;; http://kitchingroup.cheme.cmu.edu/blog/2015/02/04/Helm-at-the-Emacs/
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(use-package f)
(require 'helm-for-files)
(defun hotspots ()
  "helm interface to my hotspots, which includes my locations, org-files and bookmarks"
  (interactive)
  (helm :sources `(((name . "Locations")
                    (candidates . (
				   ;; 				   ("Calendar" . (lambda ()  (browse-url "https://www.google.com/calendar/render")))
                   ;;                 ("RSS" . elfeed)
                   ;;                 ("Agenda" . (lambda () (org-agenda "" "n")))))
                   ;;  (action . (("Open" . (lambda (x) (funcall x))))))
                   ;; ((name . "My Locations")
                   ;;  (candidates . (
								   ;; ("Повестка" . (lambda () (interactive)(org-agenda "a" " ")))
								   ("Личное / personal" . "~/notes/org-mode/personal.org")
								   ("Работа / work" . "~/notes/org-mode/work.org")
								   ("Разное / common" . "~/notes/org-mode/common.org")
								   ;; ("Дневник / diary" . "~/notes/org-mode/diary.org")
								   ("Дневник / diary" . "~/notes/org-mode/diary.org.gpg")
								   ("Заметки / notes" . "~/notes/org-mode/notes.org")
								   ("Временное / refile" . "~/notes/org-mode/refile.org")
								   ("Дача / farm" . "~/notes/org-mode/farm.org")
								   ("Финансы, база / finances base" . "~/notes/org-mode/finances.org.gpg")
								   ("Финансы, данные / finances data" . "~/notes/ledger/bss.ledger")
								   ("Финансы, план / finances plan" . "~/notes/ledger/pending.ledger")
                                   (".emacs.d/emacs.org" . "~/.emacs.d/emacs.org" )
                                   (".emacs" . "~/.emacs" )
                                   (".emacs.d" . "~/.emacs.d" )
                                   ))
                    (action . (("Open" . (lambda (x) (find-file x))))))

                   ((name . "My directories")
                    (candidates . (
                                   ("[D] Выбрал прочитать" . "~/Dropbox/Хочу прочитать/Выбрал прочитать")
								   ("[D] Dropbox" . "~/Dropbox/")
								   ("[Files] Home directory" . "~/")
								   ("[Files] VCS directory" . "~/work/vcs")
								   ("[Files] work directory" . "~/work")
								   ("[Files] Projects directory" . "~/work/projects")
								   ("[Files] zabbix directory" . "~/work/svn/zabbix")
								   ("[Files] Django directory" . "~/work/django")
								   ("[Files] Download directory" . "~/downloads")
								   ("[Files] Temp directory" . "~/temp")
								   ("[GIT] Common" . "~/git/common")
								   ("[GIT] Private" . "~/git/private")
                                 ;; ROOT EDIT VIA SSH:
                                 ;; open a file with ssh + sudo: C-x C-f /ssh:cloud|sudo:root:/etc/passwd
								   ;; ("[workmyusername] home" . "/ssh:workmyusername:/home/myusername")
								   ;; ("[workbook] home" . "/ssh:workbook:/home/myusername")
								   ;; ("[HomeMyusernamePlink] home" . "/plink:somedomain.com#9934:/home/myusername")
								   ("[HomeMyusername] home" . "/ssh:somedomain.com#668:/home/myusername")
								   ("[HomeMyusername] etc by root" . "/ssh:somedomain.com#668|sudo:root:/etc")
								   ("[HomeMyusernameBook] home book" . "/ssh:somedomain.com#670:/home/myusername")
								   ("[Zabbix] home" . "/ssh:[email protected]:/home/myusername")
								   ("[Zabbix] WWW" . "/ssh:[email protected]:/var/www")
								   ("[Zabbix] etc/zabbix" . "/ssh:[email protected]:/etc/zabbix")
								   ("[Zabbix companion1] etc/zabbix" . "/ssh:[email protected]:/etc/zabbix")
								   ("[Zabbix companion2] etc/zabbix" . "/ssh:[email protected]:/etc/zabbix")
								   ;; ("[Zabbix plink] etc" . "/plink:[email protected]:/etc")
								   ("[Nginx proxy]" . "/ssh:myusername@proxy:/usr/local/nginx")
								   ("[Nginx1]" . "/ssh:myusername@nginx1:/usr/local/nginx")
								   ("[Nginx2]" . "/ssh:myusername@nginx2:/usr/local/nginx")
								   ("[Nginx-dmz]" . "/ssh:nginx@nginx-dmz:/usr/local/nginx")
								   ;; ("[Nginx]" . "/ssh:[email protected]:/usr/local/nginx")
								   ;; ("[Nginx-shop]" . "/ssh:[email protected]:/etc/nginx")
								   ;; ("[Nginx-dmz]" . "/ssh:nginx-dmz:/usr/local/nginx")
								   ;; ("[Nginx1 plink]" . "/plink:myusername@nginx1:/usr/local/nginx")
								   ;; ("[Nginx2 plink]" . "/plink:myusername@nginx2:/usr/local/nginx")
								   ;; ("[Nginx-dmz plink]" . "/plink:nginx@nginx-dmz:/usr/local/nginx")
								   ;; ("[NOC] squid" . "/ssh:myusername@someserver:/etc/squid")
								   ))
                    (action . (("Open in dired" . (lambda (x) (dired x))))))
                   ((name . "My org files")
                    (candidates . ,(f-entries "~/notes/org-mode"))
                    (action . (("Open" . (lambda (x) (find-file x))))))
                   helm-source-recentf
                   helm-source-bookmarks
                   helm-source-bookmark-set)))
(global-set-key (kbd "M-<f1>") 'hotspots)
(global-set-key (kbd "<f1>") 'hotspots)

document readers

fb2 reader

[2017-09-10 Sun 21:03]

spline1986/fb2-mode: FictionBook2 reader for emacs

(add-to-list 'load-path (expand-file-name "~/.emacs.d/manual-addons/fb2-mode/"))
(require 'fb2-mode)
(setq fb2-replace-hard-space t)

(defun buffer-local-set-key (key func)
  (interactive "KSet key on this buffer: \naCommand: ")
  (let ((name (format "%s-magic" (buffer-name))))
    (eval
     `(define-minor-mode ,(intern name)
        "Automagically built minor mode to define buffer-local keys."))
    (let* ((mapname (format "%s-map" name))
           (map (intern mapname)))
      (unless (boundp (intern mapname))
        (set map (make-sparse-keymap)))
      (eval
       `(define-key ,map ,key func)))
    (funcall (intern name) t)))

(ignore-errors
  (add-hook 'fb2-mode-hook (lambda ()
                             (interactive)
                             (message "we in fb2 mode hook")
                             (evil-emacs-state)
                             (buffer-local-set-key (kbd "d") 'kill-this-buffer)
                             (buffer-local-set-key (kbd "b") 'ido-switch-buffer)
                             (buffer-local-set-key (kbd "<down>") 'evil-scroll-page-down)
                             (buffer-local-set-key (kbd "<up>") 'evil-scroll-page-up)
                             (buffer-local-set-key (kbd "j") 'evil-scroll-page-down)
                             (buffer-local-set-key (kbd "k") 'evil-scroll-page-up)
                             (buffer-local-set-key (kbd "SPC") 'evil-scroll-page-down)
                             (buffer-local-set-key (kbd "S-SPC") 'evil-scroll-page-up)
                             (buffer-local-set-key (kbd "=") '(lambda () (interactive)(text-scale-adjust +1)))
                             (buffer-local-set-key (kbd "-") '(lambda () (interactive)(text-scale-adjust -1)))
                             ))
  )

epub reader (nav)

[2017-09-08 Fri 14:34]

(use-package nov
  :ensure t
  :config
  (push '("\\.epub\\'" . nov-mode) auto-mode-alist)
  (evil-set-initial-state 'nov-mode 'emacs)

  (ignore-errors
    (define-key nov-mode-map (kbd "<down>") 'evil-scroll-page-down)
    (define-key nov-mode-map (kbd "<up>") 'evil-scroll-page-up)
    (define-key nov-mode-map (kbd "j") 'nov-scroll-up)
    (define-key nov-mode-map (kbd "k") 'nov-scroll-down))

  )

hydra

transparency

(defun my--set-transparency (inc)
  "Increase or decrease the selected frame transparency"
  (let* ((alpha (frame-parameter (selected-frame) 'alpha))
         (next-alpha (cond ((not alpha) 100)
                           ((> (- alpha inc) 100) 100)
                           ((< (- alpha inc) 0) 0)
                           (t (- alpha inc)))))
    (set-frame-parameter (selected-frame) 'alpha next-alpha)))

(defhydra hydra-transparency (:columns 2)
  "
ALPHA : [ %(frame-parameter nil 'alpha) ]
"
  ("j" (lambda () (interactive) (my--set-transparency +1)) "+ more")
  ("k" (lambda () (interactive) (my--set-transparency -1)) "- less")
  ("J" (lambda () (interactive) (my--set-transparency +10)) "++ more")
  ("K" (lambda () (interactive) (my--set-transparency -10)) "-- less")
  ("=" (lambda (value) (interactive "nTransparency Value 0 - 100 opaque:")
         (set-frame-parameter (selected-frame) 'alpha value)) "Set to ?" :color blue))

rectangle

(defhydra hydra-rectangle (:body-pre (rectangle-mark-mode 1)
                                     :color pink
                                     :hint nil
                                     :post (deactivate-mark))
  "
  ^_k_^       _w_ copy      _o_pen       _N_umber-lines            |\\     -,,,--,,_
_h_   _l_     _y_ank        _t_ype       _e_xchange-point          /,`.-'`'   ..  \-;;,_
  ^_j_^       _d_ kill      _c_lear      _r_eset-region-mark      |,4-  ) )_   .;.(  `'-'
^^^^          _u_ndo        _g_ quit     ^ ^                     '---''(./..)-'(_\_)
"
  ("k" rectangle-previous-line)
  ("j" rectangle-next-line)
  ("h" rectangle-backward-char)
  ("l" rectangle-forward-char)
  ("d" kill-rectangle)                    ;; C-x r k
  ("y" yank-rectangle)                    ;; C-x r y
  ("w" copy-rectangle-as-kill)            ;; C-x r M-w
  ("o" open-rectangle)                    ;; C-x r o
  ("t" string-rectangle)                  ;; C-x r t
  ("c" clear-rectangle)                   ;; C-x r c
  ("e" rectangle-exchange-point-and-mark) ;; C-x C-x
  ("N" rectangle-number-lines)            ;; C-x r N
  ("r" (if (region-active-p)
           (deactivate-mark)
         (rectangle-mark-mode 1)))
  ("u" undo nil)
  ("g" nil)
  ("q"   nil "cancel" :color blue)
  )
(global-set-key (kbd "<s-f5>") 'hydra-rectangle/body)

unicode

(defun my/insert-unicode (unicode-name)
       "Same as C-x 8 enter UNICODE-NAME."
       (insert-char (cdr (assoc-string unicode-name (ucs-names)))))

(global-set-key
 (kbd "C-x 9")
 (defhydra hydra-unicode (:hint nil)
   "
   Unicode  _e_ €  _s_ ZERO WIDTH SPACE
            _f_ ♀  _o_ °   _m_ µ
            _r_ ♂  _a_ →   _c_ ©
   "
   ("e" (my/insert-unicode "EURO SIGN"))
   ("r" (my/insert-unicode "MALE SIGN"))
   ("f" (my/insert-unicode "FEMALE SIGN"))
   ("s" (my/insert-unicode "ZERO WIDTH SPACE"))
   ("o" (my/insert-unicode "DEGREE SIGN"))
   ("a" (my/insert-unicode "RIGHTWARDS ARROW"))
   ("m" (my/insert-unicode "MICRO SIGN"))
   ("c" (my/insert-unicode "COPYRIGHT SIGN"))
   ("q"   nil "cancel" :color blue)
   ))

org-clock

https://www.gnu.org/software/emacs/manual/html_node/org/Clocking-commands.html

 ;; (defhydra hydra-org-clock (:color blue :hint nil)
 (defhydra hydra-org-clock (:hint nil)
   "
^Clock:^ ^In/out^     ^Edit^   ^Summary^    | ^Timers:^ ^Run^           ^Insert
-^-^-----^-^----------^-^------^-^----------|--^-^------^-^-------------^------
(_?_)    _i_n         _e_dit   _g_oto entry | (_z_)     _r_elative      ti_m_e
 ^ ^     _c_ontinue   _Q_uit   _d_isplay    |  ^ ^      cou_n_tdown     it_E_m
 ^ ^     _o_ut        ^ ^      _R_eport     |  ^ ^      _p_ause toggle
 ^ ^     h_I_story    ^ ^      ^ ^          |  ^ ^      _s_top
 ------------------------------------------------------------------------------
^Pomodoro:^
         _k_icker state: %(if org-pomodoro-plus-kicker-enabled \"Enabled\" \"Disabled\")   _t_icking state: %(if (get-process org-pomodoro-plus-ticktack-process-name) \"Enabled\" \"Disabled\")

"
   ("t" (if (get-process org-pomodoro-plus-ticktack-process-name) (org-pomodoro-plus-stop-ticking) (org-pomodoro-plus-restore-ticking)))
   ("k" (if org-pomodoro-plus-kicker-enabled (pomodoro-kicker-timer-mode-stop) (pomodoro-kicker-timer-mode-start)))
   ("i" org-clock-in)
   ;; ("I" (lambda () (interactive) (let ((current-prefix-arg '(4))) ((org-clock-in)))))
   ("I" (org-clock-in '(4) t))
   ("c" org-clock-in-last)
   ("o" org-clock-out)

   ("e" org-clock-modify-effort-estimate)
   ("Q" org-clock-cancel)

   ("g" org-clock-goto)
   ("d" org-clock-display)
   ("R" org-clock-report)
   ("?" (org-info "Clocking commands"))

  ;; ("k" pomodoro-kicker-timer-mode-start)
  ;; ("K" pomodoro-kicker-timer-mode-stop)
  ("D" org-pomodoro-plus-stop-ticking)
  ("E" org-pomodoro-plus-restore-ticking)

  ("r" org-timer-start)
  ("n" org-timer-set-timer)
  ("p" org-timer-pause-or-continue)
  ("s" org-timer-stop)

  ("m" org-timer)
  ("E" org-timer-item)
  ("z" (org-info "Timers")))
 (bind-key "C-c w" 'hydra-org-clock/body)

org-hydra

https://www.gnu.org/software/emacs/manual/html_node/org/Clocking-commands.html

 (defhydra hydra-org-hydra (:color blue :hint nil)
   "
^Clock:^ ^In/out^     ^Edit^   ^Summary^    | ^Timers:^ ^Run^           ^Insert
-^-^-----^-^----------^-^------^-^----------|--^-^------^-^-------------^------
(_?_)    _i_n         _e_dit   _g_oto entry | (_z_)     _r_elative      ti_m_e
 ^ ^     _c_ontinue   _q_uit   _d_isplay    |  ^ ^      cou_n_tdown     i_t_em
 ^ ^     _o_ut        ^ ^      _R_eport     |  ^ ^      _p_ause toggle
 ^ ^     h_I_story    ^ ^      ^ ^          |  ^ ^      _s_top
"
   ("i" org-clock-in)
   ;; ("I" (lambda () (interactive) (let ((current-prefix-arg '(4))) ((org-clock-in)))))
   ("I" (org-clock-in '(4) t))
   ("c" org-clock-in-last)
   ("o" org-clock-out)

   ("e" org-clock-modify-effort-estimate)
   ("q" org-clock-cancel)

   ("g" org-clock-goto)
   ("d" org-clock-display)
   ("R" org-clock-report)
   ("?" (org-info "Clocking commands"))

  ("r" org-timer-start)
  ("n" org-timer-set-timer)
  ("p" org-timer-pause-or-continue)
  ("s" org-timer-stop)

  ("m" org-timer)
  ("t" org-timer-item)
  ("z" (org-info "Timers")))
 (bind-key "C-c w" 'hydra-org-clock/body)

macros

(defhydra hydra-macro (:hint nil :color pink :pre
                             (when defining-kbd-macro
                                 (kmacro-end-macro 1)))
  "
  ^Create-Cycle^   ^Basic^           ^Insert^        ^Save^         ^Edit^
╭─────────────────────────────────────────────────────────────────────────╯
     ^_k_^           [_e_] execute    [_n_] insert    [_b_] name      [_'_] previous
     ^^↑^^           [_d_] delete     [_t_] set       [_K_] key       [_,_] last
 _h_ ←   → _l_       [_o_] edit       [_a_] add       [_x_] register
     ^^↓^^           [_r_] region     [_f_] format    [_B_] defun
     ^_j_^           [_m_] step
    ^^   ^^          [_s_] swap
"
  ("h" kmacro-start-macro :color blue)
  ("l" kmacro-end-or-call-macro-repeat)
  ("k" kmacro-cycle-ring-previous)
  ("j" kmacro-cycle-ring-next)
  ("r" apply-macro-to-region-lines)
  ("d" kmacro-delete-ring-head)
  ("e" kmacro-end-or-call-macro-repeat)
  ("o" kmacro-edit-macro-repeat)
  ("m" kmacro-step-edit-macro)
  ("s" kmacro-swap-ring)
  ("n" kmacro-insert-counter)
  ("t" kmacro-set-counter)
  ("a" kmacro-add-counter)
  ("f" kmacro-set-format)
  ("b" kmacro-name-last-macro)
  ("K" kmacro-bind-to-key)
  ("B" insert-kbd-macro)
  ("x" kmacro-to-register)
  ("'" kmacro-edit-macro)
  ("," edit-kbd-macro)
  ("q" nil :color blue))

projectile

projectile settings

(projectile-global-mode)
;; C-c p f (M-x projectile-find-file RET).
;; projectile-switch-project (C-c p p)
;; (setq projectile-switch-project-action 'projectile-dired)
(setq projectile-switch-project-action 'projectile-find-dir)
(setq projectile-find-dir-includes-top-level t)

;; if you ever forget any of Projectile's keybindings just do a:
;; C-c p C-h

;; You can change the default keymap prefix C-c p like this:
;; (setq projectile-keymap-prefix (kbd "C-c C-p"))
;; (setq projectile-keymap-prefix (kbd "C-c P"))

;; helm-projectile: https://github.com/bbatsov/helm-projectile
;; (setq helm-projectile-fuzzy-match nil)
(use-package helm-projectile)
;;(helm-projectile-on)
(setq projectile-completion-system 'helm)

(define-key projectile-mode-map (kbd "H-p") 'projectile-command-map)
(define-key projectile-mode-map (kbd "H-d") 'helm-projectile-find-dir)
;; (define-key projectile-mode-map (kbd "H-p") 'helm-projectile-switch-project)
(define-key projectile-mode-map (kbd "H-f") 'helm-projectile-find-file)
(define-key projectile-mode-map (kbd "H-g") 'helm-projectile-grep)


(if (display-graphic-p)
    (setq projectile-mode-symbol "")
    (setq projectile-mode-symbol " Prj"))

;; (setq projectile-globally-ignored-file-suffixes "")
;; (setq  projectile-globally-ignored-file-suffixes '( "*.txt" "*.~undo-tree~" "*.pyc" "*.swp" "*.elc" ))
;; (setq projectile-globally-ignored-files '( "TAGS" "*.txt" "*.~undo-tree~" "*.pyc" "*.swp" "*.elc" ))
;; https://github.com/bbatsov/helm-projectile/issues/21
;; (setq projectile-indexing-method 'git)
;; (setq projectile-indexing-method 'alien)


(setq projectile-enable-caching t)
(setq projectile-globally-ignored-directories
      (append '(
        ".git"
        ".svn"
        "__pycache__"
        "out"
        "repl"
        "target"
        "venv"
        )
          projectile-globally-ignored-directories))
(setq projectile-globally-ignored-files
      (append '(
        ".DS_Store"
        "*.gz"
        "*.pyc"
        "*.jar"
        "*.tar.gz"
        "*.tgz"
        "*.zip"
        )
          projectile-globally-ignored-files))

(setq projectile-mode-line '(:eval
                             (if (file-remote-p default-directory)
                                 ;; " Prj"
                                 projectile-mode-symbol
                               ;; (format " Prj[%s]" (projectile-project-name))
                               (format "%s[%s]" projectile-mode-symbol (projectile-project-name))
                               )))

projectile hydra

(defhydra hydra-projectile-other-window (:color teal)
  "projectile-other-window"
  ("f"  projectile-find-file-other-window        "file")
  ("g"  projectile-find-file-dwim-other-window   "file dwim")
  ("d"  projectile-find-dir-other-window         "dir")
  ("b"  projectile-switch-to-buffer-other-window "buffer")
  ("q"  nil                                      "cancel" :color blue))

(defhydra hydra-projectile (:color teal
                            :hint nil)
  "
     PROJECTILE: %(projectile-project-root)

     Find File            Search/Tags          Buffers                Cache
------------------------------------------------------------------------------------------
 _f_: file                 _a_: ag                _i_: Ibuffer           _c_: cache clear
 _F_: file (other win)     _t_: update gtags      _b_: switch to buffer  _x_: remove known project
 _r_: recent file          _o_: multi-occur       _K_: Kill all buffers  _X_: cleanup non-existing
 _d_: dir (helm)           _g_: grep (helm)                            ^^^^_z_: cache current
 _D_: dir                  _G_: grep

"
  ("a"   projectile-ag)
  ("b"   projectile-switch-to-buffer)
  ("c"   projectile-invalidate-cache)
  ("d"   helm-projectile-find-dir)
  ("D"   projectile-find-dir)
  ;; ("s-f" projectile-find-file)
  ;; ("ff"  projectile-find-file-dwim)
  ;; ("fd"  projectile-find-file-in-directory)
  ("f"   helm-projectile-find-file)
  ("F"   projectile-find-file-other-window)
  ("t"   ggtags-update-tags)
  ("s-g" ggtags-update-tags)
  ("i"   projectile-ibuffer)
  ("K"   projectile-kill-buffers)
  ("s-k" projectile-kill-buffers)
  ("m"   projectile-multi-occur)
  ("g"   helm-projectile-grep)
  ("G"   projectile-grep)
  ("o"   projectile-multi-occur)
  ("s-p" projectile-switch-project "switch project")
  ("p"   projectile-switch-project)
  ("s"   projectile-switch-project)
  ("r"   projectile-recentf)
  ("x"   projectile-remove-known-project)
  ("X"   projectile-cleanup-known-projects)
  ("z"   projectile-cache-current-file)
  ("`"   hydra-projectile-other-window/body "other window")
  ("q"   nil "cancel" :color blue))

(global-set-key (kbd "<C-f5>") 'hydra-projectile/body)

(global-set-key (kbd "<f5>") 'hydra-project/body)
;; https://github.com/abo-abo/hydra/wiki/Projectile-%26-Fixmee
(defhydra hydra-project (:color blue :hint nil :idle 0.4)
        "
                                                                    ╭────────────┐
    Files             Search          Buffer             Do         │ Projectile │
  ╭─────────────────────────────────────────────────────────────────┴────────────╯
    [_f_] file          [_a_] ag          [_b_] switch         [_m_] magit/vcs
    [_l_] file dwim     [_g_] grep (helm) [_v_] show all       [_p_] commander
    [_r_] recent file   [_G_] grep        [_V_] ibuffer        [_i_] info
    [_d_] dir           [_s_] occur       [_K_] kill all
    [_o_] other         [_S_] replace
    [_u_] test file     [_t_] find tag
    [_h_] root (dired)  [_T_] make tags
                                                                        ╭────────┐
    Other Window      Run             Cache              Do             │ Fixmee │
  ╭──────────────────────────────────────────────────╯ ╭────────────────┴────────╯
    [_F_] file          [_U_] test        [_kc_] clear         [_x_] TODO & FIXME
    [_L_] dwim          [_P_] compile     [_kk_] add current   [_X_] toggle
    [_D_] dir           [_c_] shell       [_ks_] cleanup
    [_O_] other         [_C_] command     [_kd_] remove
    [_B_] buffer
  --------------------------------------------------------------------------------
        "
        ("<tab>" hydra-master/body "back")
        ("<ESC>" nil "quit")
        ("a"   projectile-ag)
        ("g"   helm-projectile-grep)
        ("G"   projectile-grep)
        ("b"   projectile-switch-to-buffer)
        ("B"   projectile-switch-to-buffer-other-window)
        ("c"   projectile-run-async-shell-command-in-root)
        ("C"   projectile-run-command-in-root)
        ("d"   helm-projectile-find-dir)
        ("D"   projectile-find-dir-other-window)
        ("f"   helm-projectile-find-file)
        ("F"   projectile-find-file-other-window)
        ("m"   projectile-vc)
        ("h"   projectile-dired)
        ("i"   projectile-project-info)
        ("kc"  projectile-invalidate-cache)
        ("kd"  projectile-remove-known-project)
        ("kk"  projectile-cache-current-file)
        ("K"   projectile-kill-buffers)
        ("ks"  projectile-cleanup-known-projects)
        ("l"   projectile-find-file-dwim)
        ("L"   projectile-find-file-dwim-other-window)
        ("P"   projectile-compile-project)
        ("o"   projectile-find-other-file)
        ("O"   projectile-find-other-file-other-window)
        ("p"   projectile-commander)
        ("r"   projectile-recentf)
        ("s"   projectile-multi-occur)
        ("S"   projectile-replace)
        ("t"   projectile-find-tag)
        ("T"   projectile-regenerate-tags)
        ("u"   projectile-find-test-file)
        ("U"   projectile-test-project)
        ("v"   projectile-display-buffer)
        ("V"   projectile-ibuffer)
        ("X"   fixmee-mode)
        ("x"   fixmee-view-listing))

bookmarks

;; Bookmark handling
(setq bookmark-default-file "~/.emacs.d/.emacs.bmk")
;(global-set-key (kbd "<f4>") 'bookmark-bmenu-list)
;;
;;(global-set-key (kbd "<C-f6>") '(lambda () (interactive) (bookmark-set "SAVED")))
;;(global-set-key (kbd "<f6>") '(lambda () (interactive) (bookmark-jump "SAVED")))
(use-package bm
  :config
  (push '("\\*bm-bookmarks\\*" . emacs) evil-buffer-regexps)
  (use-package helm-bm
    ;; :after (evil-leader)
    ;; :config
    ;; (evil-leader/set-key
    ;;   "bb" 'helm-bm
    ;;   "bt" 'bm-toggle
    ;;   "bn" 'bm-next
    ;;   "bp" 'bm-previous
    ;;   )
    )


  ;; :bind
  ;;   ;; This is useful when you want to hard-mark some lines in your code and return
  ;;   ;; to them, cycle between them during *current* editing session.
  ;;   ;;
  ;;   ;; Memoize: b = bookmark, down, up, p -previous, n -next, space -set/clean
  ;;   ("s-z b" . bm-toggle)
  ;;   ("s-z <up>" . bm-previous)
  ;;   ("s-z C-p" . bm-previous)
  ;;   ("s-z <down>" . bm-next)
  ;;   ("s-z C-n" . bm-next)
  ;;   ("s-z <SPC>" . bm-show-all)
  )

tramp

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Tramp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; (defun tramp-find-file-timeout ()
;;   (when tramp
;;     (with-timeout (4)
;;       (keyboard-quit))))
;; (add-hook 'find-file-hook 'tramp-find-file-timeout)
;; I found one hint that can limit the painful wait to 5 seconds. Add this line to  ~/.ssh/config:

;; Host *
;;      ServerAliveInterval 5
;; #  host myusername.mydomain
;; host workmyusername
;; ProxyCommand ssh -q proxy-linux nc -q0 myusername.mydomain 22

(setq tramp-ssh-controlmaster-options
      "-o ControlMaster=auto -o ControlPath='tramp.%%C' -o ControlPersist=no")
;; (setq tramp-verbose 10)
(use-package tramp)
(setq tramp-auto-save-directory "~/temp")
;;http://www.gnu.org/software/tramp/#Ad_002dhoc-multi_002dhops
;; http://www.gnu.org/software/tramp/#Multi_002dhops
;;C-x C-f /ssh:bird@bastion|ssh:you@remotehost:/path
;; tramp debug (setq tramp-save-ad-hoc-proxies t)
(setq password-cache-expiry nil)
;; (setq tramp-default-method "ssh")
(if (eq system-type 'windows-nt) ;OR gnu/linux
    (progn
      (setq tramp-default-method "plink"
            tramp-default-user "myusername"
            tramp-default-host "192.168.1.200"
            )
      ;; (setq ssh-program "Y:/apps/putty/plink.exe")
      ;; (setq ssh-explicit-args `("-i" "P:/.ssh/putty_key.ppk" "-l" "aeloviko"))
      ))

;; (defun ido-remove-tramp-from-cache nil
;;   "Remove any TRAMP entries from `ido-dir-file-cache'.
;;     This stops tramp from trying to connect to remote hosts on emacs startup,
;;     which can be very annoying."
;;   (interactive)
;;   (setq ido-dir-file-cache
;;         (cl-remove-if
;;          (lambda (x)
;;            (string-match "/\\(rsh\\|ssh\\|telnet\\|su\\|sudo\\|sshx\\|krlogin\\|ksu\\|rcp\\|scp\\|rsync\\|scpx\\|fcp\\|nc\\|ftp\\|smb\\|adb\\):" (car x)))
;;          ido-dir-file-cache)))
;; ;; redefine `ido-kill-emacs-hook' so that cache is cleaned before being saved
;; (defun ido-kill-emacs-hook ()
;;   (ido-remove-tramp-from-cache)
;;   (ido-save-history))

;; (add-hook 'kill-emacs-hook (lambda () (ido-remove-tramp-from-cache)))

;; (defun bss-shell-zabbix ()
;;     (interactive)
;;     (let ((default-directory "/plink:[email protected]:"))
;;       (shell)))

;;  C-x C-f /sudo::/etc/hosts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; disable vc-svn on files accessed with tramp: http://www.emacswiki.org/emacs/TrampMode
(defadvice vc-svn-registered (around my-vc-svn-registered-tramp activate)
  "Don't try to use SVN on files accessed via TRAMP."
  (if (and (fboundp 'tramp-tramp-file-p)
	   (tramp-tramp-file-p (ad-get-arg 0)))
      nil
    ad-do-it))

sr-speedbar

;; http://www.emacswiki.org/emacs/SrSpeedbar
(use-package sr-speedbar)
(global-set-key (kbd "H-s") 'sr-speedbar-open)
(global-set-key (kbd "s-s") 'sr-speedbar-toggle)
(setq speedbar-default-position 'left)
(setq speedbar-hide-button-brackets-flag nil)
(setq speedbar-show-unknown-files t)
(setq speedbar-smart-directory-expand-flag t)
(setq sr-speedbar-right-side nil)
;; (setq sr-speedbar-auto-refresh nil)
(setq speedbar-use-images t)
;; (setq sr-speedbar-max-width 70)
;; (setq sr-speedbar-width-console 40)

;; (setq speedbar-frame-parameters
;;       '((minibuffer)
;; 	(width . 40)
;; 	(border-width . 0)
;; 	(menu-bar-lines . 0)
;; 	(tool-bar-lines . 0)
;; 	(unsplittable . t)
;; 	(left-fringe . 0)))

;; (when window-system
;;   (defadvice sr-speedbar-open (after sr-speedbar-open-resize-frame activate)
;;     (set-frame-width (selected-frame)
;;                      (+ (frame-width) sr-speedbar-width)))
;;   (ad-enable-advice 'sr-speedbar-open 'after 'sr-speedbar-open-resize-frame)

;;   (defadvice sr-speedbar-close (after sr-speedbar-close-resize-frame activate)
;;     (sr-speedbar-recalculate-width)
;;     (set-frame-width (selected-frame)
;;                      (- (frame-width) sr-speedbar-width)))
;;   (ad-enable-advice 'sr-speedbar-close 'after 'sr-speedbar-close-resize-frame))

folding

origami

(use-package origami
  ;; :disabled
  :config
  ;;origami https://github.com/gregsexton/origami.el
  ;; (use-package origami)
  (global-origami-mode 1)

  (defun nin-origami-toggle-node ()
    (interactive)
    (if (equal major-mode 'org-mode)
	(org-cycle)
      (save-excursion ;; leave point where it is
	(goto-char (point-at-eol))             ;; then go to the end of line
	(origami-toggle-node (current-buffer) (point)))))                 ;; and try to fold

  (add-hook 'prog-mode-hook
	    (lambda ()
	      ;; parsers see in variable origami-parser-alist
	      (setq-local origami-fold-style 'triple-braces)
	      (origami-mode)
	      (origami-close-all-nodes (current-buffer))
	      ))
  ;; mapping works only in normal mode
  (evil-define-key 'normal prog-mode-map (kbd "<tab>") 'nin-origami-toggle-node)
  ;; (evil-define-key 'normal php-mode-map (kbd "TAB") 'nin-origami-toggle-node)
  ;; (evil-define-key 'normal php-mode-map (kbd "<tab>") 'nin-origami-toggle-node)

  (define-key evil-normal-state-map "za" 'origami-forward-toggle-node)
  (define-key evil-normal-state-map "zR" 'origami-close-all-nodes)
  (define-key evil-normal-state-map "zM" 'origami-open-all-nodes)
  (define-key evil-normal-state-map "zr" 'origami-close-node-recursively)
  (define-key evil-normal-state-map "zm" 'origami-open-node-recursively)
  (define-key evil-normal-state-map "zo" 'origami-show-node)
  (define-key evil-normal-state-map "zc" 'origami-close-node)
  (define-key evil-normal-state-map "zj" 'origami-forward-fold)
  (define-key evil-normal-state-map "zk" 'origami-previous-fold)
  (define-key evil-visual-state-map "zf"
    '(lambda ()
       "create fold and add comment to it"
       (interactive)
       (setq start (region-beginning))
       (setq end (region-end))
       (deactivate-mark)
       (and (< end start)
	    (setq start (prog1 end (setq end start))))
       (goto-char start)
       (beginning-of-line)
       (indent-according-to-mode)
       (if (equal major-mode 'emacs-lisp-mode)
	   (insert ";; ")
	 ;; (indent-according-to-mode)
	 (insert comment-start " "))

       ;; (insert comment-start " ")
       (setq start (point))
       (insert "Folding" " {{{")
       (newline-and-indent)
       (goto-char end)
       (end-of-line)
       (and (not (bolp))
	    (eq 0 (forward-line))
	    (eobp)
	    (insert ?\n))
       (indent-according-to-mode)
       (if (equal major-mode 'emacs-lisp-mode)
	   (insert ";; }}}")

	 (if (equal comment-end "")
	     (insert comment-start " }}}")
	   (insert comment-end "}}}")))
       (newline-and-indent)
       (goto-char start)
       ))
  )

hideshow

(use-package hideshow
  :disabled
  :config
  ;; HideShow https://www.emacswiki.org/emacs/HideShow
  (defvar hs-special-modes-alist
    (mapcar 'purecopy
	    '((c-mode "{" "}" "/[*/]" nil nil)
	      (c++-mode "{" "}" "/[*/]" nil nil)
	      (bibtex-mode ("@\\S(*\\(\\s(\\)" 1))
	      (java-mode "{" "}" "/[*/]" nil nil)
	      (js-mode "{" "}" "/[*/]" nil)
	      (emacs-lisp- "(" ")" nil))))

  ;; (use-package hideshow)
  (add-hook 'python-mode-hook         'hs-minor-mode)

  (define-key evil-normal-state-map "zt" 'hs-toggle-hiding)
  (define-key evil-normal-state-map "zM" 'hs-hide-all)
  (define-key evil-normal-state-map "zm" 'hs-hide-block)
  (define-key evil-normal-state-map "zR" 'hs-show-all)
  (define-key evil-normal-state-map "zr" 'hs-show-block)
					;https://github.com/shanecelis/hideshow-org/tree/master
  (use-package hideshow-org)
  (global-set-key (kbd "<f7>") 'hs-org/minor-mode)

  ;; (global-set-key (kbd "<f7>") 'hs-toggle-hiding)
  ;; (global-set-key (kbd "C-<f7>") 'hs-hide-all)
  ;; (global-set-key (kbd "C-S-<f7>") 'hs-show-all)

  (autoload 'hideshowvis-enable "hideshowvis" "Highlight foldable regions")

  (autoload 'hideshowvis-minor-mode
    "hideshowvis"
    "Will indicate regions foldable with hideshow in the fringe."
    'interactive)

  (dolist (hook (list 'emacs-lisp-mode-hook
		      'python-mode-hook
		      'c++-mode-hook))
    (add-hook hook 'hideshowvis-enable))

  ;; If enabling hideshowvis-minor-mode is slow on your machine use M-x,
  ;; customize-option, hideshowvis-ignore-same-line and set it to nil. This will
  ;; then display - icons for foldable regions of one line, too but is faster
  ;;
  ;; To enable displaying a + symbol in the fringe for folded regions,
  ;; use:
  ;;
  (use-package hideshowvis)
  (HIDESHOWVIS-SYMBOLS)
  )

folding-mode

;; folding mode {{{
;; origami-mode ;; ;; Folding http://www.emacswiki.org/emacs/FoldingMode
;; origami-mode ;; (if (load "folding" 'nomessage 'noerror)
;; origami-mode ;; 	(folding-mode-add-find-file-hook))
;; origami-mode ;;
;; origami-mode ;; ;; to enable call M-x folding-mode
;; origami-mode ;; ;; (folding-add-to-marks-list 'python-mode "#{{{" "#}}}" nil t) ;example
;; origami-mode ;; ;;(folding-add-to-marks-list 'ruby-mode "#{{{" "#}}}" nil t) ;example
;; origami-mode ;;
;; origami-mode ;; (define-key evil-normal-state-map "za" 'folding-toggle-show-hide)
;; origami-mode ;; (define-key evil-normal-state-map "zR" 'folding-whole-buffer)
;; origami-mode ;; (define-key evil-normal-state-map "zM" 'folding-open-buffer)
;; origami-mode ;; (define-key evil-normal-state-map "zr" 'folding-hide-current-subtree)
;; origami-mode ;; (define-key evil-normal-state-map "zm" 'folding-show-current-subtree)
;; origami-mode ;; (define-key evil-normal-state-map "zo" 'folding-show-current-entry)
;; origami-mode ;; (define-key evil-normal-state-map "zc" 'folding-hide-current-entry)
;; origami-mode ;; (define-key evil-normal-state-map "zj" 'folding-next-visible-heading)
;; origami-mode ;; (define-key evil-normal-state-map "zk" 'folding-previous-visible-heading)
;; origami-mode ;; ;; (define-key evil-normal-state-map "zf" 'folding-fold-region)
;; origami-mode ;; (define-key evil-normal-state-map "zf"
;; origami-mode ;;   '(lambda ()
;; origami-mode ;; 	 "create fold, exit from shifting and add comment to it"
;; origami-mode ;; 	 (interactive)
;; origami-mode ;; 	 (folding-fold-region (region-beginning) (region-end))
;; origami-mode ;; 	 (folding-shift-out)
;; origami-mode ;; 	 (folding-toggle-show-hide)
;; origami-mode ;; 	 (evil-append-line 1)
;; origami-mode ;; 	 (insert " FoldingComment")
;; origami-mode ;; 	 (evil-normal-state)
;; origami-mode ;; 	 (evil-backward-WORD-begin)
;; origami-mode ;; ))
;; origami-mode ;;
;; origami-mode ;; (defun bss/folding-not-in-org ()
;; origami-mode ;;   "selective folding toggle by tab: skip org-mode"
;; origami-mode ;;   (interactive)
;; origami-mode ;;   (if (equal major-mode 'org-mode)
;; origami-mode ;;  	  (org-cycle)
;; origami-mode ;;  	(folding-toggle-show-hide)
;; origami-mode ;; 	))
;; origami-mode ;; ;; (define-key evil-normal-state-map (kbd "<tab>") 'bss/folding-not-in-org)
;; origami-mode ;; (evil-define-key 'normal prog-mode-map (kbd "<tab>") 'bss/folding-not-in-org)
;; origami-mode ;;
;; origami-mode ;; (add-hook 'prog-mode-hook (lambda () (folding-mode) (folding-whole-buffer)))
;; origami-mode ;;
;; origami-mode ;; ;; (add-hook 'python-mode-hook
;; origami-mode ;; ;; 		  (lambda ()
;; origami-mode ;; ;; 			(folding-mode)
;; origami-mode ;;
;; origami-mode ;; ;; 			(add-to-list 'write-file-functions 'delete-trailing-whitespace)))
;; origami-mode ;;
;; origami-mode ;; ;; C-c @ C-f		folding-fold-region
;; origami-mode ;; ;; C-c @ C-k		folding-marks-kill
;; origami-mode ;; ;; C-c @ C-n		folding-display-name
;; origami-mode ;; ;; C-c @ C-o		folding-open-buffer
;; origami-mode ;; ;; C-c @ C-q		folding-toggle-show-hide
;; origami-mode ;; ;; C-c @ C-r		folding-convert-buffer-for-printing
;; origami-mode ;; ;; C-c @ C-s		folding-show-current-entry
;; origami-mode ;; ;; C-c @ C-t		folding-show-all
;; origami-mode ;; ;; C-c @ C-u		folding-toggle-enter-exit
;; origami-mode ;; ;; C-c @ C-v		folding-pick-move
;; origami-mode ;; ;; C-c @ C-w		folding-whole-buffer
;; origami-mode ;; ;; C-c @ C-x		folding-hide-current-entry
;; origami-mode ;; ;; C-c @ C-y		folding-show-current-subtree
;; origami-mode ;; ;; C-c @ C-z		folding-hide-current-subtree
;; origami-mode ;; ;; C-c @ SPC		folding-next-visible-heading
;; origami-mode ;; ;; C-c @ #			folding-region-open-close
;; origami-mode ;; ;; C-c @ %			folding-convert-to-major-folds
;; origami-mode ;; ;; C-c @ .			folding-context-next-action
;; origami-mode ;; ;; C-c @ /			folding-all-comment-blocks-in-region
;; origami-mode ;; ;; C-c @ ;			folding-comment-fold
;; origami-mode ;; ;; C-c @ <			folding-shift-out
;; origami-mode ;; ;; C-c @ >			folding-shift-in
;; origami-mode ;; ;; C-c @ I			folding-insert-advertise-folding-mode
;; origami-mode ;; ;; C-c @ v			folding-previous-visible-heading
;; origami-mode ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; origami-mode ;; ;; }}}

neo-tree

;; NeoTree
;; http://www.emacswiki.org/emacs/NeoTree?utm_medium=referral&utm_source=zeef.com&utm_campaign=ZEEF
;; https://github.com/jaypei/emacs-neotree
;; https://www.emacswiki.org/emacs/NeoTree
(use-package neotree
  :config
  (global-set-key (kbd "H-t") 'neotree-toggle)
  (global-set-key (kbd "s-t") 'neotree-toggle)
  (setq neo-smart-open t)
  (setq projectile-switch-project-action 'neotree-projectile-action)
  (evil-set-initial-state 'neotree-mode 'emacs)

  (define-key neotree-mode-map (kbd "j") 'neotree-next-line)
  (define-key neotree-mode-map (kbd "k") 'neotree-previous-line)
  (define-key neotree-mode-map (kbd "h") 'backward-char)
  (define-key neotree-mode-map (kbd "l") 'forward-char)
  (define-key neotree-mode-map (kbd "C-d") 'evil-scroll-down)
  (define-key neotree-mode-map (kbd "C-u") 'evil-scroll-up)
  (define-key neotree-mode-map (kbd "C-j") 'neotree-enter)

  )


;; (evil-define-key 'normal neotree-mode-map (kbd "<tab>") 'neotree-enter)
;; (evil-define-key 'normal neotree-mode-map (kbd "C-j") 'neotree-enter)
;; (evil-define-key 'normal neotree-mode-map (kbd "q") 'neotree-hide)
;; (evil-define-key 'normal neotree-mode-map (kbd "g") 'neotree-refresh)
;; (evil-define-key 'normal neotree-mode-map (kbd "<return>") 'neotree-enter)
;; (evil-define-key 'normal neotree-mode-map (kbd "H") 'neotree-hidden-file-toggle)
;; (evil-define-key 'normal neotree-mode-map (kbd "SPC") 'neotree-quick-look)

 ;; (add-hook 'neotree-mode-hook
 ;;            (lambda ()
 ;;              (define-key evil-normal-state-local-map (kbd "TAB") 'neotree-enter)
 ;;              (define-key evil-normal-state-local-map (kbd "SPC") 'neotree-quick-look)
 ;;              (define-key evil-normal-state-local-map (kbd "q") 'neotree-hide)
 ;;              (define-key evil-normal-state-local-map (kbd "RET") 'neotree-enter)))


;; (setq neo-theme (if (display-graphic-p) 'icons 'arrow))
;; (add-hook 'neo-after-create-hook
;;           (lambda (_)
;;             (call-interactively 'text-scale-decrease)))

dired

base settings

(put 'dired-find-alternate-file 'disabled nil)
;; если открыт другой буфер с dired, то по-умолчанию в пути подставлять его каталог
(setq dired-dwim-target t)

(if (eq system-type 'windows-nt)  ;OR gnu/linux
	(setq dired-listing-switches "-lah")
  (setq dired-listing-switches "-lah --group-directories-first"))
(if (eq system-type 'darwin)
	(setq insert-directory-program "/usr/local/bin/gls"))
;; (when (eq system-type 'darwin)
  ;; (use-package ls-lisp)
  ;; (setq ls-lisp-use-insert-directory-program nil))

;; windows settings See (customize-group 'ls-lisp)
(setq ls-lisp-dirs-first t)
(setq ls-lisp-ignore-case t)
; hide the link count, user, and group columns - default is '(links uid gid)
(setq ls-lisp-verbosity '(links))
; use ISO dates (the first is for recent dates, second for old dates)
(setq ls-lisp-format-time-list '("%Y-%m-%d %H:%M" "%Y-%m-%d %H:%M"))
(setq ls-lisp-use-localized-time-format t)

;; Always copy/delete recursively
(setq dired-recursive-copies (quote always))
(setq dired-recursive-deletes (quote top))

;; Auto refresh dired, but be quiet about it
(setq global-auto-revert-non-file-buffers t)
(setq auto-revert-verbose nil)

(define-key dired-mode-map (kbd "K") 'dired-do-kill-lines)
(define-key dired-mode-map (kbd "k") 'dired-previous-line)
(define-key dired-mode-map (kbd "J") 'dired-goto-file)
(define-key dired-mode-map (kbd "j") 'dired-next-line)
(define-key dired-mode-map (kbd "M-p") 'ace-window)
(define-key dired-mode-map (kbd "M-q") 'ace-window)
(define-key dired-mode-map (kbd "/") 'helm-occur)
;; (define-key dired-mode-map (kbd "C-j") 'dired-find-alternate-file)
(define-key dired-mode-map (kbd "C-j") 'dired-find-file)
(define-key dired-mode-map (kbd "C-d") 'evil-scroll-page-down)
(define-key dired-mode-map (kbd "C-u") 'evil-scroll-page-up)


(define-key package-menu-mode-map (kbd "h") 'left-char)
(define-key package-menu-mode-map (kbd "j") 'next-line)
(define-key package-menu-mode-map (kbd "k") 'previous-line)
(define-key package-menu-mode-map (kbd "l") 'right-char)

;; (eval-after-load 'tramp
;;  '(progn
;;     ;; Allow to use: /sudo:user@host:/path/to/file
;;     (add-to-list 'tramp-default-proxies-alist
;; 		  '(".*" "\\`.+\\'" "/ssh:%h:"))))

dired details (disabled)

[2017-03-23 Thu 16:57]

;; (use-package dired-details)
;; (dired-details-install)
;; ;;(setq dired-details-hidden-string " [\u25bc] ")
;; (setq dired-details-hidden-string "[…] ")

dired+

[2017-03-23 Thu 16:56]

http://www.emacswiki.org/emacs/DiredPlus

(use-package dired+
  :ensure t
  :init
      (progn
        ;; Details toggling is bound to "(" in `dired-mode' by default
        (setq diredp-hide-details-initially-flag nil))
  :config
  ;; (setq diredp-hide-details-initially-flag nil)
  ;; (setq diredp-hide-details-propagate-flag nil)
  )

dired-x

[2017-03-23 Thu 16:57]

;; включаем omit-mode по-умолчанию, т.е. скрываем по-умолчанию файлы .bashrc и т.д.
;; отключается в меню или по C-x M-o
;; http://www.emacswiki.org/emacs/DiredOmitMode
;;(setq dired-omit-files "^\\.?#\\|^\\.$\\|^\\.\\.$") ;;default

(require 'dired-x)
(setq-default dired-omit-files-p t) ; Buffer-local variable
;; (setq dired-omit-files "^\\.?#\\|^\\.$\\|^\\.[^.].+$")
(setq dired-omit-files "^\\.?#\\|^\\.$\\|^\\.[^.].+$\\|^.DS_Store$\\|^__MACOSX$")
(add-hook 'dired-mode-hook (lambda () (dired-omit-mode)))

dired async mode (disabled)

[2017-03-23 Thu 16:53]

;; (autoload 'dired-async-mode "dired-async.el" nil t)
;; (dired-async-mode nil)

dired get selected items size via “?” key

[2017-03-23 Thu 16:52]

;; get directory-size
(defun dired-get-size ()
  (interactive)
  (let ((files (dired-get-marked-files)))
    (with-temp-buffer
      (if (eq system-type 'darwin)
          (apply 'call-process "gdu" nil t nil "-sch" files)
        (apply 'call-process "/usr/bin/du" nil t nil "-sch" files))
      (message "Size of all marked files: %s"
               (progn
                 (re-search-backward "\\(^[0-9.,]+[A-Za-z]+\\).*total$")
                 (match-string 1))))))

(define-key dired-mode-map (kbd "?") 'dired-get-size)

dired recent dirs via C-x C-d

[2017-03-23 Thu 16:51]

;; open recent directory, requires ivy (part of swiper)
;; borrows from http://stackoverflow.com/questions/23328037/in-emacs-how-to-maintain-a-list-of-recent-directories
(defun bjm/ivy-dired-recent-dirs ()
  "Present a list of recently used directories and open the selected one in dired"
  (interactive)
  (let ((recent-dirs
         (delete-dups
          (mapcar (lambda (file)
                    (if (file-directory-p file) file (file-name-directory file)))
                  recentf-list))))

    (let ((dir (ivy-read "Directory: "
                         recent-dirs
                         :re-builder #'ivy--regex
                         :sort nil
                         :initial-input nil)))
      (dired dir))))

(global-set-key (kbd "C-x C-d") 'bjm/ivy-dired-recent-dirs)

dired open file in external app via “C-return”

[2017-03-23 Thu 16:51]

;;----------------------------------------
;;Open file by C-return in external application
(defun ergoemacs-open-in-external-app ()
  "Open the current file or dired marked files in external app."
  (interactive)
  (let ( doIt
         (myFileList
          (cond
           ((string-equal major-mode "dired-mode") (dired-get-marked-files))
           (t (list (buffer-file-name))) ) ) )

    (setq doIt (if (<= (length myFileList) 5)
                   t
                 (y-or-n-p "Open more than 5 files?") ) )

    (when doIt
      (cond
       ((string-equal system-type "windows-nt")
        (mapc (lambda (fPath) (w32-shell-execute "open" (replace-regexp-in-string "/" "\\" fPath t t)) ) myFileList)
        )
       ((string-equal system-type "darwin")
        (mapc (lambda (fPath) (shell-command (format "open \"%s\"" fPath)) )  myFileList) )
       ((string-equal system-type "gnu/linux")
        (mapc (lambda (fPath) (let ((process-connection-type nil)) (start-process "" nil "xdg-open" fPath)) ) myFileList) ) ) ) ) )

(define-key dired-mode-map (kbd "<C-return>") 'ergoemacs-open-in-external-app)

;;----------------------------------------

dired sort menu

[2017-03-23 Thu 16:50]

;;Sort settings
(use-package dired-sort-menu+)
(add-hook 'dired-load-hook
          (lambda () (use-package dired-sort-menu)))

dired shell instead dired via “M-return”

[2017-03-23 Thu 16:49]

;; open eterm for current directory by pressing M-return

(defun shell-instead-dired ()
  (interactive)
  (let ((dired-buffer (current-buffer)))
    (eshell)
    ;; (shell (concat default-directory "-shell"))
    ;; ;; (kill-buffer dired-buffer) ;; remove this line if you don't want to kill the dired buffer
    ;; ;; (delete-other-windows)
	))

(define-key dired-mode-map (kbd "<M-return>") 'shell-instead-dired)

dired sudo toggle

[2017-03-23 Thu 16:48]

;; Allow to switch from current user to sudo when browsind `dired' buffers.
;; To activate and swit with "C-c C-s" just put in your .emacs:
(use-package dired-toggle-sudo)
(define-key dired-mode-map (kbd "C-c C-s") 'dired-toggle-sudo)

dired create new file via ‘N’ key

[2017-03-23 Thu 16:47]

;;------------------------------
;;
;; для создания нового файла из dired нажимаем "N" и вводем имя. каталоги в имени вроде foo/bar/filename будут созданы, если их нет

(eval-after-load 'dired
  '(progn
	 (defun my-dired-create-file (file)
       "Create a file called FILE. If FILE already exists, signal an error."
       (interactive
        (list (read-file-name "Create file: " (dired-current-directory))))
       (let* ((expanded (expand-file-name file))
              (try expanded)
              (dir (directory-file-name (file-name-directory expanded)))
              new)
         (if (file-exists-p expanded)
             (error "Cannot create file %s: file exists" expanded))
         ;; Find the topmost nonexistent parent dir (variable `new')
         (while (and try (not (file-exists-p try)) (not (equal new try)))
           (setq new try
                 try (directory-file-name (file-name-directory try))))
         (when (not (file-exists-p dir))
           (make-directory dir t))
         (write-region "" nil expanded t)
         (when new
           (dired-add-file new)
           (dired-move-to-filename))))
	 (define-key dired-mode-map (kbd "N") 'my-dired-create-file)))

dired-subtree via TAB

[2017-03-23 Thu 16:47]

;; show directory subtree by tab/shift-tab
(use-package dired-subtree)
(define-key dired-mode-map (kbd "<tab>") 'dired-subtree-toggle)
(define-key dired-mode-map (kbd "<backtab>") 'dired-subtree-cycle)

dired-archive

[2017-03-23 Thu 16:46]

;;----------------------------------------
;; http://stackoverflow.com/questions/10226836/how-to-tar-and-compress-marked-files-in-emacs
;; Работа с архивами: просто копируем файлы в архив, например
;; You can also archive files just by marking and copying them to an archive file.
;; For example, mark several files in dired, and select m-x dired-do-copy.
;; When prompted for destination, type test.zip. The files will be added to the zip archive automatically.
;; You can also uncompress files by selecting them in dired and running the command dired-do-extract
;; To set this up, look at the following variables: dired-to-archive-copy-alist dired-extract-alist
;; Here's my setup, which has served me for many years...
;; ;; dired-a provides support functions, including archiving, for dired
;; (load "dired-a")

;; Alist with information how to add files to an archive (from dired-a)
;; Each element has the form (REGEXP ADD-CMD NEW-CMD). If REGEXP matches
;; the file name of a target, that target is an archive and ADD-CMD is a command
;; that adds to an existing archive and NEW-CMD is a command that makes a new
;; archive (overwriting an old one if it exists). ADD-CMD and NEW-CMD are:
;; 1. Nil (meaning we cannot do this for this type of archive) (one of
;;    ADD-CMD and NEW-CMD must be non-nil).
;; 2. A symbol that must be a function e.g. dired-do-archive-op.
;; 3. A format string with two arguments, the source files concatenated into
;;    a space separated string and the target archive.
;; 4. A list of strings, the command and its flags, to which the target and
;;    the source-files are concatenated."
(setq dired-to-archive-copy-alist
      '(("\\.sh\\(ar\\|[0-9]\\)*$" nil "shar %s > %s")
    ("\\.jar$" ("jar" "uvf") ("jar" "cvf"))
    ("\\.tar$" ("tar" "-uf") ("tar" "-cf"))
    ("\\.tgz$\\|\\.tar\\.g?[zZ]$" ("tar" "-uf %s" "|" "gzip > %s") ("tar" "-czvf"))
    ("\\.ear$" ("zip" "-qr") ("zip" "-qr"))
;   ("\\.rar$" ("rar" "a")   ("rar" "a"))
    ("\\.war$" ("zip" "-qr") ("zip" "-qr"))
    ("\\.zip$" ("zip" "-qr") ("zip" "-qr"))
    ("\\.wmz$" ("zip" "-qr") ("zip" "-qr")) ;; for media player skins
    ("\\.arc$" ("arc" "a") nil)
    ("\\.zoo$" ("zoo" "aP") nil)
    ))

;; use pkzip with manipulating zip files (t) from within dired (use zip
;; and unzip otherwise)
(setq archive-zip-use-pkzip nil)

;; add these file types to archive mode to allow viewing and changing
;; their contents
(add-to-list 'auto-mode-alist '("\\.[ejrw]ar$\\'" . archive-mode))

;; modify the dired-extract switches to use the directory
;; ~/download/tryout as the default extract directory for zip files
(defconst MY_TRYOUT_DIR "~/downloads/tryout"
  "Directory for extracting files")

(setq dired-extract-alist
      `(
    ("\\.u\\(ue\\|aa\\)$" . dired-uud)
    ("\\.jar$" . "jar -xvf %s")
    ("\\.tar$" . ,(concat "tar -xf %s -C " MY_TRYOUT_DIR))
    ("\\.tgz$\\|\\.tar\\.g?[zZ]$" . ,(concat "tar -xzf %s -C " MY_TRYOUT_DIR))
    ("\\.arc$" . "arc x %s ")
    ("\\.bz2$" . ,(concat "bunzip2 -q %s"))
    ("\\.rar$" . ,(concat "unrar x %s " MY_TRYOUT_DIR "\\"))
    ("\\.zip$" . ,(concat "unzip -qq -Ux %s -d " MY_TRYOUT_DIR))
    ("\\.ear$" . ,(concat "unzip -qq -Ux %s -d " MY_TRYOUT_DIR))
    ("\\.war$" . ,(concat "unzip -qq -Ux %s -d " MY_TRYOUT_DIR))
    ("\\.zoo$" . "zoo x. %s ")
    ("\\.lzh$" . "lha x %s ")
    ("\\.7z$"  . "7z e %s ")
    ("\\.g?[zZ]$" . "gzip -d %s")   ; There is only one file
    ))


dired-ediff

[2017-03-23 Thu 16:46]

; ----------------------------------------
;; dired ediff selected files by = key
; ----------------------------------------
;; http://stackoverflow.com/questions/18121808/emacs-ediff-marked-files-in-different-dired-buffers
;; works for files marked in the same dired buffer and also for files in different buffers. In
;; addition to working on 2 marked files potentially across dired buffers, it handles the case when
;; there are 0 or 1 marked files. 0 marked files will use the file under the cursor as file A, and
;; prompt for a file to compare with. 1 marked files will use the marked file as file A, and prompt
;; for a file to compare with. The file under the point is used as the default in the prompt. I
;; bound this to =

;;ediff-split-window-function ;; http://www.gnu.org/software/emacs/manual/html_node/ediff/Miscellaneous.html

(defun mkm/ediff-marked-pair ()
   "Run ediff-files on a pair of files marked in dired buffer"
   (interactive)
   (let* ((marked-files (dired-get-marked-files nil nil))
          (other-win (get-window-with-predicate
                      (lambda (window)
                        (with-current-buffer (window-buffer window)
                          (and (not (eq window (selected-window)))
                               (eq major-mode 'dired-mode))))))
          (other-marked-files (and other-win
                                   (with-current-buffer (window-buffer other-win)
                                     (dired-get-marked-files nil)))))
     (cond ((= (length marked-files) 2)
            (ediff-files (nth 0 marked-files)
                         (nth 1 marked-files)))
           ((and (= (length marked-files) 1)
                 (= (length other-marked-files) 1))
            (ediff-files (nth 0 marked-files)
                         (nth 0 other-marked-files)))
           ((= (length marked-files) 1)
            (let ((single-file (nth 0 marked-files)))
              (ediff-files single-file
                           (read-file-name
                            (format "Diff %s with: " single-file)
                            nil (m (if (string= single-file (dired-get-filename))
                                       nil
                                     (dired-get-filename))) t))))
           (t (error "mark no more than 2 files")))))

(define-key dired-mode-map "=" 'mkm/ediff-marked-pair)


dired bf-mode (disabled)

[2017-03-23 Thu 16:45]

;;----------------------------------------
;; bf-mode
;; Usage:
;;   1. invoke dired by C-x d.
;;   2. b               enter bf-mode
;;   3. b or q          exit from bf-mode
;;   4. n or p          move cursor to target file in order to browse it.
;;   5. SPC             scroll up browsing window
;;      S-SPC           scroll down browsing window
;;   6. r               toggle read-only
;;      j               toggle browsing alternatively (html, archive and more)
;;      s               adjust browsable file size
(use-package bf-mode
  :disabled
  :ensure t
  :config
  ;; list up file extensions which should be excepted
  (setq bf-mode-except-exts
	(append '("\\.dump$" "\\.data$" "\\.mp3$" "\\.lnk$" "\\.avi$" "\\.mov$" )
		bf-mode-except-exts))

  ;; list up file extensions which should be forced browsing
  ;; (setq bf-mode-force-browse-exts
  ;;      (append '("\\.txt$" "\\.and.more...")
  ;;              bf-mode-force-browse-exts))

  ;; browsable file size maximum
  (setq bf-mode-browsing-size 50) ;; 50 killo bytes

  ;; browsing htmls with w3m (needs emacs-w3m.el and w3m)
  (setq bf-mode-html-with-w3m t)

  ;; browsing archive file (contents listing) verbosely
  (setq bf-mode-archive-list-verbose t)

  ;; browing directory (file listing) verbosely
  (setq bf-mode-directory-list-verbose t)

  ;; start bf-mode immediately after starting dired
  (setq bf-mode-enable-at-starting-dired t)

  ;; quitting dired directly from bf-mode
  (setq bf-mode-directly-quit t)
  )

dired follow-mode (peep-dired)

[2017-05-01 Mon 22:15]

https://github.com/asok/peep-dired

(use-package peep-dired
  :ensure t
  :config
  (setq peep-dired-cleanup-on-disable t)
  ;; (setq peep-dired-cleanup-eagerly t)

  ;; (evil-define-key 'normal peep-dired-mode-map (kbd "<SPC>") 'peep-dired-scroll-page-down
  ;;                                            (kbd "C-<SPC>") 'peep-dired-scroll-page-up
  ;;                                            (kbd "<backspace>") 'peep-dired-scroll-page-up
  ;;                                            (kbd "j") 'peep-dired-next-file
  ;;                                            (kbd "k") 'peep-dired-prev-file)
  ;; (add-hook 'peep-dired-hook 'evil-normalize-keymaps)

  (define-key peep-dired-mode-map (kbd "j") 'peep-dired-next-file)
  (define-key peep-dired-mode-map (kbd "k") 'peep-dired-prev-file)
  (setq peep-dired-ignored-extensions '("mkv" "iso" "mp4" "mp3" "ogg"))
  :defer t ; don't access `dired-mode-map' until `peep-dired' is loaded
  :bind (:map dired-mode-map
              ("P" . peep-dired))
  )

dired open with

[2017-03-23 Thu 16:41]

(defun add-dired-extension-list (command extension-list)
  (mapc (lambda (extension)
          (add-to-list 'dired-guess-shell-alist-user (list extension command)))
        extension-list))


(add-hook 'dired-load-hook
          (function (lambda ()
                      (load "dired-x")
                      (add-dired-extension-list "mplayer -really-quiet --" (make-regex-file-extension-list (make-file-part-extensions '("avi" "mkv" "mpg" "mpeg" "mp4" "flv" "wmv" "rm" "asf" "wav" "VOB" "ram" "divx" "mov" "ogv" "flc" "swf"))))
                      (add-dired-extension-list "xterm -e mplayer --" (make-regex-file-extension-list (make-file-part-extensions '("spx" "flac" "mp3" "ogg"))))
                      ;; (add-to-list 'dired-guess-shell-alist-user (list "\\.cbr$" "comix --"))
                      ;; (add-dired-extension-list "evince --" (make-regex-file-extension-list (make-file-part-extensions '("pdf" "ps"))))
                      ;; (add-to-list 'dired-guess-shell-alist-user (list "\\.pdf$" "evince --"))
                      ;; (add-to-list 'dired-guess-shell-alist-user (list "\\.cbz$" "comix --"))
                      )))

autocompletion

hippie-expand

(global-set-key (kbd "H-SPC") 'hippie-expand)

;; from Sacha Chua config
(setq hippie-expand-try-functions-list
      '(yas-hippie-try-expand
        try-expand-all-abbrevs
        try-complete-file-name-partially
        try-complete-file-name
        try-expand-dabbrev
        try-expand-dabbrev-from-kill
        try-expand-dabbrev-all-buffers
        try-expand-list
        try-expand-line
        try-complete-lisp-symbol-partially
        try-complete-lisp-symbol))

auto-complete (disabled)

;; https://github.com/auto-complete/auto-complete
;; https://github.com/auto-complete/auto-complete/blob/master/doc/manual.md
;;company successor ;; (require 'auto-complete-config)
;;company successor ;; (add-to-list 'ac-dictionary-directories "~/.emacs.d/ac-dict")
;;company successor ;; (ac-config-default)
;;company successor ;; ;; (global-auto-complete-mode)
;;company successor ;; (setq ac-use-quick-help t)
;;company successor ;; (setq ac-quick-help-delay 1.5)
;;company successor ;; (setq ac-auto-show-menu 0.8)
;;company successor ;; (setq ac-ignore-case 'smart)
;;company successor ;; (setq ac-use-menu-map t)
;;company successor ;; (setq ac-auto-start 4)
;;company successor ;; (setq ac-use-fuzzy t)
;;company successor ;; (define-key ac-completing-map "<escape>" 'ac-stop)
;;company successor ;; (ac-set-trigger-key "s-SPC")
;;company successor ;; ;; (evil-define-key 'insert prog-mode-map (kbd "s-SPC") 'ac-complete)
;;company successor ;; ;; (evil-define-key 'insert powershell-mode-map (kbd "s-SPC") 'ac-complete)
;;company successor ;; (ac-linum-workaround)
;;company successor ;;
;;company successor ;; (setq-default ac-sources '(ac-source-filename
;;company successor ;;                            ac-source-functions
;;company successor ;;                            ac-source-yasnippet
;;company successor ;;                            ac-source-variables
;;company successor ;;                            ac-source-symbols
;;company successor ;;                            ac-source-features
;;company successor ;;                            ac-source-abbrev
;;company successor ;;                            ac-source-imenu
;;company successor ;;                            ac-source-words-in-same-mode-buffers
;;company successor ;;                            ac-source-dictionary))

;;company successor ;; ;; https://github.com/auto-complete/auto-complete
;;company successor ;; ;; https://github.com/auto-complete/auto-complete/blob/master/doc/manual.md
;;company successor ;; (require 'auto-complete-config)
;;company successor ;; (add-to-list 'ac-dictionary-directories "~/.emacs.d/ac-dict")
;;company successor ;; (ac-config-default)
;;company successor ;; (global-auto-complete-mode)
;;company successor ;; (setq ac-use-quick-help t)
;;company successor ;; (setq ac-quick-help-delay 1.5)
;;company successor ;; (setq ac-auto-show-menu 0.8)
;;company successor ;; (setq ac-ignore-case 'smart)
;;company successor ;; (setq ac-use-menu-map t)
;;company successor ;; (setq ac-auto-start 4)
;;company successor ;; (setq ac-use-fuzzy t)
;;company successor ;;
;;company successor ;; ;; (setq ac-auto-start nil)
;;company successor ;; (define-key ac-completing-map "<escape>" 'ac-stop)
;;company successor ;; (ac-set-trigger-key "s-SPC")
;;company successor ;; (evil-define-key 'insert prog-mode-map (kbd "s-SPC") 'ac-complete)
;;company successor ;; (evil-define-key 'insert powershell-mode-map (kbd "s-SPC") 'ac-complete)
;;company successor ;; ;; (set-face-background 'ac-candidate-face "lightgray")
;;company successor ;; ;; (set-face-underline 'ac-candidate-face "darkgray")
;;company successor ;; ;; (set-face-background 'ac-selection-face "steelblue")
;;company successor ;; (ac-linum-workaround)
;;company successor ;;
;;company successor ;; (setq-default ac-sources '(ac-source-filename
;;company successor ;;                            ac-source-functions
;;company successor ;;                            ac-source-yasnippet
;;company successor ;;                            ac-source-variables
;;company successor ;;                            ac-source-symbols
;;company successor ;;                            ac-source-features
;;company successor ;;                            ac-source-abbrev
;;company successor ;;                            ac-source-imenu
;;company successor ;;                            ac-source-words-in-same-mode-buffers
;;company successor ;;                            ac-source-dictionary))
;;company successor ;;
;;company successor ;; (require 'ac-anaconda)
;;company successor ;; (add-hook 'emacs-lisp-mode-hook 'turn-on-eldoc-mode)

company

;;http://company-mode.github.io/
(use-package company)
;; (setq company-idle-delay nil)
;; (setq company-idle-delay 1)
;; (setq company-show-numbers t)
;; (add-hook 'after-init-hook 'global-company-mode)
;; (setq company-require-match 'never)

(global-company-mode t)
(setq company-idle-delay                -1
      delete-selection-mode             t
      company-minimum-prefix-length     2
      company-dabbrev-downcase          nil
      company-dabbrev-other-buffers     t
      company-echo-delay                0
      company-show-numbers              t
      company-dabbrev-code-everywhere   t
      company-dabbrev-code-ignore-case  t
      company-selection-wrap-around     t
      company-tooltip-align-annotations t
      selection-coding-system           'utf-8
      company-auto-complete-chars       '(32 40 41 119 46 34 36 47 124 33)
      company-backends '((
                          company-yasnippet
                          company-semantic
                          company-capf
                          company-etags
                          company-files
                          company-keywords
                          company-dabbrev-code
                          company-dabbrev)))



(defun bss/tab-or-complete ()
  (interactive)
  (let ((start (line-beginning-position))
        (mypoint (point))
        (notfound t))


    (if (equal major-mode 'org-mode)
    (org-cycle)
      (progn ;; not in org-mode
    ;; if we first non-whitespace from line begin
    (if (string-match "^[[:space:]]*$" (buffer-substring (line-beginning-position) (point)))
        (progn
          (setq notfound nil)
          (insert "    "))
	  (save-excursion
	    (backward-char 1)
	    (if (and (string-match "^[[:space:]]*$" (buffer-substring (point) mypoint))
		     (>= (point) (line-beginning-position))) ; we on same line
		(progn
		  (insert "    ")
		  (setq notfound nil)
		  ))))
	;; (if notfound (company-complete-common))
	(if notfound
	    (if (company-manual-begin)
		(company-complete-common)
              (insert "    ")))
	))
    ))

(evil-define-key 'insert prog-mode-map (kbd "s-SPC") 'company-complete)
(evil-define-key 'insert powershell-mode-map (kbd "s-SPC") 'company-complete)
(evil-define-key 'insert prog-mode-map (kbd "<tab>") 'bss/tab-or-complete)
(evil-define-key 'insert org-mode-map (kbd "<tab>") 'bss/tab-or-complete)
(define-key prog-mode-map (kbd "<tab>") 'bss/tab-or-complete)

;; mapping works only in insert mode:
(evil-define-key 'insert prog-mode-map (kbd "<H-tab>") 'indent-according-to-mode)
(define-key prog-mode-map (kbd "<H-tab>") 'indent-according-to-mode)

;; ;; https://github.com/company-mode/company-mode/wiki/Switching-from-AC
(eval-after-load 'company
  '(progn
     (define-key company-active-map (kbd "TAB") 'company-complete-common-or-cycle)
     (define-key company-active-map (kbd "<tab>") 'company-complete-common-or-cycle)
     (define-key company-active-map (kbd "S-TAB") 'company-select-previous)
     (define-key company-active-map (kbd "<backtab>") 'company-select-previous)))


(use-package color)

(let ((bg (face-attribute 'default :background)))
  (custom-set-faces
   `(company-tooltip ((t (:inherit default :background ,(color-lighten-name bg 20)))))
   `(company-scrollbar-bg ((t (:background ,(color-lighten-name bg 40)))))
   `(company-scrollbar-fg ((t (:background ,(color-lighten-name bg 60)))))
   `(company-tooltip-selection ((t (:inherit font-lock-function-name-face))))
   `(company-tooltip-common ((t (:inherit font-lock-constant-face))))))



;; company autocompletion in org babel
(defun add-pcomplete-to-capf ()
  (add-hook 'completion-at-point-functions 'pcomplete-completions-at-point nil t))

(add-hook 'org-mode-hook #'add-pcomplete-to-capf)

imenu - tags navigation

[2017-10-05 Thu 10:10]

секции/imenu

Настройки для разделения на секции (http://metasandwich.com/2013/01/19/emacs-config-youre-doing-it-wrong/) В imenu можно добавлять секции текущего файла. Ниже настройка для elsp для строчек, начинающихся с ;;;; ;;;; BINDINGS … ;;;; HOOKS …

(defun imenu-elisp-sections ()
  (setq imenu-prev-index-position-function nil)
  (add-to-list 'imenu-generic-expression '("Foldings" "^;; \\(.+\\) \{\\{3\\}$" 1) t)
  (add-to-list 'imenu-generic-expression '("Foldings" "^;; \\(.+\\) {\\{3\\}$" 1) t)
  ;; (add-to-list 'imenu-generic-expression '("Foldings3" "^# \\(.+\\) {\\{3\\}$" 1) t)
  ;; (add-to-list 'imenu-generic-expression '("Foldings4" "^# \\(.+\\) \{\\{3\\}$" 1) t)
  (add-to-list 'imenu-generic-expression '("Sections" "^;;;; \\(.+\\)$" 1) t))

(add-hook 'emacs-lisp-mode-hook 'imenu-elisp-sections)

;; (defun imenu-python-sections ()
;;   (interactive)
;;   ;; (setq imenu-prev-index-position-function nil)
;;   (add-to-list 'imenu-generic-expression '("Foldings" "^# \\(.+\\) \{\\{3\\}$" 1) t)
;;   ;; (add-to-list 'imenu-generic-expression '("Foldings" "^# \\(.+\\) {\\{3\\}$" 1) t)
;;   (add-to-list 'imenu-generic-expression '("Sections" "^#### \\(.+\\)$" 1) t))
;; ;; (add-hook 'python-mode-hook 'imenu-python-sections)

;; (require 'semantic)
;; ;; http://stackoverflow.com/questions/21644876/imenu-does-not-work-for-python-mode-or-c-mode
;; (defun my-merge-imenu ()
;;   (interactive)
;;   (let ((mode-imenu (imenu-default-create-index-function))
;;         (custom-imenu (imenu--generic-function imenu-generic-expression)))
;;     (append mode-imenu custom-imenu)))



;; (add-hook 'python-mode-hook
;;           (lambda ()
;;             (add-to-list 'imenu-generic-expression '("Sections" "^#### \\[ \\(.*\\) \\]$" 1))
;;             (add-to-list 'imenu-generic-expression '("Foldings" "^# \\[ \\(.*\\) \\] {\\{3\\}$" 1))
;;             ;; (imenu-add-to-menubar "Position")
;;             (setq imenu-create-index-function 'my-merge-imenu)
;; 	    ))

;; Shuffling lines {{{

(defun my/shuffle-lines-in-region (beg end)
  (interactive "r")
  (let ((list (split-string (buffer-substring beg end) "[\r\n]+")))
    (delete-region beg end)
    (insert (mapconcat 'identity (shuffle-list list) "\n"))))
;; }}}

better imenu usage

[2017-10-04 Wed 20:31]

;; from http://rakan.me/emacs/code-navigation-in-emacs/


(defun codenav-imenu-candidates ()
  "Get the candidates list from imenu."
  (let* ((items (imenu--make-index-alist))
	 (items (delete (assoc "*Rescan*" items) items)))
    items))

(defun codenav-flatten-candidates (candidates)
  "Flatten CANDIDATES of imenu list."
  (let (result)
    (dolist (candidate candidates result)
      (if (imenu--subalist-p candidate)
          (setq result (append result (codenav-flatten-candidates (cdr candidate))))
        (add-to-list 'result candidate)))
    result))

(defun codenav-sort-candidates (candidates)
  (sort candidates (lambda (a b) (< (cdr a) (cdr b)))))

(defun codenav-current-symbol (names-and-pos)
  "Figure out current definition by checking positions of NAMES-AND-POS against current position."
  (let ((list-length (length names-and-pos))
        (current-pos (point))
        (current-index 0)
        (next-index 0))
    (dolist (symbol names-and-pos)
      ;; If we reaches the end, just return the last element
      ;; instead of returning index+1
      (setq next-index (if (< next-index (1- list-length))
                          (1+ current-index)
                         current-index))
      (let* ((current-symbol-pos (marker-position (cdr symbol)))
	     (next-symbol-pos (marker-position (cdr (nth next-index names-and-pos)))))
        (if (and (= current-index 0) (< current-pos current-symbol-pos))
            (return 0))
	(if (and (>= current-pos current-symbol-pos) (< current-pos next-symbol-pos))
	    (return current-index)))
      (setq current-index (1+ current-index)))
    ;; If last item, decrement index
    (if (eq current-index (length names-and-pos))
	(1- current-index)
      current-index)))

(defun codenav-next-definition ()
  "Navigate to next function/class definition."
  (interactive)
  (let* ((imenu-candidates (codenav-imenu-candidates))
         (names-and-pos (codenav-sort-candidates (codenav-flatten-candidates imenu-candidates)))
	 (current-symbol (codenav-current-symbol names-and-pos))
         (next-symbol-index (if (>= (1+ current-symbol) (length names-and-pos)) 0
                              (1+ current-symbol)))
	 (next-symbol (nth next-symbol-index names-and-pos)))
    (imenu next-symbol)))


(defun codenav-prev-definition ()
  "Navigate to previous function/class definition."
  (interactive)
  (let* ((imenu-candidates (codenav-imenu-candidates))
         (names-and-pos (codenav-sort-candidates (codenav-flatten-candidates imenu-candidates)))
	 (current-symbol (codenav-current-symbol names-and-pos))
         (prev-symbol-index (if (< (1- current-symbol) 0) (1- (length names-and-pos))
                              (1- current-symbol)))
	 (prev-symbol (nth prev-symbol-index names-and-pos)))
    (imenu prev-symbol)))


(global-set-key (kbd "H-k") (lambda () (interactive) (codenav-prev-definition)))
(global-set-key (kbd "H-j") (lambda () (interactive) (codenav-next-definition)))

vspinu/imenu-anywhere: ido/ivy/helm imenu tag selection across buffers with the same mode/project etc

(use-package imenu-anywhere)

все заголовки org-mode в imenu

[2017-10-10 Tue 11:39]

(setq org-imenu-depth 5)
(setq imenu-auto-rescan t)

ediff

(use-package ediff
  :config
  (setq ediff-window-setup-function 'ediff-setup-windows-plain)
  (setq-default ediff-highlight-all-diffs 'nil)
  (setq ediff-diff-options "-w"))

;; command-line diff from https://www.emacswiki.org/emacs/EdiffMode
;; Usage: emacs -diff file1 file2
(defun command-line-diff (switch)
  (let ((file1 (pop command-line-args-left))
        (file2 (pop command-line-args-left)))
    (ediff file1 file2)))

(add-to-list 'command-switch-alist '("diff" . command-line-diff))

key-chords

;; Key-chords
(use-package key-chord)
(setq key-chord-two-keys-delay 0.5)
;; (key-chord-define evil-insert-state-map "jk" '(lambda () (interactive)(evil-normal-state)(forward-char 1)))
(key-chord-define evil-insert-state-map "kj" '(lambda () (interactive)(evil-normal-state)(forward-char 1)))
;; (key-chord-define evil-visual-state-map "jk" 'evil-normal-state)
(key-chord-define evil-visual-state-map "kj" 'evil-normal-state)
;; (key-chord-define evil-visual-state-map "jk" '(lambda () (interactive)(evil-normal-state)(forward-char 1)))
;; (key-chord-define evil-visual-state-map "kj" '(lambda () (interactive)(evil-normal-state)(forward-char 1)))
(key-chord-mode 1)



;; (key-chord-define evil-insert-state-map "jj" 'evil-normal-state)
;; http://stackoverflow.com/questions/10569165/how-to-map-jj-to-esc-in-emacs-evil-mode
;; (define-key evil-insert-state-map "о" #'cofi/maybe-exit)

;; (evil-define-command cofi/maybe-exit ()
;;   :repeat change
;;   (interactive)
;;   (let ((modified (buffer-modified-p)))
;;     (insert "о")
;;     (let ((evt (read-event (format "Insert %c to exit insert state" ?о)
;;                nil 0.5)))
;;       (cond
;;        ((null evt) (message ""))
;;        ((and (integerp evt) (char-equal evt ?о))
;;     (delete-char -1)
;;     (set-buffer-modified-p modified)
;;     (push 'escape unread-command-events))
;;        (t (setq unread-command-events (append unread-command-events
;;                           (list evt))))))))


;; (key-chord-mode -1)
;; (setq key-chord-two-keys-delay 0.05)
;;
;; and some chords, for example
;;
;; (key-chord-define-global ",."     'ace-jump-char-mode)
;; (key-chord-define-global "kl"     'ace-jump-mode)
;; (key-chord-define-global "jk"     'scroll-down-command)
;; (key-chord-define-global "m,"     'scroll-up-command)

multiple cursors

;;;; multilple cursors package
;; https://github.com/magnars/multiple-cursors.el
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(use-package multiple-cursors)
;;settings in ~/.emacs.d/.mc-lists.el

(use-package multiple-cursors
  :ensure t :defer t
  :bind
    (("C-c m t" . mc/mark-all-like-this)
     ("C-c m m" . mc/mark-all-like-this-dwim)
     ("C-c m l" . mc/edit-lines)
     ("C-c m e" . mc/edit-ends-of-lines)
     ("C-c m a" . mc/edit-beginnings-of-lines)
     ("C-c m n" . mc/mark-next-like-this)
     ("C-c m p" . mc/mark-previous-like-this)
     ("C-c m s" . mc/mark-sgml-tag-pair)
     ("C-c m d" . mc/mark-all-like-this-in-defun)))

;;(use-package mc-extras)
;;(define-key mc/keymap (kbd "C-. C-d") 'mc/remove-current-cursor)
;;(define-key mc/keymap (kbd "C-. d")   'mc/remove-duplicated-cursors)
;;
;;(define-key mc/keymap (kbd "C-. =")   'mc/compare-chars)
;;
;;; Emacs 24.4+ comes with rectangle-mark-mode.
;; (define-key rectangle-mark-mode-map (kbd "C-. C-,") 'mc/rect-rectangle-to-multiple-cursors)

;;enable mouse with C-S-mouse 1
;; (global-set-key (kbd "C-S-<mouse-1>") 'mc/add-cursor-on-click)
(global-unset-key (kbd "M-<down-mouse-1>"))
(global-set-key (kbd "M-<mouse-1>") 'mc/add-cursor-on-click)

workspace package

python-mode

(use-package python
  :mode ("\\.py" . python-mode)
  :config
  (setq py-python-command "python3")
  (setq python-shell-interpreter "python3")
  (setq python-indent-offset 4)



  (use-package jedi-core
    :config
    (setq jedi:get-in-function-call-timeout 0
          jedi:get-in-function-call-delay   0
          jedi:goto-definition-config       '((nil definition nil)))
    )

  (use-package company-jedi
    :config
    ;; (setq jedi:complete-on-dot t)
    ;; (add-hook 'python-mode-hook 'jedi:setup)
    ;; (jedi:install-server)
    )



  (use-package company-flx
    :config
    (with-eval-after-load 'company
                    (company-flx-mode +1)))

  (use-package helm-company
    :config
    (define-key company-mode-map (kbd "C-:") 'helm-company)
    (define-key company-active-map (kbd "C-:") 'helm-company)
    )

  (add-hook 'python-mode-hook
            (lambda()
              (interactive)
              (setenv "TERM" "ansi-term")
              (setq python-shell-completion-native nil
                    indent-tabs-mode                 nil
                    tab-width                      4
                    python-indent                  4
                    python-shell-interpreter         "ipython"
                    python-shell-interpreter-args  "--profile=emacs"
                    )
              (defun python-startup-function (start end &optional send-main msg)
                (unless (python-shell-get-process)
                  (run-python)))
              (add-function :before (symbol-function 'python-shell-send-region)  #'python-startup-function)
              ;; (add-to-list
              ;;  'imenu-generic-expression
              ;;  '("Sections" "^#### \\[ \\(.*\\) \\]$" 1))
              ;; (setq imenu-create-index-function 'my-merge-imenu)
              ;; pythom mode keybindings
              (define-key python-mode-map (kbd "M-.") 'jedi:goto-definition)
              ;; (define-key python-mode-map (kbd "C-c C-b") 'insert_ipdb)
              (define-key python-mode-map (kbd "C-c C-b") 'python-add-breakpoint)
              (define-key python-mode-map (kbd "RET") 'newline-and-indent)
              (define-key python-mode-map (kbd "M-RET") 'newline)
              (define-key python-mode-map (kbd "M-,") 'jedi:goto-definition-pop-marker)
              (define-key python-mode-map (kbd "M-/") 'jedi:show-doc)
              (define-key python-mode-map (kbd "M-?") 'helm-jedi-related-names)
              ;; (define-key python-mode-map (kbd "<f8>")  'next-error)
              ;; (define-key python-mode-map (kbd "<S-F8>") 'previous-error)
              ;; end python mode keybindings
              (add-to-list 'write-file-functions 'delete-trailing-whitespace)
              (modify-syntax-entry ?_ "w")
              (modify-syntax-entry ?- "w")
              ;; (py-autopep8-enable-on-save)
              (set (make-local-variable 'compile-command) (concat "python3 " buffer-file-name))

              (eval-after-load "company"
                '(progn
                   (unless (member 'company-jedi (car company-backends))
                     (setq comp-back (car company-backends))
                     (push 'company-jedi comp-back)
                     (setq company-backends (list comp-back)))))
              ))

;;
;; pystart: python header
(define-skeleton skel-python-pystart
  "Python file with utf output abbrev"
  "\n"
  "#!/usr/bin/env python\n"
  "# -*- coding: utf-8 -*-\n"
  "\n"
  "import sys\n"
  "reload(sys)\n"
  "sys.setdefaultencoding('utf-8')\n"
  "\n"
  "def main():\n"
  "    " _
  "\n"
  "if __name__ == \"__main__\":\n"
  "   main()\n"
  "\n")
 (define-abbrev python-mode-abbrev-table "pystart" "" 'skel-python-pystart)

(define-skeleton skel-python-utffile
  "utf file coding string"
  "\n"
  "# -*- coding: utf-8 -*-\n"
  "from __future__ import unicode_literals\n"
)
(define-abbrev python-mode-abbrev-table "utffile" "" 'skel-python-utffile)

              ;; ))
  ;; Подсвечивать строки, которые обычно используются при отладке
  (defun annotate-pdb()
    (interactive)
    (highlight-lines-matching-regexp "import ipdb")
    (highlight-lines-matching-regexp "import pdb")
    (highlight-lines-matching-regexp "set_trace()")
    (highlight-phrase "TODO:")
    (highlight-regexp "FIXME:")
    (highlight-regexp "BUG:")
    )
  (add-hook 'python-mode-hook 'annotate-pdb)

  (use-package flycheck
    ;; :disabled
    :ensure t
    ;; :init (global-flycheck-mode)
    :config
    ;; (setq elpy-modules (delq 'elpy-module-flymake elpy-modules))
    ;; (add-hook 'elpy-mode-hook 'flycheck-mode)
    (add-hook 'python-mode-hook 'flycheck-mode)
    )
  ;; cat ~/.config/flake8
  ;; [flake8]
  ;; ignore = E221,E501,E203,E202,E272,E251,E211,E222,E701
  ;; max-line-length = 160
  ;; exclude = tests/*
  ;; max-complexity = 10

  (use-package python-django)

  (use-package py-autopep8
    :disabled
    :config
    (add-hook 'python-mode-hook 'py-autopep8-enable-on-save)
    )





  (use-package pip-requirements
    :config
    (add-hook 'pip-requirements-mode-hook #'pip-requirements-auto-complete-setup)
    (add-to-list 'auto-mode-alist '("\\REQUIREMENTS" . pip-requirements-mode))
    (add-to-list 'auto-mode-alist '("\\REQUIREMENTS.txt" . pip-requirements-mode))
    (add-to-list 'auto-mode-alist '("\\requirements" . pip-requirements-mode))
    (add-to-list 'auto-mode-alist '("\\requirements.txt" . pip-requirements-mode))


    )

  (use-package virtualenvwrapper
    ;; :ensure t
    :config
    ;; (use-package virtualenvwrapper)
    (venv-initialize-interactive-shells)
    (venv-initialize-eshell)
    (setq venv-location "~/.virtualenvs")
    )

  (add-to-list 'Info-default-directory-list "~/.emacs.d/elpa/python-info-20151228.1052")
  (use-package info-look)

  (info-lookup-add-help
   :mode 'python-mode
   :regexp "[[:alnum:]_]+"
   :doc-spec
   '(("(python)Index" nil "")))

  ;; http://pswinkels.blogspot.ru/2010/04/debugging-python-code-from-within-emacs.html
  (defvar gud-pdb-marker-regexp
    "^> \\([-a-zA-Z0-9_ /.:\\]*\\|<string>\\)(\\([0-9]+\\))\\([a-zA-Z0-9_]*\\|\\?\\|<module>\\)()\\(->[^\n]*\\)?[\n]")

  (defun python-add-breakpoint ()
    "Add a break point"
    (interactive)
    (newline-and-indent)
    (insert "import pdb; pdb.set_trace()")
    (highlight-lines-matching-regexp "^[ ]*import ipdb; ipdb.set_trace()"))





  )

;; (lambda () ;; (setq-local indent-tabs-mode nil) ;; (setq-local tab-width 4) ;; (setq-local py-indent-tabs-mode t) ;; (local-set-key [f8] ‘next-error) ;; (local-set-key [(shift f8)] ‘previous-error) ;; (add-to-list ‘write-file-functions ‘delete-trailing-whitespace) ;; (define-key python-mode-map (kbd “RET”) ‘newline-and-indent) ;; ;;(define-key python-mode-map “\C-m” ‘newline-and-indent) ;; (define-key python-mode-map (kbd “C-c C-b”) ‘python-add-breakpoint) ;; (modify-syntax-entry ?_ “w”) ;; (modify-syntax-entry ?- “w”) ;; ;; (py-autopep8-enable-on-save) ;; (set (make-local-variable ‘compile-command) (concat “python3 ” buffer-file-name)) ;; (turn-on-eldoc-mode) ;; (add-to-list ‘company-backends ‘company-jedi))

;; (add-hook ‘python-mode-hook ’

(use-package elpy :disabled ;; https://elpy.readthedocs.io/en/latest/index.html ;; first install One-line install: pip install jedi flake8 importmagic autopep8 ;; and then run M-x elpy-config to configure elpy :init (add-to-list ‘auto-mode-alist ‘(“\.py$” . python-mode)) :config (setq elpy-rpc-backend “jedi” ;; elpy-rpc-large-buffer-size 10000 ) (when (executable-find “ipython”) (elpy-use-ipython)) (elpy-enable) :bind (:map elpy-mode-map (“M-.” . elpy-goto-definition) (“M-,” . pop-tag-mark)))

(use-package company-anaconda ;; :disabled :config

(eval-after-load “company” ‘(add-to-list ‘company-backends ‘company-anaconda))

(add-hook ‘python-mode-hook ‘anaconda-mode) (add-hook ‘python-mode-hook ‘anaconda-eldoc-mode) ;; Keybinding Description ;; C-M-i anaconda-mode-complete ;; M-. anaconda-mode-find-definitions ;; M-, anaconda-mode-find-assignments ;; M-r anaconda-mode-find-references ;; M-* anaconda-mode-go-back ;; M-? anaconda-mode-show-doc ;; Python info ;; Info-default-directory-list )

;; (use-package pyenv-mode ;; :init ;; (add-to-list ‘exec-path “~/.pyenv/shims”) ;; (setenv “WORKON_HOME” “~/.pyenv/versions/”) ;; :config ;; (pyenv-mode) ;; :bind ;; (“C-x p e” . pyenv-activate-current-project))

;; (defun pyenv-init() ;; (setq global-pyenv (replace-regexp-in-string “\n” “” (shell-command-to-string “pyenv global”))) ;; (message (concat “Setting pyenv version to ” global-pyenv)) ;; (pyenv-mode-set global-pyenv) ;; (defvar pyenv-current-version nil global-pyenv))

;; (defun pyenv-activate-current-project () ;; “Automatically activates pyenv version if .python-version file exists.” ;; (interactive) ;; (f-traverse-upwards ;; (lambda (path) ;; (message path) ;; (let ((pyenv-version-path (f-expand “.python-version” path))) ;; (if (f-exists? pyenv-version-path) ;; (progn ;; (setq pyenv-current-version (s-trim (f-read-text pyenv-version-path ‘utf-8))) ;; (pyenv-mode-set pyenv-current-version) ;; (pyvenv-workon pyenv-current-version) ;; (message (concat “Setting virtualenv to ” pyenv-current-version))))))))

;; (add-hook ‘after-init-hook ‘pyenv-init) ;; (add-hook ‘projectile-after-switch-project-hook ‘pyenv-activate-current-project)

;; Tree style source code viewer for Python buffer ;; (use-package jedi-direx ;; :ensure t ;; :config ;; (eval-after-load “python” ;; ‘(define-key python-mode-map “\C-cx” ‘jedi-direx:pop-to-buffer)) ;; (add-hook ‘jedi-mode-hook ‘jedi-direx:setup) ;; )

php-mode

from inet

[2017-03-20 Mon 11:23]

;; #+begin_src emacs-lisp (use-package ggtags :ensure t :commands ggtags-mode :diminish ggtags-mode :config (setq ggtags-completing-read-function nil))

(use-package smartparens :disabled :ensure smartparens :commands (smartparens turn-on-smartparens-strict-mode) :bind ((“C-d” . sp-delete-char) (“C-M-f” . sp-forward-sexp) (“C-M-b” . sp-backward-sexp) (“C-M-k” . sp-kill-sexp) (“C-M-e” . sp-up-sexp) (“C-M-n” . sp-next-sexp) (“C-M-p” . sp-previous-sexp) (“C-M-s” . sp-unwrap-sexp) (“C-M-t” . sp-transpose-sexp) (“C-M-<backspace>” . sp-backward-unwrap-sexp) (“C-M-w” . sp-copy-sexp) (“C-<right>” . sp-slurp-hybrid-sexp) (“C-<left>” . sp-forward-barf-sexp) (“C-M-<left>” . sp-backward-slurp-sexp) (“C-M-<right>” . sp-backward-barf-sexp) (“M-F” . sp-forward-symbol) (“M-B” . sp-backward-symbol)) :config (use-package smartparens-config))

(use-package php-extras :disabled :ensure t :commands php-mode)

(use-package phpcbf :ensure t :commands php-mode :config (setq phpcbf-standard “PSR2”))

(use-package phpunit :ensure t :commands php-mode)

(use-package company-php :ensure t :after php-mode :config (add-to-list ‘company-backends ‘company-ac-php-backend))

(use-package php-mode :ensure t :bind ((“C–” . cmack/php-quick-arrow) :map php-mode-map (“C-d” . sp-delete-char)) :config

(defun cmack/php-quick-arrow (arg) “Inserts -> at point” (interactive “P”) (insert (if arg “=>” “->”)))

(defun cmack/php-mode-hook () (emmet-mode +1) (flycheck-mode +1) ;; (ggtags-mode 1) (helm-gtags-mode +1) (company-mode +1) (eldoc-mode +1) (turn-on-auto-fill) ;; (electric-indent-mode) ;; (electric-pair-mode) ;; (electric-layout-mode) (smartparens-strict-mode +1) (setq flycheck-phpcs-standard “PSR2” flycheck-php-executable ”opt/local/bin/php” flycheck-php-phpcs-executable “~.composer/vendor/bin/phpcs” flycheck-php-phpmd-executable “~/.composer/vendor/bin/phpmd”)

;; Experiment with highlighting keys in assoc. arrays (font-lock-add-keywords ‘php-mode ‘((“\s"\([^\s;]+\)\s"\s-+=>\s-+” 1 ‘font-lock-variable-name-face t) (“->\(\w+\)(” 1 ‘font-lock-function-name-face ))))

;; (setq php-executable “/usr/bin/php”) (setq php-mode-coding-style ‘psr2) (setq tab-width 4 fill-column 119 indent-tabs-mode nil)

(add-hook ‘php-mode-hook #’cmack/php-mode-hook)) ;; #+end_src

bss

;; company successor ;; (use-package ac-php)

(use-package php-mode
  :mode
  (("\\.php\\'" . php-mode))
  :config
  (add-hook 'php-mode-hook
            '(lambda ()
               (setq-local tab-always-indent 'complete)
               (modify-syntax-entry ?_ "w")
               (modify-syntax-entry ?- "w")
               (auto-complete-mode t)
               ;; company successor ;; (use-package ac-php)
               ;; company successor ;; (setq ac-sources  '(ac-source-php ) )
               ;; (use-package company-php)
               ;; (company-mode t)
               ;; (add-to-list 'company-backends 'company-ac-php-backend )
               (yas-global-mode 1)
               ;; company successor ;; (define-key php-mode-map  (kbd "C-]") 'ac-php-find-symbol-at-point)   ;goto define
               ;; company successor ;; (define-key php-mode-map  (kbd "C-t") 'ac-php-location-stack-back   ) ;go back
               ))
  ;; company successor ;; (evil-define-key 'insert php-mode-map (kbd "s-SPC") 'ac-start)
  ;; (evil-define-key 'insert php-mode-map (kbd "s-SPC") 'bss/tab-or-complete)
  (evil-define-key 'insert php-mode-map (kbd "<tab>") 'bss/tab-or-complete)
  ;; (add-to-list 'load-path "~/.emacs.d/manual-addons/php-extras")
  ;; (use-package php-extras)
  ;; (use-package php-extras-gen-eldoc)

  ;; (use-package phpunit
  ;;   :mode
  ;;   (("\\.php\\'" . phpunit-mode)))

  )

skeletons, yasnippet, abbrev

abbrev-mode

enable mode

;; Enable abbrev-mode
;; From https://github.com/purcell/emacs.d/blob/master/lisp/init-auto-complete.el - Exclude very large buffers from dabbrev
(defun sanityinc/dabbrev-friend-buffer (other-buffer)
  (< (buffer-size other-buffer) (* 1 1024 1024)))
(setq dabbrev-friend-buffer-function 'sanityinc/dabbrev-friend-buffer)

(add-hook 'org-mode-hook (lambda () (abbrev-mode 1)))
(add-hook 'python-mode-hook (lambda () (abbrev-mode 1)))

Define more abbreviations

BaseExpansion
wowithout
wiwith
qm[email protected]
qehttp://sachachua.com/dotemacs
;; (mapc (lambda (x) (define-global-abbrev (car x) (cadr x))) (cddr data))
;; (add-hook 'text-mode-hook 'abbrev-mode)
;; (diminish 'abbrev-mode " A")

org-structure-template

Org makes it easy to insert blocks by typing <s[TAB], etc. I hardly ever use LaTeX, but I insert a lot of Emacs Lisp blocks, so I redefine <l to insert a Lisp block instead.

;; type ‘<’ followed by the key and then press the completion key, usually ‘TAB’.
(setq org-structure-template-alist
      (quote (("s" "#+begin_src ?\n\n#+end_src" "<src lang=\"?\">\n\n</src>")
              ("e" "#+begin_example\n?\n#+end_example" "<example>\n?\n</example>")
              ("q" "#+begin_quote\n?\n#+end_quote" "<quote>\n?\n</quote>")
              ("v" "#+begin_verse\n?\n#+end_verse" "<verse>\n?\n</verse>")
              ("c" "#+begin_center\n?\n#+end_center" "<center>\n?\n</center>")
              ("l" "#+begin_latex\n?\n#+end_latex" "<literal style=\"latex\">\n?\n</literal>")
              ("L" "#+latex: " "<literal style=\"latex\">?</literal>")
              ("h" "#+begin_html\n?\n#+end_html" "<literal style=\"html\">\n?\n</literal>")
              ("H" "#+html: " "<literal style=\"html\">?</literal>")
              ("a" "#+begin_ascii\n?\n#+end_ascii")
              ("A" "#+ascii: ")
              ("i" "#+index: ?" "#+index: ?")
              ("I" "#+include %file ?" "<include file=%file markup=\"?\">"))))

skeletons

;;;; Skeletons



;; sblk - Generic block #+begin_FOO .. #+end_FOO
(define-skeleton skel-org-block
  "Insert an org block, querying for type."
  "Type: "
  "#+begin_" str "\n"
  _ - \n
  "#+end_" str "\n")

(define-abbrev org-mode-abbrev-table "sblk" "" 'skel-org-block)

;; splantuml - PlantUML Source block
(define-skeleton skel-org-block-plantuml
  "Insert a org plantuml block, querying for filename."
  "File (no extension): "
  "#+begin_src plantuml :file " str ".png :cache yes\n"
  _ - \n
  "#+end_src\n")

(define-abbrev org-mode-abbrev-table "splantuml" "" 'skel-org-block-plantuml)

(define-skeleton skel-org-block-plantuml-activity
  "Insert a org plantuml block, querying for filename."
  "File (no extension): "
  "#+begin_src plantuml :file " str "-act.png :cache yes :tangle " str "-act.txt\n"
  (bh/plantuml-reset-counters)
  "@startuml\n"
  "skinparam activity {\n"
  "BackgroundColor<<New>> Cyan\n"
  "}\n\n"
  "title " str " - \n"
  "note left: " str "\n"
  "(*) --> \"" str "\"\n"
  "--> (*)\n"
  _ - \n
  "@enduml\n"
  "#+end_src\n")

(defvar bh/plantuml-if-count 0)

(defun bh/plantuml-if ()
  (incf bh/plantuml-if-count)
  (number-to-string bh/plantuml-if-count))

(defvar bh/plantuml-loop-count 0)

(defun bh/plantuml-loop ()
  (incf bh/plantuml-loop-count)
  (number-to-string bh/plantuml-loop-count))

(defun bh/plantuml-reset-counters ()
  (setq bh/plantuml-if-count 0
        bh/plantuml-loop-count 0)
  "")

(define-abbrev org-mode-abbrev-table "sact" "" 'skel-org-block-plantuml-activity)

(define-skeleton skel-org-block-plantuml-activity-if
  "Insert a org plantuml block activity if statement"
  ""
  "if \"\" then\n"
  "  -> [condition] ==IF" (setq ifn (bh/plantuml-if)) "==\n"
  "  --> ==IF" ifn "M1==\n"
  "  -left-> ==IF" ifn "M2==\n"
  "else\n"
  "end if\n"
  "--> ==IF" ifn "M2==")

(define-abbrev org-mode-abbrev-table "sif" "" 'skel-org-block-plantuml-activity-if)

(define-skeleton skel-org-block-plantuml-activity-for
  "Insert a org plantuml block activity for statement"
  "Loop for each: "
  "--> ==LOOP" (setq loopn (bh/plantuml-loop)) "==\n"
  "note left: Loop" loopn ": For each " str "\n"
  "--> ==ENDLOOP" loopn "==\n"
  "note left: Loop" loopn ": End for each " str "\n" )

(define-abbrev org-mode-abbrev-table "sfor" "" 'skel-org-block-plantuml-activity-for)

(define-skeleton skel-org-block-plantuml-sequence
  "Insert a org plantuml activity diagram block, querying for filename."
  "File appends (no extension): "
  "#+begin_src plantuml :file " str "-seq.png :cache yes :tangle " str "-seq.txt\n"
  "@startuml\n"
  "title " str " - \n"
  "actor CSR as \"Customer Service Representative\"\n"
  "participant CSMO as \"CSM Online\"\n"
  "participant CSMU as \"CSM Unix\"\n"
  "participant NRIS\n"
  "actor Customer"
  _ - \n
  "@enduml\n"
  "#+end_src\n")

(define-abbrev org-mode-abbrev-table "sseq" "" 'skel-org-block-plantuml-sequence)

;; sdot - Graphviz DOT block
(define-skeleton skel-org-block-dot
  "Insert a org graphviz dot block, querying for filename."
  "File (no extension): "
  "#+begin_src dot :file " str ".png :cache yes :cmdline -Kdot -Tpng\n"
  "graph G {\n"
  _ - \n
  "}\n"
  "#+end_src\n")

(define-abbrev org-mode-abbrev-table "sdot" "" 'skel-org-block-dot)

;; sditaa - Ditaa source block
(define-skeleton skel-org-block-ditaa
  "Insert a org ditaa block, querying for filename."
  "File (no extension): "
  "#+begin_src ditaa :file " str ".png :cache yes\n"
  _ - \n
  "#+end_src\n")

(define-abbrev org-mode-abbrev-table "sditaa" "" 'skel-org-block-ditaa)

;; selisp - Emacs Lisp source block
(define-skeleton skel-org-block-elisp
  "Insert a org emacs-lisp block"
  ""
  "#+begin_src emacs-lisp\n"
  _ - \n
  "#+end_src\n")

(define-abbrev org-mode-abbrev-table "selisp" "" 'skel-org-block-elisp)

yasnippet

[2017-05-28 Sun 22:00]

(require 'yasnippet)
(setq yas-indent-line 'none)
(setq yas-snippet-dirs
      '("~/.emacs.d/snippets"                 ;; personal snippets
        ;; "/path/to/some/collection/"           ;; foo-mode and bar-mode snippet collection
        ;; "/path/to/yasnippet/yasmate/snippets" ;; the yasmate collection
        ;; "/path/to/yasnippet/snippets"         ;; the default collection
        ))
(yas-global-mode 1)

Emacs Lisp (from Sacha Chua)

Eldoc

Eldoc provides minibuffer hints when working with Emacs Lisp.

(use-package "eldoc"
  :diminish eldoc-mode
  :commands turn-on-eldoc-mode
  :defer t
  :init
  (progn
  (add-hook 'emacs-lisp-mode-hook 'turn-on-eldoc-mode)
  (add-hook 'lisp-interaction-mode-hook 'turn-on-eldoc-mode)
  (add-hook 'ielm-mode-hook 'turn-on-eldoc-mode)))

Refactoring (disabled)

More things that I need to get used to…

;; #+begin_src emacs-lisp :tangle yes ;; C-c C-v l : elint current buffer in clean environment. ;; C-c C-v L : elint current buffer by multiple emacs binaries. ;; See `erefactor-lint-emacsen’ ;; C-c C-v r : Rename symbol in current buffer. ;; Resolve `let’ binding as long as i can. ;; C-c C-v R : Rename symbol in requiring modules and current buffer. ;; C-c C-v h : Highlight current symbol in this buffer ;; and suppress `erefacthr-highlight-mode’. ;; C-c C-v d : Dehighlight all by above command. ;; C-c C-v c : Switch prefix bunch of symbols. ;; ex: ‘(hoge-var hoge-func) -> ‘(foo-var foo-func) ;; C-c C-v ? : Display flymake elint warnings/errors

(use-package erefactor :config (define-key emacs-lisp-mode-map “\C-c\C-v” erefactor-map))

(use-package paredit) (use-package redshank :disabled t :defer t :init (add-hook ‘emacs-lisp-mode-hook ‘redshank-mode))

;; #+end_src

Jumping to code

(define-key emacs-lisp-mode-map (kbd "C-c .") 'find-function-at-point)
(bind-key "C-c f" 'find-function)

Sorting

  (defun my/sort-sexps-in-region (beg end)
    "Can be handy for sorting out duplicates.
Sorts the sexps from BEG to END. Leaves the point at where it
couldn't figure things out (ex: syntax errors)."
    (interactive "r")
    (let ((input (buffer-substring beg end))
          list last-point form result)
      (save-restriction
        (save-excursion
          (narrow-to-region beg end)
          (goto-char (point-min))
          (setq last-point (point-min))
          (setq form t)
          (while (and form (not (eobp)))
            (setq form (ignore-errors (read (current-buffer))))
            (when form
              (add-to-list
               'list
               (cons
                (prin1-to-string form)
                (buffer-substring last-point (point))))
              (setq last-point (point))))
          (setq list (sort list (lambda (a b) (string< (car a) (car b)))))
          (delete-region (point-min) (point))
          (insert (mapconcat 'cdr list "\n"))))))

Evaluation

Borrowed from Steve Purcell’s config. This pretty-prints the results.

;; disabled #+begin_src emacs-lisp (bind-key “M-:” ‘pp-eval-expression)

(defun sanityinc/eval-last-sexp-or-region (prefix) “Eval region from BEG to END if active, otherwise the last sexp.” (interactive “P”) (if (and (mark) (use-region-p)) (eval-region (min (point) (mark)) (max (point) (mark))) (pp-eval-last-sexp prefix) ;; (eval-last-sexp prefix) (other-window 1) (evil-motion-state) ;; (local-set-key (kbd “q”) ‘kill-this-buffer) (local-set-key (kbd “q”) ‘(lambda () (interactive)(kill-this-buffer)(other-window -1))) (local-set-key (kbd “SPC”) ‘(lambda () (interactive)(kill-this-buffer)(other-window -1))) (local-set-key (kbd “<escape>”) ‘(lambda () (interactive)(kill-this-buffer)(other-window -1))) ))

(bind-key “C-x C-e” ‘sanityinc/eval-last-sexp-or-region emacs-lisp-mode-map) ;; disabled #+end_src

web-mode

(web-mode-element-vanish) is an awesome command that removes the outer html element and keeps the inner one. Super awesome for html development.

;;;; web-mode: http://web-mode.org/
(use-package web-mode
  :bind (("C-c ]" . emmet-next-edit-point)
         ("C-c [" . emmet-prev-edit-point)
         ("C-c o b" . browse-url-of-file))
  :mode
  (("\\.js\\'" . web-mode)
   ("\\.html?\\'" . web-mode)
   ("\\.css\\'" . web-mode)
   ("\\.phtml?\\'" . web-mode)
   ("\\.tpl\\.php\\'" . web-mode)
   ("\\.[agj]sp\\'" . web-mode)
   ("\\.as[cp]x\\'" . web-mode)
   ("\\.erb\\'" . web-mode)
   ("\\.mustache\\'" . web-mode)
   ("\\.j2\\'" . web-mode)
   ("\\.djhtml\\'" . web-mode)
   ("\\.jsx$" . web-mode))
  :config


  (defun bss-web-mode-hook ()
    "Hooks for Web mode."
    (setq web-mode-enable-auto-closing t
          tab-width 4
          web-mode-enable-auto-pairing t ;; see FAQ at http://web-mode.org/ for smartparens
          web-mode-code-indent-offset 4

          web-mode-enable-current-element-highlight   t
          web-mode-enable-block-face                  t
          web-mode-markup-indent-offset               4   ;; HTML
          web-mode-css-indent-offset                  4   ;; CSS
          web-mode-code-indent-offset                 4   ;; JavaScript
          web-mode-enable-part-face                   t
          web-mode-enable-comment-keywords            t
          web-mode-enable-css-colorization            t
          ;; web-mode-enable-auto-pairing                nil
          web-mode-enable-current-column-highlight    t


          )
    )
  (add-hook 'web-mode-hook  'bss-web-mode-hook)

;; Surround with Tag from Howard Abrams

;;   Seems that even the SGML mode doesn't care about properly formatted
;;   HTML tags. This allows me to select a region and add wrap it in
;;   tag...properly.

  (defun surround-html (start end tag)
     "Wraps the specified region (or the current 'symbol / word'
   with a properly formatted HTML tag."
     (interactive "r\nsTag: " start end tag)
     (save-excursion
       (narrow-to-region start end)
       (goto-char (point-min))
       (insert (format "<%s>" tag))
       (goto-char (point-max))
       (insert (format "</%s>" tag))
       (widen)))

  ;; And bind it to the HTML hook:

(define-key web-mode-map (kbd "C-c C-w") 'surround-html)




  ;; ;; from FAQ at http://web-mode.org/ for smartparens
  ;; (defun my/web-mode-hook ()
  ;;   (setq web-mode-enable-auto-pairing nil))
  ;; (add-hook 'web-mode-hook 'my/web-mode-hook)

  ;; (defun sp-web-mode-is-code-context (id action context)
  ;;   (and (eq action 'insert)
  ;; 	 (not (or (get-text-property (point) 'part-side)
  ;; 		  (get-text-property (point) 'block-side)))))
  ;; (sp-local-pair 'web-mode "<" nil :when '(sp-web-mode-is-code-context))

  (add-hook 'web-mode-hook 'jsx-flycheck)
  (add-hook 'web-mode-hook (lambda () (electric-pair-mode -1)))

  ;; highlight enclosing tags of the element under cursor
  (setq web-mode-enable-current-element-highlight t)
  (evil-define-key 'normal web-mode-map (kbd "<tab>") 'web-mode-fold-or-unfold)

  (defadvice web-mode-highlight-part (around tweak-jsx activate)
    (if (equal web-mode-content-type "jsx")
        (let ((web-mode-enable-part-face nil))
          ad-do-it)
      ad-do-it))

  (defun jsx-flycheck ()
    (when (equal web-mode-content-type "jsx")
      ;; enable flycheck
      (flycheck-select-checker 'jsxhint-checker)
      (flycheck-mode)))

  ;; editing enhancements for web-mode
  ;; https://github.com/jtkDvlp/web-mode-edit-element
  (use-package web-mode-edit-element
    :config (add-hook 'web-mode-hook 'web-mode-edit-element-minor-mode))

  ;; snippets for HTML
  ;; https://github.com/smihica/emmet-mode
  (use-package emmet-mode
    :init (setq emmet-move-cursor-between-quotes t) ;; default nil
    :diminish (emmet-mode . " e"))
  (add-hook 'web-mode-hook 'emmet-mode)
  (add-hook 'sgml-mode-hook 'emmet-mode) ;; Auto-start on any markup modes
  (add-hook 'css-mode-hook  'emmet-mode) ;; enable Emmet's css abbreviation.

  (defun my-web-mode-hook ()
    "Hook for `web-mode' config for company-backends."
    (set (make-local-variable 'company-backends)
         '((company-tern company-css company-web-html company-files))))
  (add-hook 'web-mode-hook 'my-web-mode-hook)

  ;; Enable JavaScript completion between <script>...</script> etc.
  (defadvice company-tern (before web-mode-set-up-ac-sources activate)
    "Set `tern-mode' based on current language before running company-tern."
    (message "advice")
    (if (equal major-mode 'web-mode)
	(let ((web-mode-cur-language
	       (web-mode-language-at-pos)))
	  (if (or (string= web-mode-cur-language "javascript")
		  (string= web-mode-cur-language "jsx"))
	      (unless tern-mode (tern-mode))
	    (if tern-mode (tern-mode -1))))))
  (add-hook 'web-mode-hook 'company-mode)

  ;; to get completion data for angularJS
  (use-package ac-html-angular :defer t)
  ;; to get completion for twitter bootstrap
  (use-package ac-html-bootstrap :defer t)

  ;; to get completion for HTML stuff
  ;; https://github.com/osv/company-web
  (use-package company-web)
  (add-hook 'web-mode-hook 'company-mode)
  )

;; configure CSS mode company backends
(use-package css-mode
  :config
  (defun my-css-mode-hook ()
    (set (make-local-variable 'company-backends)
         '((company-css company-dabbrev-code company-files))))
  (add-hook 'css-mode-hook 'my-css-mode-hook)
  (add-hook 'css-mode-hook 'company-mode))

;; impatient mode - Live refresh of web pages
;; https://github.com/skeeto/impatient-mode
;; M-x httpd-start
;; select buffer and call M-x impatient-mode
;; go to browser: http://localhost:8080/imp/
(use-package impatient-mode
  :diminish (impatient-mode . " i")
  :commands (impatient-mode))

;; (use-package rainbow-mode
;;   :disabled t
;;   :ensure t
;;   :defer t
;;   :config
;;     (add-hook 'css-mode-hook (lambda () (rainbow-mode 1)))
;;     (add-hook 'html-mode-hook (lambda () (rainbow-mode 1)))
;;     )


;; (use-package palette
;;   :ensure t
;;   :defer t
;;   )

;;;; js2-mode
;; https://github.com/mooz/js2-mode
(use-package js2-mode
  :bind (:map js2-mode-map
              (("C-x C-e" . js-send-last-sexp)
               ("C-M-x" . js-send-last-sexp-and-go)
               ("C-c C-b" . js-send-buffer-and-go)
               ("C-c C-l" . js-load-file-and-go)))
  :mode
  ("\\.js$" . js2-mode)
  ("\\.json$" . js2-jsx-mode)
  :config
  (custom-set-variables '(js2-strict-inconsistent-return-warning nil))
  (custom-set-variables '(js2-strict-missing-semi-warning nil))

  (setq js-indent-level 2)
  (setq js2-indent-level 2)
  (setq js2-basic-offset 2)

  ;; tern :- IDE like features for javascript and completion
  ;; http://ternjs.net/doc/manual.html#emacs
  (use-package tern
    :config
    (defun my-js-mode-hook ()
      "Hook for `js-mode'."
      (set (make-local-variable 'company-backends)
           '((company-tern company-files))))
    (add-hook 'js2-mode-hook 'my-js-mode-hook)
    (add-hook 'js2-mode-hook 'company-mode))

  (add-hook 'js2-mode-hook 'tern-mode)

  ;; company backend for tern
  ;; http://ternjs.net/doc/manual.html#emacs
  (use-package company-tern)

  ;; Run a JavaScript interpreter in an inferior process window
  ;; https://github.com/redguardtoo/js-comint
  (use-package js-comint
    :config
    (setq inferior-js-program-command "node"))

  ;; js2-refactor :- refactoring options for emacs
  ;; https://github.com/magnars/js2-refactor.el
  (use-package js2-refactor :defer t
    :diminish js2-refactor-mode
    :config
    (js2r-add-keybindings-with-prefix "C-c j r"))
  (add-hook 'js2-mode-hook 'js2-refactor-mode))

Version Control

git-timemachine

;; git-timemachine

(use-package git-timemachine
  :ensure t
  :defer t
  :config
  ;; @see https://bitbucket.org/lyro/evil/issue/511/let-certain-minor-modes-key-bindings
  (eval-after-load 'git-timemachine
    '(progn
       (evil-make-overriding-map git-timemachine-mode-map 'normal)
       ;; force update evil keymaps after git-timemachine-mode loaded
       (add-hook 'git-timemachine-mode-hook #'evil-normalize-keymaps)))
  )

magit

;;;; magit
(use-package magit
  :config
  ;; (if (eq system-type 'windows-nt)
  ;; (progn
  ;; (setq magit-git-executable "C:/Program Files/Git/bin/git")
  ;; (setq exec-path (add-to-list 'exec-path "C:/Program Files/Git/bin"))
  ;; (setenv "PATH" (concat "C:\\Program Files\\Git\\bin;" (getenv "PATH")))
  ;; (add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)
  ;; Make sure that the bash executable can be found
  ;; (setq explicit-shell-file-name "C:/Program Files/Git/bin/bash.exe")
  ;; (setq shell-file-name explicit-shell-file-name)
  ;; ))

  :bind
  ("C-x g" . magit-status)
  ;; ("C-x g s" . magit-status)
  ;; ("C-x g x" . magit-checkout)
  ;; ("C-x g c" . magit-commit)
  ;; ("C-x g p" . magit-push)
  ;; ("C-x g u" . magit-pull)
  ;; ("C-x g e" . magit-ediff-resolve)
  ;; ("C-x g r" . magit-rebase-interactive)
  )


(use-package magit-popup)

Shell

;;;; shell settings
(setq eshell-visual-commands
    '("vim" "vi" "screen" "top" "less" "more" "lynx" "ncftp" "pine"
     "tin" "trn" "elm" "tmux" "nano" "mc" ("git" ("log" "diff" "show")) ))
(use-package eshell)
(require 'em-smart)
(setq eshell-where-to-jump 'begin)
(setq eshell-review-quick-commands nil)
(setq eshell-smart-space-goes-to-end t)
(setq comint-prompt-read-only t)
;; (setq comint-process-echoes t)

(use-package better-shell
  ;; https://github.com/killdash9/better-shell
    ;; :disabled
    :ensure t
    ;; :bind (("C-'" . better-shell-shell)
    ;;        ("C-;" . better-shell-remote-open)
    ;;        )
    )

;; ansi-term
(autoload 'ansi-color-for-comint-mode-on "ansi-color" nil t)
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)

;; term
(defface term-color-black
  '((t (:foreground "#3f3f3f" :background "#272822")))
  "Unhelpful docstring.")
(defface term-color-red
  '((t (:foreground "#cc9393" :background "#272822")))
  "Unhelpful docstring.")
(defface term-color-green
  '((t (:foreground "#7f9f7f" :background "#272822")))
  "Unhelpful docstring.")
(defface term-color-yellow
  '((t (:foreground "#f0dfaf" :background "#272822")))
  "Unhelpful docstring.")
(defface term-color-blue
  '((t (:foreground "#6d85ba" :background "#272822")))
  "Unhelpful docstring.")
(defface term-color-magenta
  '((t (:foreground "#dc8cc3" :background "#272822")))
  "Unhelpful docstring.")
(defface term-color-cyan
  '((t (:foreground "#93e0e3" :background "#272822")))
  "Unhelpful docstring.")
(defface term-color-white
  '((t (:foreground "#dcdccc" :background "#272822")))
  "Unhelpful docstring.")
'(term-default-fg-color ((t (:inherit term-color-white))))
'(term-default-bg-color ((t (:inherit term-color-black))))

;; ansi-term colors
(setq ansi-term-color-vector
  [term term-color-black term-color-red term-color-green term-color-yellow
    term-color-blue term-color-magenta term-color-cyan term-color-white])

;; shell: C-d on an empty line in the shell terminates the process.
(defun comint-delchar-or-eof-or-kill-buffer (arg)
  (interactive "p")
  (if (null (get-buffer-process (current-buffer)))
      (kill-buffer)
    (comint-delchar-or-maybe-eof arg)))

;; (add-hook 'shell-mode-hook (lambda () (define-key shell-mode-map (kbd "C-d") 'comint-delchar-or-eof-or-kill-buffer)))
;; (add-hook 'eshell-mode-hook (lambda () (define-key eshell-mode-map (kbd "C-d") 'comint-delchar-or-eof-or-kill-buffer)))

(eval-after-load 'comint
  '(progn
     (define-key shell-mode-map (kbd "C-d") 'comint-delchar-or-eof-or-kill-buffer)
     (define-key shell-mode-map (kbd "<up>") 'comint-previous-input)
     (define-key shell-mode-map (kbd "<down>") 'comint-next-input)
     )
  )


;; eshell marks http://mbork.pl/2017-03-04_Bookmarking_directories_in_Eshell
;; http://jeroenjanssens.com/2013/08/16/quickly-navigate-your-filesystem-from-the-command-line.html
(defun eshell/jump (mark)
  "Jump to a directory symlinked to by a file called ~/.marks/MARK."
  (eshell/cd (file-symlink-p (concat "~/.marks/" mark))))
(defun pcomplete/jump ()
  "Complete a command that wants a name of a file in ~/.marks."
  (pcomplete-here* (directory-files "~/.marks/")))

Sql mode

;;;; Sql mode
(use-package edbi)
;; https://github.com/kiwanami/emacs-edbi

(use-package edbi-sqlite)
;; https://github.com/proofit404/edbi-sqlite
;; Run edbi-sqlite interactive command. Select appropriate sqlite database file. Type RET and you'll be connected to specified database with edbi tool.

(use-package edbi-database-url)
;; https://github.com/proofit404/edbi-database-url
;; Specify database url with environment variable
;; M-x setenv RET DATABASE_URL RET pgsql://me:secret@localhost:5678/test
;; Connect to you database
;; M-x edbi-database-url
;; Optionally you can specify database url by marking region or type it interactively.

;; https://github.com/proofit404/edbi-minor-mode
(use-package edbi-minor-mode)
(add-hook 'sql-mode-hook 'edbi-minor-mode)
;; Connect to your database with edbi:open-db-viewer. Open regular SQL file. You can use following commands to perform SQL queries:
;; Keybinding	Description
;; C-c C-b	edbi-minor-mode-execute-buffer
;; C-c C-c	edbi-minor-mode-execute-paragraph
;; C-c C-r	edbi-minor-mode-execute-region
;; C-c C-s	edbi-minor-mode-execute

chronos

;;;; chronos plugin
(use-package chronos
  :config
  ;; (use-package chronos)
  ;; https://github.com/dxknight/chronos
  ;; now is 17:00
  ;; 5 gives an expiry time of 17:05
  ;; 1:30 gives 18:30
  ;; 0:0:30 gives 30 seconds after 17:00
  ;; empty or 0 gives a count up timer starting now, at 17:00.

  ;; =17:00/Drink coffee + -5/Brew coffee + -5/Boil kettle + 25/Finish break
  ;; Which will give a timer at 5 o'clock to drink coffee, a timer five minutes before that (16:55) to
  ;; start brewing the coffee, a reminder five minutes before that (16:50) to put the kettle on and a
  ;; reminder 25 minutes after that (17:15) to finish drinking coffee and get back to work.

  ;; Key	Action
  ;; a	add a timer by specifying expiry time and a message
  ;; A	add multiple consecutive timer(s) in one go
  ;; n/p	move selection down/up (also C-n/C-p <down>/<up>)
  ;; SPC	pause/unpause (pausing affects time to go and the expiry time, but not elapsed time)
  ;; d	delete selected timer
  ;; D	delete all expired timers
  ;; e	edit selected timer
  ;; l	lap selected timer
  ;; F	freeze/unfreeze the display
  ;; q	quit window



  (defun bss/chronos-shell-notify (c)
    "Notify expiration of timer C by running a shell command."

    (if (eq system-type 'darwin)
	(chronos--shell-command "Chronos shell notification for Mac OS X"
				"/usr/local/bin/terminal-notifier"
				(list "-sound" "default" "-title" "Сработал таймер" "-message" (chronos--message c))
				)
      (chronos--shell-command "Chronos shell notification for Linux & Windows"
			      "notify-send"
			      (list "-t" "3600000" "Сработал таймер" (chronos--message c))))
    ;; 24*60*60*1000 = 86400000  60*60*1000 = 3600000
    )

  (setq
   ;; chronos-shell-notify-program "mpg123"
   ;; chronos-shell-notify-parameters '("-q ~/.emacs.d/manual-addons/sounds/end.mp3")
   ;; chronos-shell-notify-program "notify-send"
   ;; chronos-shell-notify-parameters '("-t" "0" "Сработал таймер")
   chronos-notification-wav "~/.emacs.d/manual-addons/sounds/end.wav"
   chronos-expiry-functions '(chronos-buffer-notify
			      bss/chronos-shell-notify
			      ;; chronos-sound-notify
			      chronos-message-notify
			      ))
  (use-package helm-chronos)
  ;; hack for manual addons. helm updates?
  (setq helm-chronos--fallback-source
	(helm-build-dummy-source "test"
	  :action '(("Add timer" . helm-chronos--parse-string-and-add-timer))))

  (setq helm-chronos-standard-timers
	'( "    10/Каша"
	   "    25/Каша"
	   "     4/Soak noodles"
	   "    25/Pomodoro: Work on helm-chronos + 5/Pomodoro: Rest"))
  ;; (global-set-key (kbd "C-x t") 'helm-chronos-add-timer)
  (global-set-key (kbd "C-x t") '(lambda() (interactive)(helm-chronos-add-timer)(switch-to-buffer "*chronos*")))
  ;; (global-set-key (kbd "C-x t") 'chronos-add-timers-from-string)
  (global-set-key (kbd "C-x C-t") '(lambda() (interactive)(switch-to-buffer "*chronos*")))

  )

yaml-mode

;;;; Devops tunings
;; (use-package ansible)
;; (ansible::set-default-keymap)

(use-package yaml-mode
  :config
  (add-to-list 'auto-mode-alist '("\\.yml\\'" . yaml-mode))
  (add-hook 'yaml-mode-hook
            (lambda ()
              (setq evil-shift-width 2)
              ))
  )



;; Unlike python-mode, this mode follows the Emacs convention of not
;; binding the ENTER key to `newline-and-indent'.  To get this
;; behavior, add the key definition to `yaml-mode-hook':

;; (add-hook 'yaml-mode-hook
;;           '(lambda ()
;;              (define-key yaml-mode-map "\C-m" 'newline-and-indent)))

;;;; Hydra
;; https://github.com/abo-abo/hydra/
;; (require hydra)

;;https://gitlab.com/emacs-stuff/indent-tools/
(use-package indent-tools)
(add-hook 'python-mode-hook (lambda () (define-key python-mode-map (kbd "C-c i") 'indent-tools-hydra/body)))
(add-hook 'yaml-mode-hook (lambda () (define-key yaml-mode-map (kbd "C-c i") 'indent-tools-hydra/body)))

elfeed Rss reader

;; #+begin_src emacs-lisp ;; ;; elfeed https://github.com/skeeto/elfeed https://github.com/algernon/elfeed-goodies ;; (use-package elfeed) ;; (use-package elfeed-goodies) ;; ;; (elfeed-goodies/setup) ;; (global-set-key (kbd “C-x w”) ‘elfeed) ;; ;; (setq elfeed-feeds ;; ‘( ;; “http://www.3dnews.ru/news/main/rss” ;; “https://geektimes.ru/rss/hubs/all/” ;; “https://www.linux.org.ru/section-rss.jsp?section=2&amp;group=8404” ;; “https://www.reddit.com/r/emacs/.rss” ;; “http://www.cnews.ru/inc/rss/analytics.xml” ;; “http://www.cnews.ru/inc/rss/news.xml” ;; “https://news.google.ru/news?cf=all&amp;hl=ru&amp;pz=1&amp;ned=ru_ru&amp;output=rss” ;; “https://habrahabr.ru/rss/hubs/all/” ;; )) ;; ;; ;;http://www.3dnews.ru/community ;; ;; #+end_src

всякая мелочёвка

workspaces

;; M-n and M-p look for the symbol at point
;; (use-package smartscan)
;; (global-smartscan-mode t)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; : http://grapevine.net.au/~striggs/elisp/workspaces.el
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(use-package workspaces)
;;(define-key global-map (kbd "H-/") 'workspace-controller)
;;(global-set-key (kbd "<f1>") 'workspace-controller)
;; 'C-q' \0-9\ — переключает на нужный воркспейс.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; (use-package evil-escape)
;; (setq-default evil-escape-key-sequence "kj")
;; (setq-default evil-escape-delay 0.2)
;; (setq evil-escape-unordered-key-sequence' t)
;; (evil-escape-mode)

PCRE regexps

[2017-03-22 Wed 13:00]

https://github.com/joddie/pcre2el

(use-package pcre2el
   :diminish (pcre-mode . "")
   :config
   (pcre-mode t))

which-key (подсказки по клавишам)

;; (which-key-mode): https://github.com/justbur/emacs-which-key
(use-package which-key
  :config
  (which-key-mode)

  ;; hide from modeline
  (diminish 'which-key-mode)
  ;; Set the time delay (in seconds) for the which-key popup to appear.
  (setq which-key-idle-delay 1.0)
  )

перемещение строк и блоков текста по M-S-Arrows

(use-package drag-stuff)
;; (drag-stuff-mode t)
(add-to-list 'drag-stuff-except-modes 'org-mode )
(add-to-list 'drag-stuff-except-modes 'org-agenda-mode)
(drag-stuff-global-mode 1)
(diminish 'drag-stuff-mode)

ztree

;; ztree: https://github.com/fourier/ztree
;; provides ztree-diff and ztree-dir
(push (substitute-in-file-name "path-to-ztree-directory") load-path)
(use-package ztree)
(global-set-key (kbd "C-x z") 'ztree-dir)

shell scripts debug (disabled)

;; debugger
;; (use-package realgud)


uniquify

(use-package uniquify
:ensure nil
:config
(setq uniquify-buffer-name-style 'post-forward)
;; (setq uniquify-buffer-name-style 'post-forward-angle-brackets)
(setq uniquify-strip-common-suffix t)
)

ehelp (F1)

;; ehelp https://lists.gnu.org/archive/html/help-gnu-emacs/2007-10/msg00633.html
;; press "q" to exit from help window
(use-package ehelp)
(define-key global-map "\C-h" 'ehelp-command)
(define-key global-map [help] 'ehelp-command)
(define-key global-map [f1] 'ehelp-command)

expand region

;; expand-region: https://github.com/magnars/expand-region.el
(use-package expand-region)
(global-set-key (kbd "M-=") 'er/expand-region)
(global-set-key (kbd "M--") 'er/contract-region)

linum

(use-package nlinum)
(use-package nlinum-relative)
;; ace-jump-line mode respect ;; ;; (require 'linum-relative)
;; ace-jump-line mode respect ;; (add-hook 'prog-mode-hook 'nlinum-relative-mode)
;; (global-nlinum-relative-mode)

google translate

;; google translate
;; (require 'google-translate)
;; (require 'google-translate-default-ui)
;; (setq google-translate-default-source-language "en")
;; (setq google-translate-default-target-language "ru")
;; (global-set-key "\C-ct" 'google-translate-at-point)
;; (global-set-key "\C-cT" 'google-translate-query-translate)

powershell

 (use-package powershell)
 (define-key powershell-mode-map (kbd "M-`") 'other-frame)
 (define-key powershell-mode-map (kbd "<return>") 'newline-and-indent)

(define-skeleton skel-powershell-utf8-out
  "utf file coding string"
  "\n"
  "[Console]::OutputEncoding = [Text.UTF8Encoding]::UTF8\n"
  "[Threading.Thread]::CurrentThread.CurrentUICulture = 'en-us';\n"
)
(define-abbrev powershell-mode-abbrev-table "powerutf" "" 'skel-powershell-utf8-out)

writable grep

;; https://github.com/mhayashi1120/Emacs-wgrep
(use-package wgrep)

rainbow delimiters

;;coloring parenthesis
(use-package rainbow-delimiters
  :config
  (add-hook 'prog-mode-hook #'rainbow-delimiters-mode)

  (custom-set-faces
   '(rainbow-delimiters-depth-1-face ((t (:foreground "orange"))))
   '(rainbow-delimiters-depth-2-face ((t (:foreground "deep pink"))))
   '(rainbow-delimiters-depth-3-face ((t (:foreground "chartreuse"))))
   '(rainbow-delimiters-depth-4-face ((t (:foreground "deep sky blue"))))
   '(rainbow-delimiters-depth-5-face ((t (:foreground "yellow"))))
   '(rainbow-delimiters-depth-6-face ((t (:foreground "orchid"))))
   '(rainbow-delimiters-depth-7-face ((t (:foreground "spring green"))))
   '(rainbow-delimiters-depth-8-face ((t (:foreground "sienna1")))))

  )

common-lisp settings

;; Common Lisp and SLIME setup
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;------------------------
;; https://yoo2080.wordpress.com/2013/09/08/living-with-rainbow-delimiters-mode/
(use-package cl-lib)
(use-package color)
(cl-loop
 for index from 1 to rainbow-delimiters-max-face-count
 do
 (let ((face (intern (format "rainbow-delimiters-depth-%d-face" index))))
   (cl-callf color-saturate-name (face-foreground face) 30)))

(set-face-attribute 'rainbow-delimiters-unmatched-face nil
                    :foreground 'unspecified
                    :inherit 'error
                    :strike-through t)

;;------------------------
;; http://lisper.ru/forum/thread/114
(setq slime-net-coding-system 'utf-8-unix)
(if (eq system-type 'windows-nt) ;OR gnu/linux
	(setq inferior-lisp-program "c:/emacs/clisp-2.49/full/lisp.exe -B c:/emacs/clisp-2.49/full/ -M c:/emacs/clisp-2.49/full/lispinit.mem -ansi -q")
  (setq inferior-lisp-program "/usr/bin/clisp"))

;;(require 'slime)
;;(slime-setup '(slime-fancy))

;;;;(slime-setup '(slime-repl))

Winner mode - undo and redo window configuration

winner-mode lets you use C-c <left> and C-c <right> to switch between window configurations. This is handy when something has popped up a buffer that you want to look at briefly before returning to whatever you were working on. When you’re done, press C-c <left>.

(use-package winner
  :defer t)

ipcalc

(use-package ipcalc
  :ensure t
  ;; Call: (ipcalc "192.168.0.23/21")
  )

mu4e email client

;;;;----------------------------------------------------------
;;;; Mu4e Email client ----

(if (eq system-type 'gnu/linux) ;OR gnu/linux
	(progn
	  (add-to-list 'load-path "/usr/local/share/emacs/site-lisp/mu4e")
	  ;; (add-to-list 'load-path "~/.emacs.d/dotEmacs/mu4e")
	  (use-package mu4e)

	  ;; default
	  (setq mu4e-maildir "~/Maildir")
	  ;; (setq mu4e-drafts-folder "/[Gmail].Drafts")
	  ;; (setq mu4e-sent-folder   "/[Gmail].Sent Mail")
	  ;; (setq mu4e-trash-folder  "/[Gmail].Trash")
	  (setq mu4e-drafts-folder "/Черновики")
	  (setq mu4e-sent-folder   "/Отправленные")
	  (setq mu4e-trash-folder  "/Trash")

	  ;; don't save message to Sent Messages, Gmail/IMAP takes care of this
	  (setq mu4e-sent-messages-behavior 'delete)

	  ;; setup some handy shortcuts
	  ;; you can quickly switch to your Inbox -- press ``ji''
	  ;; then, when you want archive some messages, move them to
	  ;; the 'All Mail' folder by pressing ``ma''.

	  (setq mu4e-maildir-shortcuts
			'( ("/INBOX"               . ?i)))
	  ;; (setq mu4e-maildir-shortcuts
	  ;; 		'( ("/INBOX"               . ?i)
	  ;; 		   ("/[Gmail].Sent Mail"   . ?s)
	  ;; 		   ("/[Gmail].Trash"       . ?t)
	  ;; 		   ("/[Gmail].All Mail"    . ?a)))

	  ;; allow for updating mail using 'U' in the main view:
	  (setq mu4e-get-mail-command "offlineimap")

	  ;; (setq mu4e-html2text-command "html2text -utf8 -width 99999")
	  (setq mu4e-html2text-command
			"html2markdown | grep -v '&nbsp_place_holder;'")

	  ;; something about ourselves
	  (setq
	   user-mail-address "[email protected]"
	   user-full-name  "myusername sierra"
	   message-signature
	   (concat
		"WBR, Myusername"
		"\n"))

	  ;; sending mail -- replace USERNAME with your gmail username
	  ;; also, make sure the gnutls command line utils are installed
	  ;; package 'gnutls-bin' in Debian/Ubuntu

	  (use-package smtpmail)
	  ;; (setq message-send-mail-function 'smtpmail-send-it
	  ;;       starttls-use-gnutls t
	  ;;       smtpmail-starttls-credentials '(("smtp.gmail.com" 587 nil nil))
	  ;;       smtpmail-auth-credentials
	  ;;       '(("smtp.gmail.com" 587 "[email protected]" nil))
	  ;;       smtpmail-default-smtp-server "smtp.gmail.com"
	  ;;       smtpmail-smtp-server "smtp.gmail.com"
	  ;;       smtpmail-smtp-service 587)

	  ;; alternatively, for emacs-24 you can use:
	  (setq message-send-mail-function 'smtpmail-send-it
			smtpmail-stream-type 'starttls
			smtpmail-default-smtp-server "smtp.gmail.com"
			smtpmail-smtp-server "smtp.gmail.com"
			smtpmail-smtp-service 587)

	  ;; don't keep message buffers around
	  (setq message-kill-buffer-on-exit t)

 ;;; message view action
	  (defun mu4e-msgv-action-view-in-browser (msg)
		"View the body of the message in a web browser."
		(interactive)
		(let ((html (mu4e-msg-field (mu4e-message-at-point t) :body-html))
			  (tmpfile (format "%s/%d.html" temporary-file-directory (random))))
		  (unless html (error "No html part for this message"))
		  (with-temp-file tmpfile
			(insert
			 "<html>"
			 "<head><meta http-equiv=\"content-type\""
			 "content=\"text/html;charset=UTF-8\">"
			 html))
		  (browse-url (concat "file://" tmpfile))))
	  (add-to-list 'mu4e-view-actions
				   '("View in browser" . mu4e-msgv-action-view-in-browser) t)

	  ))
;;----------------------------------------------------------
;; ---- END Email client ----
;;----------------------------------------------------------

dash

[2017-04-19 Wed 16:54]

https://github.com/stanaka/dash-at-point#readme

;; (add-to-list 'load-path "/path/to/dash-at-point")
;; (autoload 'dash-at-point "dash-at-point"
;;          "Search the word at point with Dash." t nil)

(global-set-key "\C-cd" 'dash-at-point)
(global-set-key "\C-ce" 'dash-at-point-with-docset)

The Dash product is nice, and this project allows Emacs to open Dash for documentation of anything with a C-c d keystroke:

(use-package dash-at-point
  :ensure t
  :bind ("C-c d" . dash-at-point)
  :bind ("C-c e" . dash-at-point-with-docset)
  :config
  (add-to-list 'dash-at-point-mode-alist '(clojure-mode . "clojure"))
  (add-to-list 'dash-at-point-mode-alist '(ruby-mode . "ruby"))
  (add-to-list 'dash-at-point-mode-alist '(python-mode . "python2"))
  (add-to-list 'dash-at-point-mode-alist '(sh-mode . "bash"))
  (add-to-list 'dash-at-point-mode-alist '(emacs-lisp-mode . "elisp")))

ledger-mode

[2017-05-16 Tue 23:50]

https://github.com/ledger/ledger-mode

(autoload ‘ledger-mode “ledger-mode” “A major mode for Ledger” t) (add-to-list ‘load-path (expand-file-name “/usr/share/emacs/24.4/lisp/org/ob-ledger.elc”)) (add-to-list ‘auto-mode-alist ‘(“\.ledger$” . ledger-mode))

(use-package ledger-mode
  :defer t
  :ensure t
  :mode "\\.ledger$"
  :config
  (add-to-list 'evil-emacs-state-modes 'ledger-report-mode)
  (setq ledger-post-auto-adjust-amounts t
        ledger-schedule-file "~/notes/ledger/pending.ledger"
        ledger-post-amount-alignment-column 60
        ledger-highlight-xact-under-point nil
  )


  ;; Evil-mode bindings
  (define-key ledger-report-mode-map (kbd "C-u") 'scroll-down)
  (define-key ledger-report-mode-map (kbd "C-d") 'scroll-up)
  (define-key ledger-report-mode-map (kbd "h") 'backward-char)
  (define-key ledger-report-mode-map (kbd "j") 'evil-next-line)
  (define-key ledger-report-mode-map (kbd "k") 'evil-previous-line)
  (define-key ledger-report-mode-map (kbd "l") 'forward-char)

  ;; https://github.com/purcell/flycheck-ledger
  (eval-after-load 'flycheck
  '(require 'flycheck-ledger))


  ;; Highlight current line with underline
  (add-hook 'ledger-mode-hook
            (lambda ()
            (hl-line-mode 1)
            ;; (set-face-attribute hl-line-face nil :underline t)
            ;; (set-face-background 'highlight "#222")
            (set-face-background 'highlight nil)
            (set-face-foreground 'highlight nil)
            (set-face-underline-p 'highlight t)
            ))



;; (bss/ledger-schedule-upcoming "~/notes/ledger/pending.ledger" 10 20)
(defun bss/ledger-schedule-upcoming (file look-backward look-forward)
  "Generate upcoming transactions and return it as string value."
  (interactive)
  (if (and file (file-exists-p file))
      (progn
        ;; (ledger-schedule-create-auto-buffer (ledger-schedule-scan-transactions file) look-backward look-forward)
        (let ((candidates (ledger-schedule-list-upcoming-xacts (ledger-schedule-scan-transactions file) look-backward look-forward))
              (date-format (or (cdr (assoc "date-format" ledger-environment-alist))
                               ledger-default-date-format)))
          (setq mystr "")
          (dolist (candidate candidates)
            ;; (insert (format-time-string date-format (car candidate) ) " " (cadr candidate) "\n")
            (setq mystr (concat mystr (format-time-string date-format (car candidate) ) " " (cadr candidate) "\n"))
            )
          ;; (message mystr)
          (setq mystr mystr)
          )
        )
    (error "Could not find ledger schedule file at %s" file)))


(defun bss/ledger-planned-transactions-between-dates (file day1 day2)
  "show upcoming transactions between salary day and advance day for specified file"
  (interactive)
  (let (
        (salary-day (if (< day1 day2) day1 day2))
        (advance-day (if (< day1 day2) day2 day1))
        (current-year (nth 5 (decode-time (current-time))))
        (current-month (nth 4 (decode-time (current-time))))
        (current-day (nth 3 (decode-time (current-time))))
        ;; (current-year 2017) (current-month 1) (current-day 3)
        )
    (setq current-date-days (time-to-days (date-to-time (format "%s-%s-%s 0:00" current-year current-month current-day ))))
    (setq date1-days (time-to-days (date-to-time (format "%s-%s-%s 0:00" current-year current-month salary-day ))))
    (setq date2-days (time-to-days (date-to-time (format "%s-%s-%s 0:00" current-year current-month advance-day ))))

    (if (< current-day salary-day) ; мы в новом месяце до зарплаты
        (let ((prev-year current-year) (prev-month (+ current-month 1)) )
          (if (= current-month 1)
              (progn
                (setq prev-year (- current-year 1))
                (setq prev-month 12)
                ))
          (setq date1-days (time-to-days (date-to-time (format "%s-%s-%s 0:00" prev-year prev-month advance-day ))))
          (setq date2-days (time-to-days (date-to-time (format "%s-%s-%s 0:00" current-year current-month salary-day ))))
          ))

    (if (>= current-day advance-day) ; мы в месяце аванса после аванса
        (let ((next-year current-year) (next-month (+ current-month 1)) )
          (if (= current-month 12)
              (progn
                (setq next-year (+ current-year 1))
                (setq next-month 1)
                ))
          (setq date1-days (time-to-days (date-to-time (format "%s-%s-%s 0:00" current-year current-month advance-day ))))
          (setq date2-days (time-to-days (date-to-time (format "%s-%s-%s 0:00" next-year next-month salary-day ))))
          ))

    (setq forward-days (- date2-days current-date-days))
    (setq backward-days (- current-date-days date1-days))
    ;; (message "forward: %s, backward %s" forward-days backward-days)
    (bss/ledger-schedule-upcoming file backward-days forward-days)

    )
  )
; (bss/ledger-planned-transactions-between-dates "~/notes/ledger/pending.ledger" 10 25)


;;;; hack for windows ledger
;; (if (eq system-type 'windows-nt) ;OR gnu/linux
;;     (defun ledger-master-file ()
;;       "Return the master file for a ledger file.
;;
;;    The master file is either the file for the current ledger buffer or the
;;    file specified by the buffer-local variable `ledger-master-file'.  Typically
;;    this variable would be set in a file local variable comment block at the
;;    end of a ledger file which is included in some other file."
;;       (interactive)
;;       (if ledger-master-file
;;           ;; (expand-file-name ledger-master-file)
;;           (file-name-nondirectory (expand-file-name ledger-master-file))
;;         ;; (buffer-file-name)
;;         (file-name-nondirectory (expand-file-name (buffer-file-name)))
;;         )
;;       ))


;; (loop for (mode . state) in '((ledger-mode . emacs))
;;       do (evil-set-initial-state mode state))
;; (evil-set-initial-state 'ledger-mode 'emacs)
;; (evil-set-initial-state 'ledger-report-mode 'motion)

;; (push '("\\*CAPTURE-\\*" . insert) evil-buffer-regexps)



;; Yasnippet example
;; --------------------------------------------------
;; # -*- mode: snippet -*-
;; # name: оплата чего-то кредиткой
;; # key: опкред
;; # --
;; `(if evil-mode (evil-insert-state))`
;; `(format-time-string "%Y/%m/%d" (org-read-date nil t))` ${1:Продукты}
;;     долги:кредитка Сергей
;; 	расходы:$2  $0р
;;
;;
;; --------------------------------------------------


;; yas ;; ;; шаблоны операций
;; yas ;; (add-hook 'ledger-mode-hook (lambda () (abbrev-mode 1)))
;; yas ;;
;; yas ;; ;; шаблон операции покупки продуктов с оплатой картой
;; yas ;; (define-skeleton skel-ledger-card-groceries
;; yas ;;   "шаблон операции покупки продуктов с оплатой картой"
;; yas ;;   nil
;; yas ;;   (replace-regexp-in-string "-" "/" (org-read-date)) " * "\n
;; yas ;;   "\tактивы:Зарплатная карта\n"
;; yas ;;   "\tрасходы:продукты  "  _"р"
;; yas ;;   )
;; yas ;; (define-abbrev ledger-mode-abbrev-table "оппрод" "" 'skel-ledger-card-groceries)
;; yas ;;
;; yas ;; ;; шаблон операции покупки продуктов с оплатой картой и частичным уточнением
;; yas ;; (define-skeleton skel-ledger-card-lazy-groceries
;; yas ;;   "шаблон операции покупки продуктов с оплатой картой и частичным уточнением"
;; yas ;;   nil
;; yas ;;   (setq v1 (replace-regexp-in-string "-" "/" (org-read-date)))
;; yas ;;   " * Продукты"\n
;; yas ;;   "\tактивы:Зарплатная карта\n"
;; yas ;;   "\tрасходы:продукты  "_"р"
;; yas ;;   "\n\n"
;; yas ;;   v1 " * Уточнение категорий продуктов\n"
;; yas ;;   "\tрасходы:продукты\n"
;; yas ;;   "\tрасходы:продукты:  р"
;; yas ;;
;; yas ;;   )
;; yas ;; (define-abbrev ledger-mode-abbrev-table "опленьпрод" "" 'skel-ledger-card-lazy-groceries)
;; yas ;;
;; yas ;;
;; yas ;; ;; шаблон операции покупки чего-то наличкой
;; yas ;; (define-skeleton skel-ledger-cash
;; yas ;;   "шаблон операции покупки чего-то наличкой"
;; yas ;;   nil
;; yas ;;   (replace-regexp-in-string "-" "/" (org-read-date)) " * "\n
;; yas ;;   "\tактивы:наличные\n"
;; yas ;;   "\tрасходы:"_"  р"
;; yas ;;   )
;; yas ;; (define-abbrev ledger-mode-abbrev-table "опнал" "" 'skel-ledger-cash)
;; yas ;;
;; yas ;;
;; yas ;; ;; шаблон операции покупки чего-то кредиткой
;; yas ;; (define-skeleton skel-ledger-credit-card
;; yas ;;   "шаблон операции покупки чего-то кредиткой"
;; yas ;;   nil
;; yas ;;   (replace-regexp-in-string "-" "/" (org-read-date)) " * "\n
;; yas ;;   "\tдолги:кредитка Сергей\n"
;; yas ;;   "\tрасходы:"_"  р"
;; yas ;;   )
;; yas ;; (define-abbrev ledger-mode-abbrev-table "опкред" "" 'skel-ledger-credit-card)

)

вспомогательные функции

Красиво отформатировать выделенный json-фрагмент

(defun beautify-json ()
  "Use python to prettyprint JSON."
  (interactive)
  (let ((b (if mark-active (min (point) (mark)) (point-min)))
        (e (if mark-active (max (point) (mark)) (point-max))))
    (shell-command-on-region b e
                             "python -mjson.tool" (current-buffer) t)))

narrow-dwim

[2017-03-22 Wed 13:15]

http://endlessparentheses.com/emacs-narrow-or-widen-dwim.html

Another suggestion for dealing with org src blocks: add the following between the region-active check and the derived-mode-p check:

((org-src-edit-buffer-p) (org-edit-src-exit)) This makes the function symmetric with respect to entering and exiting org src blocks. Thus, more DWIM-my! ;)

(defun narrow-or-widen-dwim (p)
  "Widen if buffer is narrowed, narrow-dwim otherwise. Dwim means: region,
org-src-block, org-subtree, or defun, whichever applies first. Narrowing to
org-src-block actually calls `org-edit-src-code'.

With prefix P, don't widen, just narrow even if buffer is already narrowed."
  (interactive "P")
  (declare (interactive-only))
  (cond ((and (buffer-narrowed-p) (not p)) (widen))
        ((region-active-p)
         (narrow-to-region (region-beginning)
                           (region-end)))
        ((org-src-edit-buffer-p) (org-edit-src-exit))
        ((derived-mode-p 'org-mode)
         ;; `org-edit-src-code' is not a real narrowing
         ;; command. Remove this first conditional if
         ;; you don't want it.
         (cond ((ignore-errors (org-edit-src-code) t)
                (delete-other-windows))
               ((ignore-errors (org-narrow-to-block) t))
               (t (org-narrow-to-subtree))))
        ((derived-mode-p 'latex-mode)
         (LaTeX-narrow-to-environment))
        (t (narrow-to-defun))))

;; (define-key endless/toggle-map "n"
;;   #'narrow-or-widen-dwim)

;; This line actually replaces Emacs' entire narrowing
;; keymap, that's how much I like this command. Only
;; copy it if that's what you want.
(define-key ctl-x-map "n" #'narrow-or-widen-dwim)
(add-hook 'LaTeX-mode-hook
          (lambda ()
            (define-key LaTeX-mode-map "\C-xn"
              nil)))

DNS-mode: reload zone on server

If you edit zone files via TRAMP you might want to activate them via rndc reload. C-c C-r just does that for you.

(defun dns-rndc ()
  "Do rndc reload of current buffers filename."
  (interactive)
  (string-match "/\\([^/]*\\)$" buffer-file-name)
  (let* ((zonefile (match-string 1 buffer-file-name))
         )
    (if (y-or-n-p (format "rndc reload %s?" zonefile))
        (shell-command (concat "rndc reload " zonefile ) ) )
    )
  )

(add-hook 'dns-mode-hook
          (lambda ()
            (define-key dns-mode-map "\C-c\C-r" 'dns-rndc)
            ))

Number lines

[2017-10-03 Tue 13:25]

EmacsWiki: Number Lines

also remember about “C-x r N”

(eval-when-compile (require 'cl))
 (defun number-rectangle (start end format-string from)
   "Delete (don't save) text in the region-rectangle, then number it."
   (interactive
    (list (region-beginning) (region-end)
          (read-string "Number rectangle: " (if (looking-back "^ *") "%d. " "%d"))
          (read-number "From: " 1)))
   (save-excursion
     (goto-char start)
     (setq start (point-marker))
     (goto-char end)
     (setq end (point-marker))
     (delete-rectangle start end)
     (goto-char start)
     (loop with column = (current-column)
           while (<= (point) end)
           for i from from   do
           (insert (format format-string i))
           (forward-line 1)
           (move-to-column column)))
   (goto-char start))

copy filename to clipboard

;; Copy filename to clipboard
(defun copy-file-name-to-clipboard ()
  "Copy the current buffer file name to the clipboard."
  (interactive)
  (let ((filename (if (equal major-mode 'dired-mode)
                      default-directory
                    (buffer-file-name))))
    (when filename
      (kill-new filename)
      (message "Copied buffer file name '%s' to the clipboard." filename))))

svn-hook

(defun my-vc-dir-delete-marked-files ()
  "Delete all marked files in a `vc-dir' buffer."
  (interactive)
  (let ((files (vc-dir-marked-files)))
    (if (not files)
        (message "No marked files.")
      (when (yes-or-no-p (format "%s %d marked file(s)? "
                                 (if delete-by-moving-to-trash "Trash" "Delete")
                                 (length files)))
        (unwind-protect
            (mapcar
             (lambda (path)
               (if (and (file-directory-p path)
                        (not (file-symlink-p path)))
                   (when (or (not (directory-files
                                   path nil directory-files-no-dot-files-regexp))
                             (y-or-n-p
                              (format "Directory `%s' is not empty, really %s? "
                                      path (if delete-by-moving-to-trash
                                               "trash" "delete"))))
                     (delete-directory path t t))
                 (delete-file path t)))
             files)
          (revert-buffer))))))

(eval-after-load 'vc-dir
  '(define-key vc-dir-mode-map (kbd "k") 'my-vc-dir-delete-marked-files))

исправление ошибок набора

;; Thanks to Marcin Borkowski for this code snippet.
(defun smart-self-insert-punctuation (count)
  "If COUNT=1 and the point is after a space, insert the relevant
character before any spaces."
  (interactive "p")
  (if (and (= count 1)
           (eq (char-before) ?\s))
      (save-excursion
        (skip-chars-backward " ")
        (self-insert-command 1))
    (self-insert-command count)))

(global-set-key "," #'smart-self-insert-punctuation)

sudo edit

;; sudo edit current file: http://emacsredux.com/blog/2013/04/21/edit-files-as-root/
(defun sudo-edit (&optional arg)
  "Edit currently visited file as root.

With a prefix ARG prompt for a file to visit.
Will also prompt for a file to visit if current
buffer is not visiting a file."
  (interactive "P")
  (if (or arg (not buffer-file-name))
      (find-file (concat "/sudo:root@localhost:"
                         (ido-read-file-name "Find file(as root): ")))
    (find-alternate-file (concat "/sudo:root@localhost:" buffer-file-name))))

(global-set-key (kbd "C-x C-r") 'sudo-edit)

калькулятор

;; more in http://blog.jorgenschaefer.de/2012/03/emacs-snippets-calculation-helpers.html
(defun my-calc-result (beg end)
  (interactive "r")
  (insert " = " (calc-eval (buffer-substring beg end))))
;;(2+3+4)*2 = 18

;; https://www.reddit.com/r/emacs/comments/445w6s/whats_some_small_thing_in_your_dotemacs_that_you/
(defun my-calc-eval-region (arg)
  "Evaluate an expression in calc and communicate the result.

If the region is active evaluate that, otherwise search backwards to the first whitespace character
to find the beginning of the expression. By default, keep the expression and insert the result into
the buffer after it. If called with the universal prefix argument, replace the expression with its
value. If called with a negative prefix argument, just echo the result in the minibuffer.
"
  (interactive "p")
  (let (start end)
(if (use-region-p)
    (setq start (region-beginning) end (region-end))
  (progn
    (setq end (point))
    (setq start (search-backward-regexp "\\s-\\|\n" 0 1))
    (setq start (1+ (if start start 0)))
    (goto-char end)))
(let ((value (calc-eval (buffer-substring-no-properties start end))))
  (pcase arg
    (4 (delete-region start end))
    (1 (insert " = ")))
  (pcase arg
    ((or 1 4) (insert value))
    (-1 (message value))))))
(global-set-key (kbd "C-x =") 'my-calc-eval-region)

посмотрить метаинформацию о файле

(defun file-metadata ()
  (interactive)
  (let* ((fname (buffer-file-name))
         (data (file-attributes fname))
         (access (current-time-string (nth 4 data)))
         (mod (current-time-string (nth 5 data)))
         (change (current-time-string (nth 6 data)))
         (size (nth 7 data))
         (mode (nth 8 data)))
    (message
     "%s:
  Accessed: %s
  Modified: %s
  Changed: %s
  Size: %s bytes
  Mode: %s"
     fname access mod change size mode)))
(define-key global-map (kbd "M-g f") 'file-metadata)

Clean up spaces

(bind-key "s-SPC" 'cycle-spacing)

Shuffling lines

(defun my/shuffle-lines-in-region (beg end)
  (interactive "r")
  (let ((list (split-string (buffer-substring beg end) "[\r\n]+")))
    (delete-region beg end)
    (insert (mapconcat 'identity (shuffle-list list) "\n"))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment