emacs.el 164 KB
Newer Older
1
;;; .emacs --- Emacs init file  -*- lexical-binding: t; -*-
Juri Linkov's avatar
Juri Linkov committed
2

3
;; Copyright (C) 1989-2019  Juri Linkov <juri@linkov.net>
Juri Linkov's avatar
Juri Linkov committed
4

5
;; Author: Juri Linkov <juri@linkov.net>
Juri Linkov's avatar
Juri Linkov committed
6
;; Keywords: dotemacs, init
7
;; URL: <http://www.linkov.net/emacs>
8
;; Version: 2019-05-05 for GNU Emacs 27.0.50 (x86_64-pc-linux-gnu)
Juri Linkov's avatar
Juri Linkov committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; This file is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

;;; Commentary:

27 28 29
;;                                             "Show me your ~/.emacs
;;                                    and I will tell you who you are."
;;                                      -- old proverb modified by me
Juri Linkov's avatar
Juri Linkov committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49


;;; settings

;; Enable all disabled commands (eval-expression, narrow-to-..., etc.)
(setq disabled-command-function nil)

;; Get rid of all space-wasting garbage and minimize clutter
(and (fboundp 'menu-bar-mode)   (menu-bar-mode   -1))
(and (fboundp 'scroll-bar-mode) (scroll-bar-mode -1))
(and (fboundp 'tool-bar-mode)   (tool-bar-mode   -1))
(and (fboundp 'tooltip-mode) (fboundp 'x-show-tip) (tooltip-mode -1))

;; Blinking cursors are distracting - turn blink OFF
(and (fboundp 'blink-cursor-mode) (blink-cursor-mode (- (*) (*) (*))))

;; Use "y or n" for answers instead of complete words "yes or no"
(fset 'yes-or-no-p 'y-or-n-p)

;; If not on AC power line, then display battery status on the mode line
50 51 52 53 54 55 56
(defvar my-battery-timer nil)
(when (and (require 'battery nil t) (functionp battery-status-function))
  (when (and (boundp 'my-battery-timer) (timerp  my-battery-timer))
    (cancel-timer my-battery-timer))
  (setq my-battery-timer
        ;; Check periodically if went off-line and
        ;; discharging battery needs to be displayed
Juri Linkov's avatar
Juri Linkov committed
57 58 59 60 61
        (run-at-time t 600 (lambda ()
			     (display-battery-mode
			      (if (member (cdr (assoc ?L (funcall battery-status-function)))
					  '("AC" "on-line"))
				  0 1))))))
Juri Linkov's avatar
Juri Linkov committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89

;; Create display table to modify some display elements
(or standard-display-table (setq standard-display-table (make-display-table)))

;; Display page delimiter ^L as a horizontal line
(aset standard-display-table ?\^L (vconcat (make-vector 64 ?-) "^L"))

;; Display triangle for outline of invisible lines.
;; For information, see (info "(elisp) Display Table Format")
;; (from old code in faces.el in Emacs repo modified for Emacs 23)
(if (facep 'escape-glyph)
    (let* ((face (lsh (face-id 'escape-glyph) 22)) ;; 22 was 19 in Emacs 22
           (backslash (+ face ?\\))
           ;; TRIANGULAR BULLET keeps the default font height
           (dot (+ face #x2023)))
      ;; (aset standard-display-table 2208 (vector backslash ?\s)) ; no-break space
      ;; (aset standard-display-table 2221 (vector backslash ?-))  ; soft hyphen
      ;; (set-char-table-extra-slot standard-display-table 2 backslash) ; \364
      ;; (set-char-table-extra-slot standard-display-table 3 (+ face ?^)) ; ^@
      ;; (set-char-table-extra-slot standard-display-table 4 (vector dot dot dot))
      (set-char-table-extra-slot standard-display-table 4 (vector dot))))

;; Non-customizable variables
(setq gc-cons-percentage 0.3)
(setq print-gensym t)
(setq print-circle t)

;; Tabify only initial whitespace
90
(setq tabify-regexp "^\t* [ \t]+")
Juri Linkov's avatar
Juri Linkov committed
91 92 93

;; For a new non-file buffer set its major mode based on the buffer name.
;; http://thread.gmane.org/gmane.emacs.devel/115520/focus=115794
94 95
;; But this has problems, e.g. in autoinsert.el that uses
;; `(eq major-mode (default-value 'major-mode))'.
Juri Linkov's avatar
Juri Linkov committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
(setq-default major-mode (lambda ()
                           (if buffer-file-name
                               (fundamental-mode)
                             (let ((buffer-file-name (buffer-name)))
                               (set-auto-mode)))))


;;; frame

;; To use maximum screen space, my Emacs frame covers the entire screen
;; and has no menus, no toolbars, no scrollbars, no title and no borders.
;; Such customization on 1024x768 display mode and 6x10 font produces
;; Emacs text screen resolution 168 columns x 75 lines.
;; `split-window-horizontally' gives two windows with 83 columns x 75 lines.
;; And `follow-mode' displays one buffer with 83 columns x 150 lines.
Juri Linkov's avatar
Juri Linkov committed
111 112 113
;; On 1366x768 this gives 225 columns x 75 lines, this means either
;; 2 horizontally split windows each 112 columns wide, or
;; 3 horizontally split windows each 75 columns wide.
Juri Linkov's avatar
Juri Linkov committed
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

(cond
 ((eq window-system 'x)
  ;;(create-fontset-from-ascii-font "-rfx-fixed-medium-r-normal--10-*-*-*-c-60-koi8-*")
  (create-fontset-from-ascii-font "-misc-fixed-medium-r-*--10-*-*-*-*-*-*-*")
  (setq default-frame-alist
        (append
         '(
           ;;TRY: maximize instead of (width . 168)
           ;;TRY: maximize instead of (height . 77)
           ;; This is useful with the next code in the ~/.sawfish/rc,
           ;; because I can't find a way to unframe and maximize Emacs window from Emacs:
           ;; (require 'sawfish.wm.state.maximize)
           ;; (define (my-customize-emacs-window w)
           ;;   (when (string-match "emacs" (nth 2 (get-x-property w 'WM_CLASS)))
           ;;     (window-put w 'type 'unframed)
           ;;     (maximize-window w)))
           ;; (add-hook 'before-add-window-hook my-customize-emacs-window t)
           ;;(font . "-*-*-medium-r-normal--10-*-*-*-c-60-fontset-koi8_r_10")
           ;;? (font . "-rfx-fixed-medium-r-normal--10-*-*-*-c-60-koi8-*")
           ;;? (font . "-rfx-fixed-medium-r-normal--10-*-*-*-c-60-*-*")
           ;; (font . "-misc-fixed-medium-r-normal--10-100-75-75-c-60-iso10646-1")
           ;; (font . "-*-*-medium-r-*--10-*-*-*-*-*-fontset-iso8859_1_10")
Juri Linkov's avatar
Juri Linkov committed
137 138 139
           ;; (font . "-misc-fixed-medium-r-normal--10-*-*-*-c-60-iso8859-1")
           ;; Unlike iso8859-1, iso10646-* correctly combines accented chars
           (font . "-misc-fixed-medium-r-normal--10-*-*-*-c-60-iso10646-*")
Juri Linkov's avatar
Juri Linkov committed
140 141 142 143 144 145 146 147 148 149 150
           (cursor-type . bar)
           ;; To win a lot of screen pixels:
           (vertical-scroll-bars . nil)
           (horizontal-scroll-bars . nil)
           (scroll-bar-width . 0)
           (internal-border-width . 0)
           (menu-bar-lines . 0)
           (tool-bar-lines . 0)
           (line-spacing . 0))
         default-frame-alist))))

151 152 153 154 155 156

;;; tabs

(global-set-key [(control tab)]               'tab-next)
(global-set-key [(control shift iso-lefttab)] 'tab-previous)

Juri Linkov's avatar
Juri Linkov committed
157 158 159 160

;;; mouse

;; Move the mouse to the screen corner on any keypress.
161 162 163 164 165 166 167 168 169 170 171
;; This is commented out because now `mouse-avoidance-mode'
;; is customized to `banish' in `custom-set-variables':
;; (when (and (display-mouse-p) (require 'avoid nil t))
;;   ;; Move the mouse to the lower-right corner instead of default upper-right
;;   ;; (defun mouse-avoidance-banish-destination ()
;;   ;;   (cons (+ 3 (frame-width)) (- (frame-height) 1)))
;;   ;; The above is now customized for 24.2+ in `custom-set-variables' as:
;;   ;; (mouse-avoidance-banish-position
;;   ;;  '((frame-or-window . frame) (side . right) (side-pos . -3)
;;   ;;    (top-or-bottom . bottom) (top-or-bottom-pos . 1)))
;;   (mouse-avoidance-mode 'banish))
Juri Linkov's avatar
Juri Linkov committed
172 173 174

;; Show the text pointer in void text areas (no need any more)
;; (setq void-text-area-pointer nil)
175
;; (setq make-pointer-invisible t)
Juri Linkov's avatar
Juri Linkov committed
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193


;;; colors

(defun my-colors-light (&optional frame)
  "Set colors suitable for working in light environments,
i.e. in daylight or under bright electric lamps."
  (interactive)
  (setq frame-background-mode 'light)
  (if frame
      (select-frame frame)
    (setq frame (selected-frame)))
  ;; The color with minimal eye fatigue in light environments
  ;; is "AntiqueWhite3" (RGB: 205 192 176),
  ;; (set-background-color "AntiqueWhite3")
  (set-background-color "white")
  (set-foreground-color "black")
  (when (facep 'region)
194
    (set-face-background 'region "gray90" frame))
Juri Linkov's avatar
Juri Linkov committed
195 196 197 198 199
  (when (facep 'fringe)
    (set-face-background 'fringe (face-background 'default) frame)
    (set-face-foreground 'fringe (face-foreground 'default) frame))
  ;; When started Emacs under root, warn by red color in the modeline
  (when (and (facep 'mode-line)
200
             ;; Alternative condition is (= (user-uid) 0)
Juri Linkov's avatar
Juri Linkov committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
             (file-exists-p "/root")
             (file-writable-p "/root"))
    (set-face-background 'mode-line "firebrick")))

(define-key global-map [f6 ?c ?s] 'my-colors-light)

(defun my-colors-dark (&optional frame)
  "Set colors suitable for working in the darkness without electricity."
  (interactive)
  (setq frame-background-mode 'dark)
  (if frame
      (select-frame frame)
    (setq frame (selected-frame)))
  (set-background-color "black")
  (set-foreground-color "DarkGrey")
  (when (facep 'region)
    (set-face-background 'region "DimGray" frame))
  (when (facep 'fringe)
    (set-face-background 'fringe (face-background 'default) frame)
    (set-face-foreground 'fringe (face-foreground 'default) frame)))

(define-key global-map [f6 ?c ?d] 'my-colors-dark)
223
(define-key global-map [Multi_key] [t]) ; don't beep on accidental keypress
Juri Linkov's avatar
Juri Linkov committed
224

225 226 227
(defvar my-sunset-timer nil)
(defvar my-sunrise-timer nil)

Juri Linkov's avatar
Juri Linkov committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
;; Automatically switch to dark background after sunset
;; and to light background after sunrise.
;; (Note that `calendar-latitude' and `calendar-longitude'
;;  should be set before calling the `solar-sunrise-sunset')
(defun my-colors-set (&optional frame)
  (interactive)
  (require 'solar)
  (if (and calendar-latitude calendar-longitude calendar-time-zone)
      (let* ((l (solar-sunrise-sunset (calendar-current-date)))
             (sunrise-string (apply 'solar-time-string (car l)))
             (sunset-string (apply 'solar-time-string (car (cdr l))))
             (current-time-string (format-time-string "%H:%M")))
        (if (or (string-lessp current-time-string sunrise-string)
                (string-lessp sunset-string current-time-string))
            (my-colors-dark frame)
          (my-colors-light frame))
        (if (and (boundp 'my-sunset-timer)  (timerp my-sunset-timer))
            (cancel-timer my-sunset-timer))
        (if (and (boundp 'my-sunrise-timer) (timerp my-sunrise-timer))
            (cancel-timer my-sunrise-timer))
        (setq my-sunset-timer  (run-at-time sunset-string  (* 60 60 24)
                                            'my-colors-dark))
        (setq my-sunrise-timer (run-at-time sunrise-string (* 60 60 24)
                                            'my-colors-light)))))

;; (my-colors-set)
Juri Linkov's avatar
Juri Linkov committed
254
;; (add-hook 'after-make-frame-functions 'my-colors-set)
Juri Linkov's avatar
Juri Linkov committed
255

Juri Linkov's avatar
Juri Linkov committed
256 257 258
(add-hook 'after-make-frame-functions 'toggle-frame-maximized)
(add-hook 'after-make-frame-functions
          (lambda (frame)
259 260
            (modify-frame-parameters frame (list (cons 'background-color "white")))
            (set-frame-parameter frame 'undecorated t)
Juri Linkov's avatar
Juri Linkov committed
261 262
            ;; For some OS window managers that don't put focus to new frames:
            (select-frame-set-input-focus frame)))
263

264 265 266 267 268
(advice-add 'make-frame-on-monitor :around
	    (lambda (orig-fun monitor &optional display parameters)
	      (funcall orig-fun monitor display '((undecorated . t))))
	    '((name . make-frame-on-monitor-undecorated)))

269
;; qv "bug#31968: Allow to hide title bar on maximize (gtk/gnome/csd)"
Juri Linkov's avatar
Juri Linkov committed
270
(set-frame-parameter nil 'undecorated t)
271

Juri Linkov's avatar
Juri Linkov committed
272 273 274 275 276 277 278 279 280 281

;;; faces

(defun my-faces-fix (&optional frame)
  "Fix defined faces."
  (interactive)
  ;; Check if this function is called by `custom-define-hook' from
  ;; `custom-declare-face' where the variable `face' is bound locally.
  (when (boundp 'face)
    (dolist (face (face-list))
282

Juri Linkov's avatar
Juri Linkov committed
283
      ;; Make italic gray instead of black
284 285 286 287 288
      ;; (when (face-italic-p face frame)
      ;;   (if (equal (face-foreground face frame) "black")
      ;;       (set-face-foreground face "gray50" frame)))

      ;; My font makes bold text illegible,
Juri Linkov's avatar
Juri Linkov committed
289
      ;; so replace bold property with underline property
290 291 292 293 294
      ;; (when (face-bold-p face frame)
      ;;   (set-face-bold face nil frame)
      ;;   ;; (set-face-inverse-video face t frame)
      ;;   (set-face-underline face t frame))

Juri Linkov's avatar
Juri Linkov committed
295 296 297 298
      ;; Fonts with different height decrease the amount of lines
      ;; visible on screen, so remove the height property
      (when (numberp (face-attribute face :height frame))
        (set-face-attribute face frame :height 'unspecified))
299

Juri Linkov's avatar
Juri Linkov committed
300 301 302 303
      ;; Fonts with different width decrease the amount of characters
      ;; on the line, so remove the width property
      (when (numberp (face-attribute face :width frame))
        (set-face-attribute face frame :width 'unspecified))
304

Juri Linkov's avatar
Juri Linkov committed
305 306 307 308 309 310 311 312
      ;; Fonts with different weight decrease the height and width,
      ;; of the line, so remove the weight property
      ;; (when (numberp (face-attribute face :weight frame))
      ;;   (set-face-attribute face frame :weight 'unspecified))
      ;; (unless (string-match "^mode-line" (symbol-name face))
      ;;   ;; Reset all face attributes
      ;;   (modify-face face))
      )))
313

Juri Linkov's avatar
Juri Linkov committed
314 315
;; 1. Fix existing faces
;; (let ((face t)) (my-faces-fix))
316
;; (add-hook 'after-init-hook (lambda () (let (face) (my-faces-fix))) t)
Juri Linkov's avatar
Juri Linkov committed
317
;; 2. Call `my-faces-fix' every time some new face gets defined
Juri Linkov's avatar
Juri Linkov committed
318
(add-hook 'custom-define-hook 'my-faces-fix)
Juri Linkov's avatar
Juri Linkov committed
319 320 321 322 323 324


;;; keybindings

(define-key global-map [(control left)]       'backward-sexp)
(define-key global-map [(control right)]      'forward-sexp)
325 326
(define-key global-map [(control kp-left)]    'backward-sexp)
(define-key global-map [(control kp-right)]   'forward-sexp)
Juri Linkov's avatar
Juri Linkov committed
327 328
(define-key global-map [(control meta left)]  'left-word)
(define-key global-map [(control meta right)] 'right-word)
Juri Linkov's avatar
Juri Linkov committed
329 330 331 332 333 334 335 336 337

(define-key global-map [(control meta up)]    'backward-paragraph)
(define-key global-map [(control meta down)]  'forward-paragraph)

;; fix new controversial keybindings in Emacs 23
(define-key global-map [home] 'beginning-of-visual-line)
(define-key global-map [end]  'end-of-visual-line)
(define-key global-map [up]   'previous-line)
(define-key global-map [down] 'next-line)
338 339 340
;; This is BAD because C-n/C-p are useful in the multi-line minibuffer:
;; (define-key global-map "\C-p" 'previous-logical-line) ; previous-real-line
;; (define-key global-map "\C-n" 'next-logical-line)     ; next-real-line
Juri Linkov's avatar
Juri Linkov committed
341

342 343 344
(define-key global-map [(meta left)]
  (lambda ()
    (interactive)
345
    ;; TODO: also check in (wincows-states)
346 347 348 349 350 351 352 353
    (if (> (length (get-buffer-window-list (current-buffer) t t)) 1)
        (dired-jump)
      ;; Go to the top to not store emacs-places.
      (goto-char (point-min))
      (kill-current-buffer-and-dired-jump))))
(define-key global-map [(meta right)]         'my-find-thing-at-point)
;; Keybindings (meta up) (meta down) are free when windmove uses `super'.

Juri Linkov's avatar
Juri Linkov committed
354 355 356 357
;; Actually I don't use next two keybindings, use them for something useful
;; (define-key global-map [(control meta prior)] 'scroll-right)
;; (define-key global-map [(control meta next)]  'scroll-left)

358 359 360 361 362
(define-key global-map [(control down)] 'scroll-up-line)
(define-key global-map [(control up)] 'scroll-down-line)
(define-key global-map [(control kp-down)] 'scroll-up-line)
(define-key global-map [(control kp-up)] 'scroll-down-line)

Juri Linkov's avatar
Juri Linkov committed
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
;; (define-key global-map [(control return)]
;;   (lambda () (interactive) (let ((use-hard-newlines t)) (newline))))
;; (define-key global-map [(meta return)]
;;   (lambda () (interactive) (scroll-other-window 1))) ;; [(meta down)]
;; (define-key global-map [(meta backspace)]
;;   (lambda () (interactive) (scroll-other-window -1))) ;; [(meta up)]

(define-key global-map [(control backspace)] 'backward-kill-word)
;; (define-key global-map [(meta backspace)] 'undo)
;; (define-key global-map [(meta backspace)] 'backward-kill-word)
;; (define-key global-map [(control backspace)] 'join-lines)

(define-key global-map [(control ?=)] 'compare-windows)
;; alternative: (lambda () (interactive) (compare-windows t))

;; I often mistype `compare-windows' as `comapre-windows', allow both:
(defalias 'comapre-windows 'compare-windows)

(define-key global-map [(control kp-home)] 'beginning-of-buffer)
(define-key global-map [(control kp-end)]  'end-of-buffer)
(define-key global-map [(control shift kp-5)] 'goto-line)
(define-key global-map [(control kp-begin)] 'goto-line)

386 387 388 389 390
;; Use new dwim case commands
(define-key esc-map "u" 'upcase-dwim)
(define-key esc-map "l" 'downcase-dwim)
(define-key esc-map "c" 'capitalize-dwim)

Juri Linkov's avatar
Juri Linkov committed
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
;; These following two keybindings are standard default:
;; (define-key global-map [(meta /)] 'dabbrev-expand)
;; (define-key global-map [(control meta /)] 'dabbrev-completion)
(define-key global-map [(meta kp-divide)] 'hippie-expand)
;; The following key is not available:
;; (define-key global-map [(control meta kp-divide)] 'hippie-expand)

;; BAD key: (define-key global-map "\M-n" 'clone-buffer)
(define-key global-map [(control x) (c) (b)] 'clone-buffer)

(define-key ctl-x-map "\C-\M-u" 'raise-sexp)  ;; like `C-M-u'
(define-key ctl-x-map "\M-("    'delete-pair) ;; the reverse of `M-('

(define-key global-map [f1] 'info)
(define-key global-map [(control f1)] 'info-lookup-symbol)
(define-key global-map [f2] 'save-buffer)
407
;; (define-key global-map [f9] 'call-last-kbd-macro)
Juri Linkov's avatar
Juri Linkov committed
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
(define-key global-map [(control f9)] 'compile)
(define-key global-map [(meta f7)] 'grep) ; Commander-like
(define-key global-map [(meta shift f7)] 'grep-find)

(define-key goto-map "re" 'grep)
(define-key goto-map "rr" 'rgrep)
(define-key goto-map "rl" 'lgrep)
(define-key goto-map "\M-r\M-e" 'grep)
(define-key goto-map "\M-r\M-r" 'rgrep)
(define-key goto-map "\M-r\M-l" 'lgrep)

;; (define-key global-map [(control escape)]
;;   (lambda () (interactive) (buffer-menu 1))) ; not needed
;; (define-key global-map [(control escape)] 'ibuffer)
;; (define-key global-map [(shift f10)] 'buffer-menu) ; not needed

;; Like standard Emacs 22 commands (bound to C-x left/right)
(define-key global-map [f11] 'previous-buffer) ;; my-buffer-prev
(define-key global-map [f12] 'next-buffer)     ;; my-buffer-next

;; Like standard Emacs 22 commands (bound to M-g n/p)
(define-key global-map [(control f11)] 'previous-error)
(define-key global-map [(control f12)] 'next-error)
(define-key global-map [(control shift f11)] 'compilation-previous-file)
(define-key global-map [(control shift f12)] 'compilation-next-file)

(defvar my-next-error-prev-buffer nil)
(defun my-next-error ()
  ;; Get rid of file buffers visited during going through results.
  (when (and my-next-error-prev-buffer
             (not (eq my-next-error-prev-buffer (current-buffer)))
             ;; buffer not edited
             (memq buffer-undo-list '(nil t))
             ;; only on consequent keystrokes
             (memq this-command '(next-error previous-error))
             (eq (with-current-buffer next-error-last-buffer major-mode)
                 'grep-mode))
    ;; TODO: preserve existing file buffers, and positions in all file buffers
    ;; (goto-char (point-min)) ...
    (kill-buffer my-next-error-prev-buffer))
  (setq my-next-error-prev-buffer (current-buffer)))
(add-hook 'next-error-hook 'my-next-error)

451 452 453 454 455 456 457 458 459 460
;; See bug#20489: 25.0.50; next-error-find-buffer chooses non-current buffer without good reason
;; See bug#28864: 25.3.50; next-error-no-select does select
;; (setq next-error-find-buffer-function
;;       (lambda (&optional avoid-current extra-test-inclusive extra-test-exclusive)
;; 	(window-parameter nil 'next-error-buffer)))
;; (add-hook 'next-error-hook
;; 	  (lambda ()
;; 	    (set-window-parameter
;; 	     nil 'next-error-buffer next-error-last-buffer)))

Juri Linkov's avatar
Juri Linkov committed
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
;; TODO: currently key (control escape) is free, bind it to something useful,
;; unless it is used by the window manager

;; The following two corrections are for Scandinavian keyboard layouts.
;; Bind AltGr-space to the same command as is bound to Alt-space (M-SPC)
;; instead of inserting space-looking nobreak-space (nbsp, 0xa0, 0x8a0).
;; This is not necessary in Emacs 22 where nbsp has a special face.
;; (define-key global-map [?\xa0]  'just-one-space)
;; (define-key global-map [?\x8a0] 'just-one-space)

;; Swap currency sign with dollar sign, so dollar sign which is used more
;; often in programming languages could be typed more easily by pressing
;; shift-4 instead of AltGr-4.
;; (keyboard-translate ?\244 ?\$)
;; (keyboard-translate ?\$ ?\244)
;; Better to change this in .xmodmaprc for other applications too as:
;; keycode 13 = 4 dollar 4 dollar dollar cent

;; Map some diacritic characters (Ao, A", O") to arrow keys
;; which have the same layout as arrow pad keys on AltGr keyboards
;; This is experimental to make C-f/C-b/C-n/C-p like as easy as hjkl.
;; (define-key global-map [?\x8e5] 'previous-line) ; [up]
;; (define-key global-map [?\x8e4] 'next-line)
;; (define-key global-map [?\x8f6] 'backward-char)
;; (define-key global-map [?'] 'forward-char)

487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524

;;; copy-paste

(defvar kill-ring-save-set-region-p nil)

;; When M-w (kill-ring-save) is called without region, copy text at point.
(advice-add 'kill-ring-save :before
	    (lambda (&rest _args)
	      (interactive (lambda (spec)
			     (setq kill-ring-save-set-region-p nil)
			     (unless (use-region-p)
			       (let ((bounds (or (bounds-of-thing-at-point 'url)
						 (bounds-of-thing-at-point 'filename)
						 (bounds-of-thing-at-point 'symbol)
						 (bounds-of-thing-at-point 'sexp))))
				 (unless bounds
				   (signal 'mark-inactive nil))
				 (goto-char (car bounds))
				 (push-mark (cdr bounds) t t)
				 (setq kill-ring-save-set-region-p t)))
			     (advice-eval-interactive-spec spec))))
	    '((name . set-region-if-inactive)))

;; Indicate copied region, especially needed when
;; the region was activated by the advice above
(advice-add 'kill-ring-save :after
	    (lambda (&rest _args)
	      ;; When the region was set by the advice above,
	      ;; only then display its text.
	      (when kill-ring-save-set-region-p
		(let ((text (substring-no-properties (current-kill 0))))
		  (message "Copied text \"%s\""
			   (query-replace-descr ; don't show newlines literally
			    (if (> (length text) 64)
				(concat (substring text 0 64) "..." (substring text -16))
			      text))))))
	    '((name . indicate-copied-region)))

525
(defvar yank-from-kill-ring-history nil)
526 527
(defun yank-from-kill-ring (string)
  "Insert the kill-ring item selected from the minibuffer history.
528
Use minibuffer navigation and search commands to browse the kill-ring
529
in the minibuffer history before typing RET to insert the item."
530 531 532 533 534
  (interactive
   (list (let ((history-add-new-input nil)
	       ;; Remove keymaps from text properties of copied string,
	       ;; because typing RET in the minibuffer might call
	       ;; an irrelevant command from the map of copied string.
535 536 537 538 539 540 541 542
	       (yank-from-kill-ring-history
                (mapcar (lambda (h)
			  (remove-list-of-text-properties
			   0 (length h)
			   '(keymap local-map action mouse-action) h)
			  h)
			kill-ring)))
	   (read-string "Yank from kill-ring: " nil 'yank-from-kill-ring-history))))
543 544
  (setq yank-window-start (window-start))
  (push-mark)
545 546
  (insert-for-yank string))

547
(global-set-key "\M-\C-y" 'yank-from-kill-ring)
548 549

(when delete-selection-mode
550
  (put 'yank-from-kill-ring 'delete-selection t))
551

Juri Linkov's avatar
Juri Linkov committed
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608

;;; quail

;; The default key `C-\' is difficult to type on AltGr keyboards.
;; (global-set-key [(control ?+)] 'toggle-input-method)
;; (global-set-key [(control ?')] 'toggle-input-method)
;; (global-set-key [(meta return)] 'toggle-input-method)
;; (define-key isearch-mode-map [(meta return)] 'isearch-toggle-input-method)
;; added for capslock to ~/.xsession: echo "keycode 66 = Print" | xmodmap -
;; (global-set-key [print] 'toggle-input-method)
;; (define-key isearch-mode-map [print] 'isearch-toggle-input-method)
;; (define-key mule-keymap "\\" 'set-input-method)

;; TODO for Emacs23: if toggle-input-method is called on the active region
;; then convert region to other coding, this is very useful when the region
;; was typed with a wrong input method, when the user forgot to toggle it


;;; mule

;; Delete codings like `utf-*-with-signature' (they hide BOMs)
;; to allow to always display the BOM (Byte-order mark signature)
;; to be able to remove it without the need to visit files literally
;; or with `C-x RET c utf-8 RET C-x C-f'.
;; SEE ALSO http://thread.gmane.org/gmane.emacs.devel/116668/focus=116738

(setq auto-coding-regexp-alist
      (delete (rassoc 'utf-16be-with-signature auto-coding-regexp-alist)
      (delete (rassoc 'utf-16le-with-signature auto-coding-regexp-alist)
      (delete (rassoc 'utf-8-with-signature auto-coding-regexp-alist)
              auto-coding-regexp-alist))))


;;; C-z my-map

;; Make the prefix key `C-z' for my personal keymap.
;; On qwerty-keyboards `C-z' is one of the most accessible keys
;; like `C-x' and `C-c', but the prefix key `C-c' is reserved
;; for mode-specific commands (both user-defined and standard Emacs extensions).
;; The standard binding of `C-z' (`suspend-emacs' or `iconify-or-deiconify-frame')
;; is reassigned here to double key sequence `C-z C-z'.
(defvar my-map
  (let ((map (make-sparse-keymap))
        (c-z (global-key-binding "\C-z")))
    (global-unset-key "\C-z")
    (define-key global-map "\C-z" map)
    (define-key map "\C-z" c-z)
    map))

;; my map can be used from isearch
;; (define-key isearch-mode-map "\C-z" my-map)
;; (define-key isearch-mode-map "\C-z" 'isearch-other-control-char)

(when window-system
  ;; Use single escape keypress instead of knocking it 3 times.
  ;; On a window system there is no need to use ESC as a prefix key.
  (define-key global-map [escape] 'keyboard-escape-quit)
609
  (define-key isearch-mode-map  [escape] 'isearch-cancel)
Juri Linkov's avatar
Juri Linkov committed
610 611 612 613 614 615 616

  ;; Set ESC-modifier to C-z escape
  ;; This is useful to invoke `M-TAB' or `M-|' on keyboards with AltGr key,
  ;; as `C-z ESC TAB' or `C-z ESC |'
  (define-key my-map [escape] esc-map)

  (define-key my-map "t" 'toggle-truncate-lines)
617 618 619 620
  (define-key my-map "v" nil)
  (define-key my-map "vs" 'set-variable)
  (define-key my-map "vc" 'customize-variable)
  (define-key my-map "vtw2" (lambda () (interactive) (setq-local tab-width 2) (force-mode-line-update)))
Juri Linkov's avatar
Juri Linkov committed
621
  (define-key my-map "r" 'revert-buffer)
622 623 624 625
  (define-key my-map "\C-q" 'quoted-insert) ; because global C-q is rebound above
  ;; `C-z -' and `C-z C--' inserts a vertical line.
  (define-key my-map [(control ?-)] (lambda () (interactive) (insert "\f\n"))) ; because global C-q C-l is rebound above
  (define-key my-map "-" (lambda () (interactive) (insert "\f\n"))) ; because global C-q C-l is rebound above
Juri Linkov's avatar
Juri Linkov committed
626 627 628 629
  (define-key my-map "p" (lambda () (interactive) (my-shell-command "perl test.pl")))
  ;; TEST: try `C-z C-x C-x C-x C-x ...', try `C-x z C-z C-z C-z' (repeat.el)
  )

630
;; Modify esc-map when not on a tty
Juri Linkov's avatar
Juri Linkov committed
631
(when window-system
Juri Linkov's avatar
Juri Linkov committed
632
  ;; Insert paired characters (either ''/"" or ‘’/“” depending on mode)
633 634 635 636 637 638 639 640
  (define-key esc-map "\""
    (lambda ()
      (interactive)
      (let ((insert-pair-alist
             (cons
              (if (and (memq buffer-file-coding-system '(utf-8-unix utf-8-emacs-unix))
                       (or (and comment-start (nth 4 (syntax-ppss)))
                           (and (derived-mode-p 'text-mode)
641
                                (not (derived-mode-p 'org-mode))
642 643
                                (not (derived-mode-p 'sgml-mode))
                                (not (derived-mode-p 'vc-git-log-edit-mode))
644
                                (not (derived-mode-p 'yaml-mode))
645 646 647 648 649 650 651
                                )
                           ;; (derived-mode-p 'fundamental-mode)
                           ))
                  '(?\" ?\“ ?\”)
                '(?\" ?\" ?\"))
              insert-pair-alist)))
        (call-interactively 'insert-pair))))
Juri Linkov's avatar
Juri Linkov committed
652 653
  ;; (define-key esc-map "`"  'insert-pair)
  ;; (define-key global-map "\M-`" 'insert-pair)
654 655 656 657 658 659 660 661
  (define-key esc-map "'"
    (lambda ()
      (interactive)
      (let ((insert-pair-alist
             (cons
              (if (and (memq buffer-file-coding-system '(utf-8-unix utf-8-emacs-unix))
                       (or (and comment-start (nth 4 (syntax-ppss)))
                           (and (derived-mode-p 'text-mode)
662
                                (not (derived-mode-p 'org-mode))
663 664
                                (not (derived-mode-p 'sgml-mode))
                                (not (derived-mode-p 'vc-git-log-edit-mode))
665
                                (not (derived-mode-p 'yaml-mode))
666 667 668 669 670 671 672 673 674
                                )
                           ;; (derived-mode-p 'fundamental-mode)
                           ))
                  '(?\' ?\‘ ?\’)
                '(?\' ?\' ?\'))
              insert-pair-alist)))
        (call-interactively 'insert-pair))))
  ;; Optionally, make ' insert backquote `'.
  ;; (add-to-list 'insert-pair-alist '(?\' ?\` ?\'))
Juri Linkov's avatar
Juri Linkov committed
675 676
  (define-key esc-map "["  'insert-pair)
  (define-key esc-map "{"  'insert-pair)
677
  (define-key esc-map ")"  'up-list))
Juri Linkov's avatar
Juri Linkov committed
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692

(define-key my-map  "`"  'insert-pair)
(define-key my-map  "<"  'insert-pair)

;; (defun insert-pair-without-space ()
;;   (interactive)
;;   (let ((parens-require-spaces nil))
;;     (call-interactively 'insert-pair)))
;; (defun insert-pair-with-space ()
;;   (interactive)
;;   (let ((parens-require-spaces t))
;;     (call-interactively 'insert-pair)))
;; (define-key esc-map "[" 'insert-pair-without-space)
;; (define-key esc-map "(" 'insert-pair-with-space)

Juri Linkov's avatar
Juri Linkov committed
693 694 695 696 697

;;; advices

;; Allow set-variable to set internal variables, not only customizable ones:
(advice-add 'set-variable :around
Juri Linkov's avatar
Juri Linkov committed
698
	    (lambda (orig-fun &rest args)
Juri Linkov's avatar
Juri Linkov committed
699
	      (interactive (lambda (spec)
700 701 702 703 704
			     (cl-letf (((symbol-function 'custom-variable-p)
                                        (lambda (v)
                                          (and (symbolp v) (boundp v)))))
                               (advice-eval-interactive-spec spec))))
	      (cl-flet ((custom-variable-p (v) t))
Juri Linkov's avatar
Juri Linkov committed
705 706
		(apply orig-fun args)))
	    '((name . override-custom-variable)))
Juri Linkov's avatar
Juri Linkov committed
707

Juri Linkov's avatar
Juri Linkov committed
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754

;;; functions

(defun my-find-thing-at-point ()
  "Find variable, function or file at point."
  (interactive)
  (cond ((not (eq (variable-at-point) 0))
         (call-interactively 'describe-variable))
        ((function-called-at-point)
         (call-interactively 'describe-function))
        (t (find-file-at-point))))

(defun my-next-link-or-scroll-page-forward (next-point)
  "Scroll one screen forward when no more next links are visible on the screen.
The argument `next-point' is the point's position of the next link."
  (if (and (> (window-end) next-point) (> next-point (point)))
      (goto-char next-point)
    (if (>= (window-end) (point-max))
        (goto-char (point-max))
      (progn (View-scroll-page-forward-set-page-size) (move-to-window-line 0)))))

(defun my-prev-link-or-scroll-page-backward (prev-point)
  "Scroll one screen backward when no more previous links are visible on the screen.
The argument `prev-point' is the point's position of the previous link."
  (if (and (< (window-start) prev-point) (< prev-point (point)))
      (goto-char prev-point)
    (if (<= (window-start) (point-min))
        (goto-char (point-min))
      (progn (View-scroll-page-backward-set-page-size)))))

(defvar my-scroll-auto-timer nil)
(defun my-scroll-auto (arg)
  "Scroll text of current window automatically with a given frequency.
With a numeric prefix ARG, use its value as frequency in seconds.
With C-u, C-0 or M-0, cancel the timer."
  (interactive
   (list (progn
           (if (and (boundp 'my-scroll-auto-timer)
                    (timerp  my-scroll-auto-timer))
               (cancel-timer my-scroll-auto-timer))
           (or current-prefix-arg
               (read-from-minibuffer
                "Enter scroll frequency measured in seconds (0 or RET for cancel): "
                nil nil t nil "0")))))
  (if (not (or (eq arg 0) (equal arg '(4))))
      (setq my-scroll-auto-timer (run-at-time t arg 'scroll-up 1))))

755
;; (define-key my-map "s" 'my-scroll-auto)
Juri Linkov's avatar
Juri Linkov committed
756

757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794

;;; cursor

;; USE (setq-default cursor-type ...) INSTEAD OF THE NEXT FUNCTION
;; (defun set-cursor-type (cursor-type)
;;   "Set the text cursor type of the selected frame to CURSOR-TYPE.
;; When called interactively, prompt for the name of the type to use.
;; To get the frame's current cursor type, use `frame-parameters'."
;;   ;; see `fringe-query-style'
;;   (interactive (list (intern (completing-read
;;                            "Cursor type: "
;;                            '("box" "hollow" "bar" "hbar" nil)))))
;;   (modify-frame-parameters (selected-frame)
;;                         (list (cons 'cursor-type cursor-type))))

;; Currently cursor color is frame-local, but should be buffer-local like
;; cursor-type (or maybe even window-local).
;; Also background color should be buffer-local
;; (maybe this is already fixed in the tiled-background branch?).

;; (defadvice toggle-input-method (after my-toggle-input-method activate)
;;   (if current-input-method
;;       (set-cursor-color "red") ; "AntiqueWhite4"
;;     (set-cursor-color "black")))

;; Use box cursor for overwrite-mode, and red cursor for quail active input.
(defun my-change-cursor ()
  "Change cursor color and type depending on insertion mode and input method."
  (set-cursor-color
   (cond (current-input-method "red3") ; "AntiqueWhite4"
         ((eq (frame-parameter (selected-frame) 'background-mode) 'dark)
                               "DarkGrey")
         (t                    "black")))
  (setq-default cursor-type
   (cond (overwrite-mode       'box)
         (t                    'bar))))
(add-hook 'post-command-hook 'my-change-cursor)

Juri Linkov's avatar
Juri Linkov committed
795 796 797

;;; window

798 799 800 801
(winner-mode)

(windmove-default-keybindings 'super)
(windmove-display-default-keybindings '(super meta))
802
(windmove-delete-default-keybindings nil 'super)
803
(windmove-swap-states-default-keybindings '(shift super)) ; like 15 puzzle
804

805 806 807
;; Prev version posted to emacs-devel Subject: Re: Include buffer-move.el
;; https://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00685.html
;; Maybe add recipe to http://www.emacswiki.org/cgi-bin/wiki/TransposeWindows
808
;; Now I use the standard command `window-swap-states' instead of this.
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
;; (defun rotate-window-buffers (&optional n)
;;   "Exchange buffers in all windows N times.
;; With positive N, it uses the window order of `window-list'.
;; With negative N, does this in the reverse order."
;;   (interactive "p")
;;   (let* ((ws (window-list))
;;          (ls (mapcar (lambda (w)
;;                        (list (window-buffer w)
;;                              (window-point w)
;;                              (window-next-buffers w)
;;                              (window-prev-buffers w)))
;;                      ws))
;;          (n  (mod (or n 1) (length ws))))
;;     (dolist (w (append (last ws n) (butlast ws n)))
;;       (let ((l (pop ls)))
;;         (set-window-buffer w (nth 0 l))
;;         (set-window-point  w (nth 1 l))
;;         (set-window-next-buffers w (nth 2 l))
;;         (set-window-prev-buffers w (nth 3 l))))))
828

Juri Linkov's avatar
Juri Linkov committed
829 830 831 832 833 834
(defun my-move-to-window-top (&optional arg)
  "Position point to the top line of the window."
  (interactive)
  (move-to-window-line 0))

(define-key global-map [(control prior)] 'my-move-to-window-top)
835
(define-key global-map [(control kp-prior)] 'my-move-to-window-top)
Juri Linkov's avatar
Juri Linkov committed
836 837 838 839 840 841 842

(defun my-move-to-window-bottom (&optional arg)
  "Position point to the bottom line of the window."
  (interactive)
  (move-to-window-line -1))

(define-key global-map [(control next)]  'my-move-to-window-bottom)
843
(define-key global-map [(control kp-next)]  'my-move-to-window-bottom)
Juri Linkov's avatar
Juri Linkov committed
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886

(defun my-windows-balance ()
  (interactive)
  (other-window 1)
  (balance-windows)
  (shrink-window-if-larger-than-buffer)
  (other-window -1))

(define-key my-map "wb" 'my-windows-balance)

;; [2009-11-29] TRY TO USE `recenter-top-bottom' instead of this:
;; (defvar my-recenter-line 15)
;; (defun my-recenter (&optional arg)
;;   "Places point in window on eyes level."
;;   (interactive "P")
;;   (if (equal arg '(16))
;;       (setq my-recenter-line (count-screen-lines
;;                               (window-start)
;;                               (save-excursion (beginning-of-line) (point)))
;;             arg nil
;;             recenter-position (/ (float my-recenter-line)
;;                                  (count-screen-lines
;;                                   (window-start) (window-end)))))
;;   (if arg (recenter arg) (recenter my-recenter-line)))
;; (put 'my-recenter 'isearch-scroll t)
;;
;; (define-key my-map "\C-l" 'my-recenter)
;; (define-key global-map "\C-l" 'my-recenter)

;; [2009-11-29] TRY TO USE `move-to-window-line-top-bottom' instead of this:
;; (defun my-move-to-window-line (&optional arg)
;;   "Places point in window on eyes level."
;;   (interactive "P")
;;   (if (equal arg '(16))
;;       (setq my-recenter-line (count-screen-lines
;;                               (window-start)
;;                               (save-excursion (beginning-of-line) (point)))
;;             arg nil))
;;   (if arg (move-to-window-line arg) (move-to-window-line my-recenter-line)))
;;
;; (define-key my-map "\M-r" 'my-move-to-window-line)
;; (define-key global-map "\M-r" 'my-move-to-window-line)

887 888
(when (boundp 'recenter-positions)
  (setq recenter-position (car recenter-positions)))
Juri Linkov's avatar
Juri Linkov committed
889

890 891 892 893 894 895
;; Instead of the default hook that recenters to the middle of the screen,
;; add hooks that recenter to the middle of the top half of the screen
(defun recenter-top ()
  (interactive)
  (recenter (round (* recenter-position (window-height)))))

896 897 898
(add-hook 'xref-after-jump-hook 'reposition-window)
(add-hook 'xref-after-return-hook 'reposition-window)
(add-hook 'find-function-after-hook 'reposition-window)
899

900 901
;; Let `C-M-a' (beginning-of-defun) not scroll the window
;; when after jump point stays within current window bounds
902 903 904 905 906 907 908 909 910 911 912 913 914 915
(advice-add 'beginning-of-defun :around
	    (lambda (orig-fun &rest args)
	      (let ((w-s (window-start))
		    (w-e (window-end)))
		(apply orig-fun args)
		(when (and
		       ;; Only when used interactively
		       (eq this-command 'beginning-of-defun)
		       ;; And only when jumping outside of window
		       ;; to the center of the window
		       (or (< (point) w-s) (> (point) w-e)))
		  (recenter-top))))
	    '((name . recenter-top)))

Juri Linkov's avatar
Juri Linkov committed
916 917 918 919 920 921 922 923
;; OLD: (setq split-window-preferred-function 'split-window-preferred-horizontally)
;; (defadvice split-window-preferred-horizontally
;;            (around my-split-window-preferred-horizontally act)
;;   (let ((window ad-do-it))
;;     (if (string-match "\\*Help\\*\\(\\|<[0-9]+>\\)" (buffer-name (car (buffer-list))))
;;         (selected-window)
;;       window)))

924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
(defun split-window-horizontally-3 ()
  (interactive)
  (delete-other-windows)
  (split-window-horizontally)
  (split-window-horizontally)
  (balance-windows)
  (other-window -1))

(defun follow-mode-3 ()
  (interactive)
  (split-window-horizontally-3)
  (follow-mode 1)
  (goto-char (point-min)))

(define-key my-map "3" 'split-window-horizontally-3)
(define-key my-map "f3" 'follow-mode-3)

(defun split-window-horizontally-4 ()
  (interactive)
  (delete-other-windows)
  (split-window-horizontally)
  (split-window-horizontally)
  (other-window 2)
  (split-window-horizontally)
  (other-window 2))

(defun follow-mode-4 ()
  (interactive)
  (split-window-horizontally-4)
  (follow-mode 1)
  (goto-char (point-min)))

(define-key my-map "4" 'split-window-horizontally-4)
(define-key my-map "f4" 'follow-mode-4)

959 960 961 962 963 964 965 966

;;; mark-active-window

;; Make mark buffer-and-window-local
;; Posted to https://lists.gnu.org/archive/html/emacs-devel/2018-09/msg00716.html

(defvar-local mark-active-window nil)

Juri Linkov's avatar
Juri Linkov committed
967
;; (add-hook 'activate-mark-hook (lambda () (setq mark-active-window (selected-window))))
Juri Linkov's avatar
Juri Linkov committed
968 969
(advice-add 'activate-mark :after
	    (lambda (&rest _args)
Juri Linkov's avatar
Juri Linkov committed
970 971
	      (setq mark-active-window (selected-window)))
	    '((name . mark-active-window)))
Juri Linkov's avatar
Juri Linkov committed
972 973 974 975 976 977 978 979 980

;; Can't use deactivate-mark-hook because when clicking mouse in another window
;; with the same buffer it calls both activate-mark and deactivate-mark,
;; but deactivate-mark checks if the region is active (region-active-p),
;; and doesn't advance further because mark-active was set to nil in the redisplay
;; hook below.  OTOH, the advice is used unconditionally.
;; (add-hook 'deactivate-mark-hook (lambda () (setq mark-active-window nil)))
(advice-add 'deactivate-mark :after
	    (lambda (&rest _args)
Juri Linkov's avatar
Juri Linkov committed
981 982
	      (setq mark-active-window nil))
	    '((name . mark-active-window)))
983 984 985 986 987

(defun redisplay--update-mark-active-window (window)
  (when mark-active-window
    (setq mark-active (eq mark-active-window window))))

Juri Linkov's avatar
Juri Linkov committed
988
(add-hook 'pre-redisplay-functions #'redisplay--update-mark-active-window)
989

990 991 992

;;; follow

993 994 995
(with-eval-after-load 'follow
  (define-key follow-mode-map [prior] 'follow-scroll-down)
  (define-key follow-mode-map [next]  'follow-scroll-up))
996

Juri Linkov's avatar
Juri Linkov committed
997 998 999

;;; isearch

1000
;; Save and restore window start positions on returning to previous search
1001
;; TODO: try to use ‘add-function’
1002 1003 1004 1005
(setq isearch-push-state-function
      (lambda ()
	;; Recenter new search hits outside of window boundaries
        (when (and isearch-success (not (pos-visible-in-window-p)))
Juri Linkov's avatar
Juri Linkov committed
1006 1007 1008 1009
	  ;; reposition-window takes too much time in large buffers
          (if (or (eq major-mode 'fundamental-mode)
                  (> (buffer-size) 1000000))
	      (recenter-top)
1010 1011 1012 1013
	    (condition-case nil
		;; Prevent errors from reposition-window
		(reposition-window)
	      (error nil))))
1014 1015 1016 1017
        `(lambda (cmd)
           (when isearch-success
             (set-window-start nil ,(window-start))))))

1018
(defun isearch-refresh-state ()
Juri Linkov's avatar
Juri Linkov committed
1019
  "Refresh the last search state.
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
This might be necessary when e.g. the window was manually recentered with
`C-l C-l', so new window-start should be updated in push-state-function above
before searching for the next hit."
  ;; Pop and discard the previous state
  (pop isearch-cmds)
  ;; Push a new state
  (isearch-push-state))

(advice-add 'isearch-repeat-forward :before
	    (lambda (&rest _args)
	      (isearch-refresh-state))
	    '((name . refresh-state)))

(advice-add 'isearch-repeat-backward :before
	    (lambda (&rest _args)
	      (isearch-refresh-state))
	    '((name . refresh-state)))

Juri Linkov's avatar
Juri Linkov committed
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
;; Wrap without failing, posted to
;; http://stackoverflow.com/questions/285660/automatically-wrapping-i-search#287067
;; (defadvice isearch-repeat (after isearch-no-fail activate)
;;   (unless isearch-success
;;     (ad-disable-advice 'isearch-repeat 'after 'isearch-no-fail)
;;     (ad-activate 'isearch-repeat)
;;     (isearch-repeat (if isearch-forward 'forward))
;;     (ad-enable-advice 'isearch-repeat 'after 'isearch-no-fail)
;;     (ad-activate 'isearch-repeat)))

;; Automatically recenter every found isearch match
;; (defadvice isearch-update (before my-isearch-update activate)
;;   (sit-for 0)
;;   (if (and
;;        ;; not the scrolling command
;;        (not (eq this-command 'isearch-other-control-char))
;;        ;; not the empty string
;;        (> (length isearch-string) 0)
;;        ;; not the first key (to lazy highlight all matches w/o recenter)
;;        (> (length isearch-cmds) 2)
;;        ;; the point in within the given window boundaries
;;        (let ((line (count-screen-lines (point) (window-start))))
;;          (or (> line (* (/ (window-height) 4) 3))
;;              (< line (* (/ (window-height) 9) 1)))))
;;       (let ((recenter-position 0.3))
;;         (recenter '(4)))))

;; Automatically reposition every found isearch match
;; (defadvice isearch-update (before my-isearch-reposite activate)
;;   (sit-for 0)
;;   (reposition-window))

1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
;; TODO: try to use `isearch-update-post-hook', e.g.
;; (add-hook 'isearch-update-post-hook 'recenter)
;; (add-hook 'replace-update-post-hook 'recenter)
(defadvice isearch-update (before my-isearch-reposite activate)
  (sit-for 0)
  ;; While browsing patches, make the next hunk posited at the window's top:
  (when (and (derived-mode-p 'diff-mode) isearch-regexp (equal "^revno:" isearch-string))
    (recenter 1)))

(put 'toggle-truncate-lines 'isearch-scroll t)
1080
(put 'comint-show-output 'isearch-scroll t) ;; bound to `C-M-l'
Juri Linkov's avatar
Juri Linkov committed
1081 1082 1083 1084 1085 1086 1087 1088 1089

(define-key isearch-mode-map "\M-<" 'isearch-beginning-of-buffer)
(define-key isearch-mode-map "\M->" 'isearch-end-of-buffer)

(define-key isearch-mode-map             "\t" 'isearch-complete)
(define-key minibuffer-local-isearch-map "\t" 'isearch-complete-edit)

(define-key isearch-mode-map [(control return)] 'isearch-exit)

1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
;; C-RET doesn't add the current search string to the search ring
;; and moves point to the beginning of the found search string.
(add-hook 'isearch-mode-end-hook
          (lambda ()
            ;; Exiting isearch with C-RET
            (when (eq last-input-event 'C-return)
              ;; Move point to the beginning of the found search string
              (if (and isearch-forward isearch-other-end)
                  (goto-char isearch-other-end))
              ;; Don't add the current search string to the search ring
              (if isearch-regexp
                  (setq regexp-search-ring (cdr regexp-search-ring))
                (setq search-ring (cdr search-ring))))))

Juri Linkov's avatar
Juri Linkov committed
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
;; S-RET leaves lazy-highlighted matches.
(defun my-isearch-exit-leave-lazy-highlight ()
  "Exit search and leave extra match highlighting."
  (interactive)
  (let ((lazy-highlight-cleanup nil))
    (when isearch-lazy-highlight
      (isearch-lazy-highlight-new-loop (point-min) (point-max)))
    (isearch-exit)))

(define-key isearch-mode-map [(shift return)]
                             'my-isearch-exit-leave-lazy-highlight)

;; Make Isearch mode-line string shorter, just " /" instead of " Isearch"
;; (add-hook 'isearch-mode-hook
;;           (lambda () (setq isearch-mode " /") (force-mode-line-update)))

;; Do not use customization to not corrupt .emacs with literal
;; control characters.
;; The next line is bad, because \n is bad for `C-M-s SPC $'
;; (setq search-whitespace-regexp "[ \t\r\n]+")
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
;; TRY to ignore punctuation, BAD because C-w (`isearch-yank-word-or-char')
;; doesn't yank punctuation characters, so use word search instead of this:
;; (setq search-whitespace-regexp "\\W+")
;; TRY to match newlines like in `compare-windows-whitespace':
(setq search-whitespace-regexp "\\(\\s-\\|\n\\)+")
;; Actually this line doesn't affect `search-whitespace-regexp' defined below.
(setq Info-search-whitespace-regexp "\\(\\s-\\|\n\\)+")

;; TRY:
;; Like `word-search-regexp'
(defun search-whitespace-regexp (string &optional _lax)
  "Return a regexp which ignores whitespace.
Uses the value of the variable `search-whitespace-regexp'."
  (if (or (not (stringp search-whitespace-regexp))
          (null (if isearch-regexp
                    isearch-regexp-lax-whitespace
                  isearch-lax-whitespace)))
      string
    ;; FIXME: this is not strictly correct implementation because it ignores
    ;; `subregexp-context-p' and replaces spaces inside char set group like
    ;; in `C-M-s M-s SPC [ ]', it converts it to ["\\(\\s-\\|\n\\)+"] !
    (replace-regexp-in-string
     search-whitespace-regexp
     search-whitespace-regexp ;; or replace by " " that is handled by search-spaces-regexp
     (regexp-quote string) nil t)))
;; (defun search-forward-lax-whitespace (string &optional bound noerror count)
;;   (re-search-forward (search-whitespace-regexp (regexp-quote string)) bound noerror count))
;; (defun search-backward-lax-whitespace (string &optional bound noerror count)
;;   (re-search-backward (search-whitespace-regexp (regexp-quote string)) bound noerror count))
;; (defun re-search-forward-lax-whitespace (regexp &optional bound noerror count)
;;   (re-search-forward (search-whitespace-regexp regexp) bound noerror count))
;; (defun re-search-backward-lax-whitespace (regexp &optional bound noerror count)
;;   (re-search-backward (search-whitespace-regexp regexp) bound noerror count))
(setq search-default-mode #'char-fold-to-regexp)

Juri Linkov's avatar
Juri Linkov committed
1159 1160
;;;; isearch-lazy-hints

Juri Linkov's avatar
Juri Linkov committed
1161 1162 1163
(defcustom isearch-lazy-hints nil
  "Show numeric hints on isearch lazy-highlighted matches.")

Juri Linkov's avatar
Juri Linkov committed
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
(defface isearch-lazy-hint
  '((t :inherit lazy-highlight))
  "Face for lazy highlighting of counter hints."
  :group 'lazy-highlight
  :group 'basic-faces)

(defvar isearch-lazy-hints-overlays nil)

(defun isearch-lazy-hints-cleanup ()
  (while isearch-lazy-hints-overlays
    (delete-overlay (pop isearch-lazy-hints-overlays))))

(defun isearch-lazy-hint (pos count)
Juri Linkov's avatar
Juri Linkov committed
1177 1178 1179 1180 1181 1182
  (let* ((ov (make-overlay pos pos)
             ;; (if (or (and isearch-forward (> count 0))
             ;;         (and (not isearch-forward) (< count 0)))
             ;;     (make-overlay (1- pos) pos)
             ;;   (make-overlay pos (1+ pos)))
             )
Juri Linkov's avatar
Juri Linkov committed
1183 1184 1185 1186 1187 1188
         (hint (number-to-string count)))
    (set-text-properties 0 (length hint)
                         '(face isearch-lazy-hint
                           display ((height 0.7) (raise 0.3)))
                         hint)
    (overlay-put ov 'after-string hint)
Juri Linkov's avatar
Juri Linkov committed
1189
    ;; (overlay-put ov 'display hint)
Juri Linkov's avatar
Juri Linkov committed
1190 1191 1192 1193 1194
    (overlay-put ov 'priority 1000)
    (overlay-put ov 'window (selected-window))
    (push ov isearch-lazy-hints-overlays)))

(defun isearch-lazy-hints ()
Juri Linkov's avatar
Juri Linkov committed
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
  (when isearch-lazy-hints
    (isearch-lazy-hints-cleanup)
    (let* ((wgs (window-group-start))
           (wge (window-group-end))
           (p (or isearch-other-end (point)))
           (grouped-overlays
            (seq-group-by (lambda (ov)
                            (let* ((os (overlay-start ov))
                                   (oe (overlay-end   ov)))
                              (cond
                               ((or (< os wgs) (> oe wge)) nil)
                               ((> oe p) 'after)
                               (t 'before))))
                          isearch-lazy-highlight-overlays)))
      (seq-map-indexed
       (lambda (ov index)
	 (isearch-lazy-hint (if isearch-forward (overlay-end ov) (overlay-start ov))
                            (1+ index)))
       (cdr
	;; Skip the current match
	(seq-sort-by #'overlay-start (if isearch-forward #'< #'>)
                     (cdr (assq (if isearch-forward 'after 'before)
				grouped-overlays)))))
      (seq-map-indexed
       (lambda (ov index)
	 (isearch-lazy-hint (if isearch-forward (overlay-start ov) (overlay-end ov))
                            (- (1+ index))))
       (seq-sort-by #'overlay-start (if isearch-forward #'> #'<)
                    (cdr (assq (if isearch-forward 'before 'after)
                               grouped-overlays)))))))

(defun isearch-toggle-lazy-hints ()
  (interactive)
  (when isearch-lazy-hints
    (isearch-lazy-hints-cleanup))
  (setq isearch-lazy-hints (not isearch-lazy-hints))
  (when isearch-lazy-hints
    (isearch-lazy-hints)))

;; (add-hook 'isearch-mode-end-hook 'isearch-lazy-hints-cleanup)
;; To clean also after ispell lazy-highlight
(advice-add 'lazy-highlight-cleanup :after (lambda (&optional _ _) (isearch-lazy-hints-cleanup)))
Juri Linkov's avatar
Juri Linkov committed
1237 1238 1239 1240 1241 1242 1243

;; TODO: add to the end of isearch-lazy-highlight-new-loop
(add-hook 'isearch-update-post-hook 'isearch-lazy-hints)

;; TODO: call isearch-lazy-hint from isearch-lazy-highlight-update?
(advice-add 'isearch-lazy-highlight-update :after 'isearch-lazy-hints)

Juri Linkov's avatar
Juri Linkov committed
1244 1245
(define-key isearch-mode-map (kbd "C-0") 'isearch-toggle-lazy-hints)

Juri Linkov's avatar
Juri Linkov committed
1246 1247
;;;; isearch-decomposition

1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
;; OBSOLETE:
;; Decomposition search for accented letters.
(define-key isearch-mode-map "\M-sd" 'isearch-toggle-decomposition)
(defun isearch-toggle-decomposition ()
  "Toggle Unicode decomposition searching on or off."
  (interactive)
  (setq isearch-word (unless (eq isearch-word 'isearch-decomposition-regexp)
		       'isearch-decomposition-regexp))
  (if isearch-word (setq isearch-regexp nil))
  (setq isearch-success t isearch-adjusted t)
  (isearch-update))
(defun isearch-decomposition-regexp (string &optional _lax)
  "Return a regexp that matches decomposed Unicode characters in STRING."
  (let ((accents "['`\"́̋]"))
    (mapconcat
     (lambda (c0)
       (concat (string c0) accents "?"))
     (replace-regexp-in-string accents "" string) "")))
(put 'isearch-decomposition-regexp 'isearch-message-prefix "deco ")
Juri Linkov's avatar
Juri Linkov committed
1267

Juri Linkov's avatar
Juri Linkov committed
1268 1269
;;;; isearch-diff-hunk

1270 1271 1272 1273 1274 1275 1276
(isearch-define-mode-toggle diff-hunk "+" diff-hunk-to-regexp "\
Ignore diff-mode hunk indicators such as `+' or `-' at bol.")

(defun diff-hunk-to-regexp (string &optional _lax from)
  (replace-regexp-in-string
   "[[:space:]]+" "[[:space:]]+"
   (replace-regexp-in-string
1277
    "^\\(\\\\\\+\\|-\\)" "\\(^\\)[+-]"
1278 1279 1280 1281 1282 1283
    (regexp-quote string) nil t)))

(add-hook 'diff-mode-hook
	  (lambda ()
	    (set (make-local-variable 'search-default-mode) 'diff-hunk-to-regexp)))

Juri Linkov's avatar
Juri Linkov committed
1284 1285 1286

;;; occur

1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
;; Make *Occur* buffer names unique and writable
;; (like in `compilation-mode-hook' below).
(add-hook 'occur-hook
          (lambda ()
            (occur-rename-buffer t)
            (setq buffer-read-only nil)))

;; Based on `occur-mode-goto-occurrence-other-window'
(defun occur-mode-goto-occurrence-kill-buffer ()
  "Go to the occurrence the current line describes, and kill the Occur buffer."
  (interactive)
  (let ((buf (current-buffer))
        (pos (occur-mode-find-occurrence)))
    (switch-to-buffer-other-window (marker-buffer pos))
    (goto-char pos)
    (kill-buffer buf)
    (run-hooks 'occur-mode-find-occurrence-hook)))

;; Bind to "o" in place of `occur-mode-goto-occurrence'.
(define-key occur-mode-map [(control return)] 'occur-mode-goto-occurrence-kill-buffer)
Juri Linkov's avatar
Juri Linkov committed
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316


;;; replace

(defun substitute-regexp (substitution)
  "Use s/old/new/g regexp syntax for `query-replace'."
  (interactive
   (list
    (read-from-minibuffer "Substitute regexp: " '("s///g" . 3) nil nil
                          'query-replace-history nil t)))
1317
  (if (string-match "\\`s/\\(.*\\)/\\(.*\\)/\\([gi]*\\)" substitution)
Juri Linkov's avatar
Juri Linkov committed
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
      (let* ((sregex (match-string 1 substitution))
             (ssubst (match-string 2 substitution))
             (sflags (match-string 3 substitution))
             (case-fold-search (string-match "i" sflags)))
        (perform-replace
         sregex ssubst (string-match "g" sflags)
         t nil nil nil
         (if (and transient-mark-mode mark-active) (region-beginning))
         (if (and transient-mark-mode mark-active) (region-end))))
    (error "Invalid syntax")))

1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
;; FROM http://emacs.stackexchange.com/questions/27135/search-replace-like-feature-for-swapping-text/27170#27170
(defun query-swap-strings (from-string to-string &optional delimited start end backward region-noncontiguous-p)
  "Swap occurrences of FROM-STRING and TO-STRING."
  (interactive
   (let ((common
	  (query-replace-read-args
	   (concat "Query swap"
		   (if current-prefix-arg
		       (if (eq current-prefix-arg '-) " backward" " word")
		     "")
		   (if (use-region-p) " in region" ""))
	   nil)))
     (list (nth 0 common) (nth 1 common) (nth 2 common)
	   (if (use-region-p) (region-beginning))
	   (if (use-region-p) (region-end))
	   (nth 3 common)
	   (if (use-region-p) (region-noncontiguous-p)))))
  (perform-replace
   (concat "\\(" (regexp-quote from-string) "\\)\\|" (regexp-quote to-string))
   `(replace-eval-replacement replace-quote (if (match-string 1) ,to-string ,from-string))
   t t delimited nil nil start end backward region-noncontiguous-p))

Juri Linkov's avatar
Juri Linkov committed
1351 1352 1353

;;; minibuffer

1354 1355 1356
;; See http://lists.gnu.org/archive/html/emacs-devel/2014-12/msg00299.html
(define-key minibuffer-local-map [S-return] 'newline)

Juri Linkov's avatar
Juri Linkov committed
1357
;; Remove potentially dangerous commands from the history immediately
1358 1359 1360 1361 1362 1363 1364
;; Also like in Bash HISTCONTROL: "A colon-separated list of values controlling
;; how commands are saved on the history list.  If the list of values includes
;; ignorespace, lines which begin with a space character are not saved in the
;; history list.  A value of ignoredups causes lines matching the previous
;; history entry to not be saved."
;; TODO: We already have ‘history-delete-duplicates’ that corresponds to ‘ignoredups’,
;; but still no option that would corresponds to ‘ignorespace.’
Juri Linkov's avatar
Juri Linkov committed
1365 1366 1367
(add-hook 'minibuffer-exit-hook
          (lambda ()
            (when (string-match
1368
                   "\\`\\(?:rm\\| \\)"
1369
                   (or (car-safe (symbol-value minibuffer-history-variable)) ""))
Juri Linkov's avatar
Juri Linkov committed
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
              (set minibuffer-history-variable
                   (cdr (symbol-value minibuffer-history-variable))))))

;; This is not needed when isearch C-s/C-r in the minibuffer is available
;; (but `C-M-r ^command' doesn't match at the beginning of the input area)
(define-key minibuffer-local-map "\eN" 'next-complete-history-element)
(define-key minibuffer-local-map "\eP" 'previous-complete-history-element)

;; M-k in the minibuffer deletes the minibuffer history element.
(defun delete-history-element ()
  "Delete the current minibuffer history element from the history.
After deleting the element, the history position is changed either
to the the previous history element, or to the next history element
if the deleted element was the last in the history list."
  (interactive)
  (cond
   ((= minibuffer-history-position 1)
    (set minibuffer-history-variable
         (cdr (symbol-value minibuffer-history-variable))))
   ((> minibuffer-history-position 1)
    (setcdr (nthcdr (- minibuffer-history-position 2)
                    (symbol-value minibuffer-history-variable))
            (nthcdr minibuffer-history-position
                    (symbol-value minibuffer-history-variable)))))
  (condition-case nil (next-history-element     1) (error nil))
  (condition-case nil (previous-history-element 1) (error nil)))

(define-key minibuffer-local-map "\ek" 'delete-history-element)
(define-key minibuffer-local-isearch-map "\ek" 'delete-history-element)

;; THE NEXT 3 FUNCTIONS WORK WITH BIG DELAY (try to use like icomplete.el)
;; see also PC-temp-minibuffer-message, file-cache-temp-minibuffer-message,
;; calc-temp-minibuffer-message and bug report in emacs-pretest-bug
;; Subject: bad doc string for PC-temp-minibuffer-message
(defun minibuffer-history-position-message ()
  (if (memq this-command '(next-history-element previous-history-element))
      (minibuffer-message
       (propertize
        (format "%s[%s]"
                (make-string
                 1
                 ;;              (- (frame-width)
                 ;;                 (minibuffer-prompt-width)
                 ;;                 (length (minibuffer-contents-no-properties))
                 ;;                 5)
                 ?\ )
                minibuffer-history-position) 'face 'shadow))))
;; (defadvice next-history-element (after history-position-message activate)
;;   (minibuffer-history-position-message))
;; (defadvice previous-history-element (after history-position-message activate)
;;   (minibuffer-history-position-message))
;; (defadvice goto-history-element (after history-position-message activate)
;;   (minibuffer-history-position-message))

;; (defadvice goto-history-element (before minibuffer-set-default activate)
;;   (if (functionp minibuffer-default-function)
;;       (funcall minibuffer-default-function)))

;; Another implementation of the same idea:
(defvar minibuffer-history-position-overlay)
(make-variable-buffer-local 'minibuffer-history-position-overlay)
(defun minibuffer-history-position-setup ()
  "Set up a minibuffer for `minibuffer-history-position-mode'.
The prompt should already have been inserted."
  (setq minibuffer-history-position-overlay (make-overlay (point-min) (1+ (point-min))))
  (overlay-put minibuffer-history-position-overlay 'evaporate t))
;; (add-hook 'minibuffer-setup-hook 'minibuffer-history-position-setup)
(defun minibuffer-history-position-update ()
  "Update a minibuffer for `minibuffer-history-position-mode'."
  (overlay-put minibuffer-history-position-overlay 'before-string
               (propertize (format "(%d) " minibuffer-history-position)
                           'face 'minibuffer-prompt)))
;; (defadvice next-history-element (after my-next-history-element activate)
;;   (minibuffer-history-position-update))
;; (defadvice previous-history-element (after my-previous-history-element activate)
;;   (minibuffer-history-position-update))


;;; other features

;; http://thread.gmane.org/gmane.emacs.devel/116457/focus=116468 is like this:
(defun my-info-refresh (&optional arg)
  "Display some useful information in the echo area instead of the mode line.
With prefix arg, insert the current timestamp to the current buffer."
  (interactive "P")
  (cond
   ((equal arg '(4))  ; C-u f5
    (insert (format-time-string "%Y%m%d" (current-time))))
   ((equal arg '(16)) ; C-u C-u f5
    (insert (format-time-string "%Y-%m-%d" (current-time))))
   (t (message "%s"
               (concat
                (format-time-string "%Y-%m-%d %H:%M:%S %z" (current-time)) ;; ISO
                " "
1464 1465 1466
                (if (boundp 'calendar-day-abbrev-array)
                    (aref calendar-day-abbrev-array (nth 6 (decode-time (current-time))))
                  (format-time-string "%a" (current-time)))
Juri Linkov's avatar
Juri Linkov committed
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
                " : "
                (or (buffer-file-name) default-directory))))))

(define-key my-map     [f5]  'my-info-refresh)
(define-key global-map [f5]  'my-info-refresh)

(defun my-work-log-add (&optional arg)
  (interactive "P")
  (find-file my-work-log-file)
  (goto-char (point-max))
  (cond ((re-search-backward "^[0-9-]+ [0-9:]+\\( +\\)[^0-9]" nil t)
         (goto-char (match-beginning 1))
         (replace-match "" t t nil 1)
         (insert (format-time-string " %H:%M " (current-time))))
        ((re-search-backward "^[0-9-]+ [0-9:]+" nil t)
         (forward-line 1)
         (insert (format-time-string "%Y-%m-%d %H:%M       \n" (current-time)))
         (backward-char))))

(define-key my-map "wl" 'my-work-log-add)

(defun my-buffer-xray ()
  "Display text properties and overlays of current buffer by adding markups."
  (interactive)
  (let* ((newbuf (get-buffer-create (format "*xray-buffer*/%s" (buffer-name))))
         (s (buffer-substring (point-min) (point-max))) ;; (buffer-string) -no-properties
         (overlays (sort (overlays-in (point-min) (point-max))
                         (lambda (a b) (< (overlay-start a)
                                          (overlay-start b)))))
         (oi 0)
         ;; ois is indexes of overlays sorted by start positions
         (ois (mapcar (lambda (o) (setq oi (1+ oi)) (cons o oi))
                      overlays))
         ;; poss is list of positions of boundaries of text properties
         ;; and start and end positions of overlays
         (poss (sort
                (append
                 (let ((p (point-min)) (pp))
                   (while p
                     (setq pp (cons (cons p (text-properties-at p)) pp))
                     (setq p (next-property-change p)))
                   pp)
                 (mapcar (lambda (o)
                           (list (overlay-start o) 'os (cdr (assq o ois))))
                         overlays)
                 (mapcar (lambda (o)
                           (list (overlay-end o) 'oe (cdr (assq o ois))))
                         overlays))
                ;; sort positions in the descending order
                (lambda (a b) (if (= (car a) (car b))
                                  ;; for equal positions first no prop
                                  (or (null (cadr b))
                                      (and (eq (cadr a) 'os) (eq (cadr b) 'os)
                                           (> (caddr a) (caddr b)))
                                      (and (eq (cadr a) 'oe) (eq (cadr b) 'oe)
                                           (< (caddr a) (caddr b))))
                                (> (car a) (car b))))))
         (p (point)))
    (switch-to-buffer newbuf)
    (insert s)
    (goto-char p)
    (save-excursion
      (mapcar (lambda (pos)
                (goto-char (car pos))
                ;; insert markup from buffer end to the beginning
                (cond
                 ((eq (cadr pos) 'os)
                  (insert (format "<o%s>" (caddr pos))))
                 ((eq (cadr pos) 'oe)
                  (insert (format "</o%s>" (caddr pos))))
                 ((null (cdr pos))
                  (insert "</p>"))
                 (t (let ((props (cdr pos)))
                      (insert "<p")
                      (while props
                        (insert (format " %s=\"" (car props)))
                        (insert
                         (cond
                          ((overlayp (cadr props))
                           (format "o%s" (cdr (assq (cadr props) ois))))
                          (t
                           (format "%s" (cadr props)))))
                        (insert "\"")
                        (setq props (cddr props)))
                      (insert ">")))))
              poss))
    (run-hooks 'my-buffer-xray)))

(add-hook 'my-buffer-xray 'html-mode)


;;; qv (evaluable bookmarks)

;; TODO: use bookmark.el?
;; TODO: add Info node and line number
(defun qv (&optional url anchor)
  "Add or activate live bookmarks.
When called interactively, put the address of the current location
inside a function call to `qv' into the clipboard that can be
pasted in another buffer that stores bookmarks.
Otherwise, after typing `C-x C-e' on the bookmark funcall
goes to the saved location."
  (interactive)
1570
  (if (called-interactively-p 'any)
Juri Linkov's avatar
Juri Linkov committed
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
      (kill-new
       (message "%s"
                (concat "(qv "
                        (cond
                         (buffer-file-name
                          (format "\"%s\"\n    \"^%s$\"" ;; "\"%s\" %s"
                                  buffer-file-name
                                  ;;(line-number-at-pos)
                                  (replace-regexp-in-string
                                   "^[ \t]*" "[ \t]*"
                                   (replace-regexp-in-string
                                    "\"" "\\\\\""
                                    (replace-regexp-in-string
                                     "\\\\" "\\\\\\\\"
                                     (regexp-quote
                                      (buffer-substring-no-properties
                                       (line-beginning-position)
                                       (line-end-position)))))))))
                        ")")))
    (cond
     ((file-exists-p url)
      (find-file url)
      (cond
       ((integerp anchor)
        (goto-line anchor))
       ((stringp anchor)
        (goto-char (point-min))
        (if (re-search-forward anchor)
            (goto-char (match-beginning 0)))))))))


;;; packages

;; Load some useful packages
(require 'misc)
(require 'tempo)
(require 'wid-edit)
(require 'generic)
(require 'generic-x)
;; Use standard js-mode instead of javascript-generic-mode from generic-x.
(setq auto-mode-alist (delete (rassoc 'javascript-generic-mode auto-mode-alist)
                              auto-mode-alist))

;; (and (require 'ffap) (ffap-bindings))
;; Don't bind ffap keybindings anymore, because now `C-x C-f M-n'
;; gets the filename at point when ffap.el is loaded
(require 'ffap)


;;; ee

(when (require 'ee-autoloads nil t)
  (define-key global-map [f1] 'ee-info)
  (define-key global-map [(control tab)] 'ee-buffers)
  (define-key my-map "eb"  'ee-buffers)
  (define-key my-map "ehc" 'ee-history-command)
  (define-key my-map "ehe" 'ee-history-extended-command)
  (define-key my-map "ehs" 'ee-history-shell-command)
  (define-key my-map "ei"  'ee-imenu)
  (define-key my-map "em"  'ee-marks)
  (define-key my-map "eo"  'ee-outline)
  (define-key my-map "epr" 'ee-programs)
  (define-key my-map "eps" 'ee-ps)
  (define-key my-map "et"  'ee-tags)
  (define-key my-map "ewa" 'ee-windows-add)
  (define-key my-map "eww" 'ee-windows)
  (define-key global-map [(meta  ?\xa7)] 'ee-windows-and-add-current)
1638
  ;; (define-key global-map [(meta ?\x8a7)] 'ee-windows-and-add-current)
Juri Linkov's avatar
Juri Linkov committed
1639 1640
  (define-key global-map [(meta     ?`)] 'ee-windows-and-add-current)
  (define-key global-map [(super    ?`)] 'ee-windows-and-add-current)
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
  (with-eval-after-load 'ee-windows
    (define-key ee-windows-keymap [(meta  ?\xa7)] 'ee-windows-select-and-delete-current)
    ;; (define-key ee-windows-keymap [(meta ?\x8a7)] 'ee-windows-select-and-delete-current)
    (define-key ee-windows-keymap [(meta     ?`)] 'ee-windows-select-and-delete-current)
    (define-key ee-windows-keymap [(super    ?`)] 'ee-windows-select-and-delete-current)
    (define-key ee-windows-keymap [( ?\xa7)] 'ee-view-record-next)
    ;; (define-key ee-windows-keymap [(?\x8a7)] 'ee-view-record-next)
    (define-key ee-windows-keymap [(    ?`)] 'ee-view-record-next)
    (define-key ee-windows-keymap [( ?\xbd)] 'ee-view-record-prev)
    ;; (define-key ee-windows-keymap [(?\x8bd)] 'ee-view-record-prev)
    (define-key ee-windows-keymap [(    ?~)] 'ee-view-record-prev)))
Juri Linkov's avatar
Juri Linkov committed
1652 1653 1654 1655

;; Use standalone wincows.el instead
(when (require 'wincows nil t)
  (define-key global-map [(meta  ?\xa7)] 'wincows)
1656
  ;; (define-key global-map [(meta ?\x8a7)] 'wincows)
Juri Linkov's avatar
Juri Linkov committed
1657 1658
  (define-key global-map [(meta     ?`)] 'wincows)
  (define-key global-map [(super    ?`)] 'wincows)
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
  (with-eval-after-load 'wincows
    (define-key wincows-mode-map [(meta  ?\xa7)] 'wincows-select)
    ;; (define-key wincows-mode-map [(meta ?\x8a7)] 'wincows-select)
    (define-key wincows-mode-map [(meta     ?`)] 'wincows-select)
    (define-key wincows-mode-map [(super    ?`)] 'wincows-select)
    (define-key wincows-mode-map [( ?\xa7)] 'wincows-next-line)
    ;; (define-key wincows-mode-map [(?\x8a7)] 'wincows-next-line)
    (define-key wincows-mode-map [(    ?`)] 'wincows-next-line)
    (define-key wincows-mode-map [( ?\xbd)] 'wincows-prev-line)
    ;; (define-key wincows-mode-map [(?\x8bd)] 'wincows-prev-line)
    (define-key wincows-mode-map [(    ?~)] 'wincows-prev-line)))
Juri Linkov's avatar
Juri Linkov committed
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681


;;; lisp

;; This is my most frequently used command bound to C-RET in Lisp modes.
(defun my-reindent-then-newline-and-indent-and-indent-sexp ()
  "Reindent current line, insert newline, then indent the new line.
Move backward out of one level of parentheses.
Indent each line of the list starting just after point."
  (interactive "*")
  (reindent-then-newline-and-indent)
  (save-excursion
1682
    (condition-case nil (backward-up-list) (error nil))
Juri Linkov's avatar
Juri Linkov committed
1683 1684 1685 1686 1687 1688 1689 1690 1691
    (indent-sexp)))

(defun my-join-line-and-indent-sexp ()
  "Join this line to previous and fix up whitespace at join.
Move backward out of one level of parentheses.
Indent each line of the list starting just after point."
  (interactive "*")
  (join-line)
  (save-excursion
1692
    (condition-case nil (backward-up-list) (error nil))
Juri Linkov's avatar
Juri Linkov committed
1693 1694 1695 1696 1697 1698 1699 1700 1701
    (let ((indent-sexp-function (key-binding "\e\C-q")))
      (if indent-sexp-function (call-interactively indent-sexp-function)))))

;; This is another frequently used command bound to C-backspace.
;; It's almost the reverse of C-RET defined above.
(defun my-join-line-and-indent-sexp-or-backward-kill-word ()
  "If point is on the whitespaces at the beginning of a line,
then join this line to previous and indent each line of the upper list.
Otherwise, kill characters backward until encountering the end of a word."
1702
  (interactive)
Juri Linkov's avatar
Juri Linkov committed
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
  (if (save-excursion (and (skip-chars-backward " \t") (bolp)))
      (my-join-line-and-indent-sexp)
    (backward-kill-word 1)))

(global-set-key [C-backspace] 'my-join-line-and-indent-sexp-or-backward-kill-word)

;; This is bound to TAB in Lisp modes.
(defun my-lisp-indent-or-complete (&optional arg)
  "Complete Lisp symbol, or indent line or region.
If the character preceding point is symbol-constituent, then perform
completion on Lisp symbol preceding point using `lisp-complete-symbol'.
Otherwise, call `indent-for-tab-command' that indents line or region."
  (interactive "P")
  (if (and (not (and transient-mark-mode mark-active
                     (not (eq (region-beginning) (region-end)))))
           (memq (char-syntax (preceding-char)) (list ?w ?_))
           (not (bobp)))
1720
      (completion-at-point)
Juri Linkov's avatar
Juri Linkov committed
1721 1722 1723 1724
    (indent-for-tab-command arg)))

(defun my-beginning-of-line-or-indentation (arg)
  "Jump to the beginning of the line or to the indentation (like `M-m')."
1725
  (interactive "^p")
Juri Linkov's avatar
Juri Linkov committed
1726 1727 1728 1729 1730
  (if (bolp)
      (beginning-of-line-text arg) ; (back-to-indentation) ?
    (if (fboundp 'move-beginning-of-line)
        (move-beginning-of-line arg)
      (beginning-of-line arg))))
1731
;; (put 'my-beginning-of-line-or-indentation 'isearch-move t)
Juri Linkov's avatar
Juri Linkov committed
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
(define-key global-map [(control ?a)] 'my-beginning-of-line-or-indentation)

(defun my-reindent-then-newline-and-indent ()
  "Create the next number item in the numbered list, or reindent."
  (interactive)
  (let ((num 1))
    (if (save-excursion
          (backward-paragraph)
          (forward-line)
          (not (and (looking-at "^\\s-*\\([0-9]\\)\\.")
                    (setq num (match-string 1)))))
        (reindent-then-newline-and-indent)
      (insert (format "\n\n%s. " (1+ (string-to-number num)))))))

(define-key global-map [(control       return)] 'reindent-then-newline-and-indent)
(define-key global-map [(control shift return)] 'my-reindent-then-newline-and-indent)

1749 1750
(define-key global-map [S-return] 'electric-newline-and-maybe-indent)

Juri Linkov's avatar
Juri Linkov committed
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
;; Lisp mode
(define-key lisp-mode-map [(control return)]
            'my-reindent-then-newline-and-indent-and-indent-sexp)
;; (define-key lisp-mode-map [(control backspace)]
;;             'my-join-line-and-indent-sexp-or-backward-kill-word)
(tempo-define-template "lisp-print-map" '("(map (lambda (x) ) " p ")"))
(define-key lisp-mode-map "\C-zim" 'tempo-template-lisp-print-map)

;; Emacs Lisp mode
(define-key emacs-lisp-mode-map [(control return)]
            'my-reindent-then-newline-and-indent-and-indent-sexp)
;; (define-key emacs-lisp-mode-map [(control backspace)]
;;             'my-join-line-and-indent-sexp-or-backward-kill-word)
(define-key emacs-lisp-mode-map [tab] 'my-lisp-indent-or-complete)
;; use C-M-i instead of
;; (define-key emacs-lisp-mode-map [(control meta tab)] 'lisp-complete-symbol)
;; use C-M-i instead of
;; (define-key emacs-lisp-mode-map "\C-ze\t" 'lisp-complete-symbol)
(define-key emacs-lisp-mode-map "\C-xF"  'find-function)
(define-key emacs-lisp-mode-map "\C-x4F" 'find-function-other-window)
(define-key emacs-lisp-mode-map "\C-x5F" 'find-function-other-frame)
(define-key emacs-lisp-mode-map "\C-xK"  'find-function-on-key)
(define-key emacs-lisp-mode-map "\C-xV"  'find-variable)
(define-key emacs-lisp-mode-map "\C-x4V" 'find-variable-other-window)
(define-key emacs-lisp-mode-map "\C-x5V" 'find-variable-other-frame)
(tempo-define-template "emacs-lisp-print-message" '("(message \"%s\" " p ")"))
(define-key emacs-lisp-mode-map "\C-zim" 'tempo-template-emacs-lisp-print-message)
(tempo-define-template "emacs-lisp-print-defun"
                       '("(defun " p " ()\n  (interactive)\n\n)\n"))
(define-key emacs-lisp-mode-map "\C-zid" 'tempo-template-emacs-lisp-print-defun)

;; Lisp Interaction mode
(define-key lisp-interaction-mode-map [(control return)]
            'my-reindent-then-newline-and-indent-and-indent-sexp)
;; (define-key lisp-interaction-mode-map [(control backspace)]
;;             'my-join-line-and-indent-sexp-or-backward-kill-word)
;; use C-M-i instead of
;; (define-key lisp-interaction-mode-map [(control meta tab)] 'lisp-complete-symbol)
(tempo-define-template "lisp-print-map" '("(map (lambda (x) ) " p ")"))
(define-key lisp-interaction-mode-map "\C-zim" 'tempo-template-emacs-lisp-print-message)

(font-lock-add-keywords
 nil ;; 'emacs-lisp-mode
 `(("\\<lambda\\>"
    (0 (progn (compose-region (match-beginning 0) (match-end 0)
                              ,(make-char 'greek-iso8859-7 107))
              nil)))))

1799 1800 1801 1802 1803 1804
(with-eval-after-load 'scheme
  (define-key scheme-mode-map [(control return)]
    'my-reindent-then-newline-and-indent-and-indent-sexp)
  ;; (define-key scheme-mode-map [(control backspace)]
  ;;             'my-join-line-and-indent-sexp-or-backward-kill-word)
  )
Juri Linkov's avatar
Juri Linkov committed
1805 1806 1807 1808


;;; clojure

1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
(with-eval-after-load 'clojure-mode
  (add-hook 'clojure-mode-hook
            (lambda ()
              (set (make-local-variable 'inferior-lisp-program)
                   ;; For latest version:
                   "lein repl"
                   ;; "java -cp /home/work/java/clojure/jar/clojure-1.7.0-alpha1.jar clojure.main"
                   ;; "java -cp /home/work/java/clojure/jar/clojure-1.5.0-RC4.jar clojure.main"
                   ;; For 1.2 with init file:
                   ;; "java clojure.main -i ~/init.clj"
                   ;; "java clojure.main"
                   ;; For OLD version 1.0 (deprecated):
                   ;; "java -cp clojure.jar clojure.lang.Repl"
                   ;; For installed version in Ubuntu:
                   ;; "clojure"
                   )))

  ;; FROM https://github.com/weavejester/compojure/wiki/Emacs-indentation
  (define-clojure-indent
    (defroutes 'defun)
    (GET 2)
    (POST 2)
    (PUT 2)
    (DELETE 2)
    (HEAD 2)
    (ANY 2)
    (context 2)))
1836 1837

;; qv http://stackoverflow.com/questions/3528705/clojure-inferior-lisp-window-in-emacs-being-displayed-over-code-when-doing-c-c-c
1838
;; (setq same-window-buffer-names (delete "*inferior-lisp*" same-window-buffer-names))
1839

Juri Linkov's avatar
Juri Linkov committed
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925

;;; snd

(autoload 'sndtr-mode "sndtr" "Major mode for editing Snd transcripts." t)
;; transcripts sndtr files
(add-to-list 'auto-mode-alist '("\\.trs\\'" . sndtr-mode))
;; marks snd files
(add-to-list 'auto-mode-alist '("\\.marks\\'" . scheme-mode))

(defun run-snd ()
  (interactive)
  (run-scheme "snd -notebook" "snd"))

;; Added "<" for Scheme "#<unspecified>"
(setq inferior-lisp-prompt "^[^<> \n]*>+:? *")

;(define-key inferior-scheme-mode-map [(meta down)] 'comint-next-prompt)
;(define-key inferior-scheme-mode-map [(meta up)] 'comint-previous-prompt)
(add-hook
 'inferior-scheme-mode-hook
 (lambda ()
   ;; no special variable for prompt in cmuscheme.el
   (setq comint-prompt-regexp "^[^<>\n]*>+ *") ; added "<"
   (define-key global-map "\C-zii"
     (lambda ()
       (interactive)
       (let* ((proc (scheme-proc))
              (m (marker-position (process-mark proc)))
              (str
               (save-excursion
                 (comint-send-string
                  proc
                  "(list (selection-position) (selection-length))\n")
                 (accept-process-output proc)
                 (set-buffer "*scheme*")
                 (buffer-substring
                  m
                  (marker-position (process-mark proc))))))
         (insert str))))))


;;; dsssl

;; Make font-lock recognise more DSSSL keywords.
;; (setq scheme-font-lock-keywords
;;      (cons '("(\\(make\\|element\\|style\\|mode\\|root\\|with-mode\\)[ \t\n]\
;;                \\([0-9a-z.-]+\\|([^)]+)\\)"
;;              (1 font-lock-keyword-face)
;;              (2 font-lock-function-name-face))
;;            scheme-font-lock-keywords))

;; Use Scheme mode for DSSSL files.
;; (add-to-list 'auto-mode-alist '("\\.dss?s?l$" . scheme-mode))
(add-to-list 'auto-mode-alist '("\\.ss$" . scheme-mode))


;;; perl

;; Use cperl mode instead of perl mode
;; PS: Don't use over-bloated cperl mode; use default perl mode instead
;; (defalias 'perl-mode 'cperl-mode)
;; (fset 'perl-mode 'cperl-mode)

(add-to-list
 'auto-insert-alist
 '(perl-mode
   nil
   "#!/usr/bin/perl -w" \n
   "# -*- Perl -*-" \n
   ;; "# \$Id\$" \n
   ;; "# \$RCSfile\$\$Revision\$\$Date\$" \n
   "# \$Revision\$" \n
   \n
   "while (<>) {" \n
   > "chomp;" \n
   > _ \n
   > "print \"$_\\n\";\n"
   "}\n"))

(tempo-define-template "perl-skeleton"
 '("#!/usr/bin/perl -w\n# -*- Perl -*-\n# \$Revision\$\n\nwhile (<>) {\n  chomp;\n  "
   p "\n}\n"))
(tempo-define-template "perl-s-skeleton" '("s/" p "//;"))
(tempo-define-template "perl-print-skeleton" '("print \"$_" p "\\n\";"))
(tempo-define-template "perl-while-skeleton" '("while (<>) {\n  chomp;\n  " p "\n}\n"))

1926 1927 1928 1929 1930
(with-eval-after-load 'perl-mode
  ;; (define-auto-insert 'perl-mode (lambda () (tempo-template-perl-skeleton)))
  (define-key perl-mode-map "\C-ziw" 'tempo-template-perl-while-skeleton)
  (define-key perl-mode-map "\C-zip" 'tempo-template-perl-print-skeleton)
  (define-key perl-mode-map "\C-zis" 'tempo-template-perl-s-skeleton))
Juri Linkov's avatar
Juri Linkov committed
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957

;; Try to distinguish between Perl and Prolog file types
;; TODO: make/use external programs (a-la 'file')
;; but best solution is to use "-*- mode: -*-" in the first line
;; qv http://thread.gmane.org/gmane.emacs.devel/114377/focus=114713
(setq auto-mode-alist
      (append '(("\\.perl\\'" . perl-mode)
                ("\\.pm\\'" . perl-mode)
                ;; pl files in *perl* dir are Perl files
                ;; ("perl.*\\.pl\\'" . perl-mode)
                ("\\.pl\\'" . perl-mode))
              auto-mode-alist))
(defun my-pl-find-file-hook ()
  ;; To distinguish Prolog and Perl files with the same file extension
  ;; '.pl', it assumes that Perl programs begin with a comment '#',
  ;; but this doesn't work yet for Prolog shell scripts, so it's more
  ;; reliable to use file local variables with the needed mode specified.
  (if (and (looking-at "#")
           (or
            ;; This works when '.pl' is associated with Prolog mode
            (string-match "Prolog" mode-name)
            ;; BTW, Perl mode fits perfectly for different conf-files
            (equal mode-name "Fundamental")))
      (perl-mode)))
;; (add-hook 'find-file-hooks 'my-pl-find-file-hook)

;; Create Perl links in the *Man* buffer
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
(with-eval-after-load 'man
  (add-hook
   'Man-cooked-hook
   (lambda ()
     ;; TODO: add to perl-mode.el? and cperl-mode.el?
     ;; BAD: it breaks links followed with a dot!
     (if (string-match "\\`\\([0-9]+ *\\)?perl" Man-arguments)
         (Man-highlight-references0
          "DESCRIPTION"
          "\\(perl\\(?:[a-z0-9]+[a-z]\\|[a-z][a-z0-9]+\\)\\)[^a-z0-9]"
          1 0 'Man-xref-man-page)))))
Juri Linkov's avatar
Juri Linkov committed
1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058


;;; prolog

(setq prolog-system 'swi)
(setq prolog-indent-width 8)
(setq prolog-electric-dot-flag t)
(setq prolog-program-switches
  '((sicstus ("-i"))
    (swi ("-G8M"))
    (t nil)))
(setq prolog-info-predicate-index "(prolog)Predicates188")

;; Use better prolog-mode from http://www.emacswiki.org/emacs/PrologMode
;; renamed here to prolog2.el
;; (load "progmodes/prolog2.el")
;; (autoload 'run-prolog   "prolog2" "Start a Prolog sub-process." t)
;; (autoload 'prolog-mode  "prolog2" "Major mode for editing Prolog programs." t)
;; (autoload 'mercury-mode "prolog2" "Major mode for editing Mercury programs." t)

;; (setq outline-regexp "[0-9]+ \\?-") ; for *prolog*
(setq auto-mode-alist
      (append '(
               ;; ("\\.pl?\\'" . 'prolog-mode) ; SWI Prolog
               ;; pl files in *prolog* dir are Prolog files
               ("prolog.*\\.pl?\\'" . prolog-mode) ; SWI Prolog
               ("\\.[Pp][Rr][Oo]\\'" . prolog-mode)
               ("\\.ari\\'" . prolog-mode) ; Arity Prolog
               ) auto-mode-alist))

;; Resolve file extension conflict between Octave and Mercury Prolog
;; in favor of Mercury Prolog
;; (add-to-list 'auto-mode-alist '("\\.m\\'" . octave-mode))
(add-to-list 'auto-mode-alist '("\\.m\\'" . mercury-mode))

(add-hook
 'prolog-mode-hook
 (lambda ()
   (require 'prolog)
   (setq prolog-system 'swi)
   (define-key prolog-mode-map [(control f1)]
     (lambda () (interactive) (my-search-prolog-doc-at-point)))
   ;;(fset 'prolog-add-predicate-comment
   ;;       [C-f5 up up ?\M-3 ?% ?  ?\M-2 C-right ?\C-k ?\C-m ?\M-2 ?% ?  ? ])
   (fset 'prolog-add-predicate-comment
         [?\C-n ?\C-o C-f5 ?\C-a up ?\M-3 ?% ?  ?\M-2 C-right ?\C-k ?\C-m ?\M-2 ?% ?  ? ])
   (define-key prolog-mode-map "\C-zic" 'prolog-add-predicate-comment)
   ;; (define-key prolog-mode-map "\C-zic"
   ;;   (lambda () (interactive) (end-of-line) (insert-string " :- ")))
   ;; (define-key prolog-mode-map "\C-zi,"
   ;;   (lambda () (interactive) (end-of-line) (insert-string ", ")))
   ;; (define-key prolog-mode-map "\C-zi."
   ;;   (lambda () (interactive) (end-of-line) (insert-string ".") (newline)))
   ;; (defun prolog-outline-level () (- 4 (outline-level)))
   (set (make-local-variable 'outline-regexp) "%%%+")
   (set (make-local-variable 'outline-level) (lambda () (- 5 (outline-level))))
   ;; (setq outline-level 'prolog-outline-level)
   ;; global-font-lock-mode doesn't work with prolog.el, but works with prolog2.el
   ;; (font-lock-mode 1)
   ))

(add-hook
 'prolog-inferior-mode-hook
 (lambda ()
   ;; (setq comint-input-ring-file-name "~/.pl_history")
   ;; (comint-read-input-ring t)
   ;; THIS CAUSED TRANSIENT-MODE NOT-WORKING !!!
   ;; -> (add-hook 'pre-command-hook 'comint-write-input-ring)
   (define-key prolog-inferior-mode-map [(control f1)]
     (lambda () (interactive) (my-search-prolog-doc-at-point)))
   (define-key prolog-inferior-mode-map "\C-zo" 'comint-kill-output-since-last-prompt)
   (set (make-local-variable 'outline-regexp) "^[1-9][0-9]* \\?- ")
   (set (make-local-variable 'outline-level) (lambda () 1))))

(defun my-search-prolog-doc-at-point ()
  (let* ((wordchars "a-zA-Z_0-9")
         (str
          (concat "\^L\n\n"
                  (current-word)
                  ;; (buffer-substring-no-properties
                  ;; (save-excursion (skip-chars-backward wordchars) (point))
                  ;; (save-excursion (skip-chars-forward  wordchars) (point)))
                  "(")))
    (view-file "~/doc/prog/prolog/PROLOG")
    ;; (set (make-local-variable 'outline-regexp) "^\\(Chapter [0-9]\\|\\)")
    ;; (make-local-variable 'outline-level)
    (if (not (re-search-forward str nil t))
        (progn
          (goto-char (point-min))
          (re-search-forward str nil t)))
2059
    (outline-show-entry) ;?
Juri Linkov's avatar
Juri Linkov committed
2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
    (message str)))

;; for PROLOG manual:
;; outline-regexp: "Chapter\\|[0-9]\\.[0-9]+ .....\\|[0-9]+\\.[0-9]+\\.[0-9]+ ....."
;; outline-level: outline-level-for-prolog-manual
;; mode: outline-minor
;; (setq outline-regexp "Chapter\\|[0-9]+\\.[0-9]+ .....\\|[0-9]+\\.[0-9]+\\.[0-9]+ .....")
;; (setq outline-level (lambda ()
;;                       (save-excursion
;;                         (cond
;;                          ((looking-at "Chapter") 1)
;;                          ((looking-at "[0-9]+\\.[0-9]+ ") 2)
;;                          ((looking-at "[0-9]+\\.[0-9]+\\.[0-9]+ ") 3)))))
;; (defun outline-level-for-prolog-manual ()
;;   (save-excursion
;;     (cond
;;      ((looking-at "Chapter") 1)
;;      ((looking-at "[0-9]+\\.[0-9]+ ") 2)
;;      ((looking-at "[0-9]+\\.[0-9]+\\.[0-9]+ ") 3))))


;;; erlang

;; TODO: for Yaws templates use mumamo with erlang-mode and html-mode
(add-to-list 'auto-mode-alist '("\\.yaws\\'" . erlang-mode))

2086 2087
(setq erlang-inferior-shell-split-window nil)

2088 2089 2090 2091 2092
(with-eval-after-load 'erlang
  (add-hook 'erlang-mode-hook
            (lambda ()
              (setq tab-width 2)
              (alchemist-mode 1))))
2093

2094 2095
(add-to-list 'auto-mode-alist '("\\.eex\\'" . html-erb-mode))

2096 2097 2098 2099 2100
(with-eval-after-load 'alchemist
  ;; (global-company-mode)
  ;; (define-key elixir-mode-map "\M-\t" 'company-complete)
  ;; (define-key company-active-map [escape] 'company-abort)
  )
2101

Juri Linkov's avatar
Juri Linkov committed
2102 2103 2104 2105 2106 2107 2108 2109 2110

;;; haskell

;; also qv comment in (qv "files.el" "^(defvar interpreter-mode-alist")
(add-to-list 'interpreter-mode-alist '("runhugs" . literate-haskell-mode))


;;; html

2111 2112 2113
(add-to-list 'auto-mode-alist '("\\.mustache\\'" . html-mode))
(add-to-list 'auto-mode-alist '("\\.ejs\\'" . html-mode))

Juri Linkov's avatar
Juri Linkov committed
2114 2115 2116
;; These are needed to set before loading sgml-mode.el:
;; (setq sgml-quick-keys t)
(setq html-quick-keys t)
2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
(with-eval-after-load 'sgml-mode
  (modify-syntax-entry ?. "." sgml-mode-syntax-table)
  (modify-syntax-entry ?: "." sgml-mode-syntax-table)
  (setq html-tag-face-alist (append '(("a" . underline))
                                    html-tag-face-alist)))

(with-eval-after-load 'sgml-mode
  (define-skeleton html-headline-1
    "HTML level 1 headline tags."
    nil
    "<h1><a name=\"" (setq str (read-string "Name: "))
    "\" id=\"" str "\">" _ "</a></h1>")

  (define-skeleton html-headline-2
    "HTML level 2 headline tags."
    nil
    "<h2><a name=\"" (setq str (read-string "Name: "))
    "\" id=\"" str "\">" _ "</a></h2>"))
Juri Linkov's avatar
Juri Linkov committed
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174

(add-hook 'html-mode-hook 'turn-off-auto-fill)
(add-hook 'html-mode-hook
          (lambda ()
            ;; (define-key html-mode-map [?\x8a0] (lambda))
            (define-key html-mode-map "\C-c&" 'sgml-name-char)
            ;; (define-key html-mode-map "\C-z" my-map)
            ))
(add-hook 'html-mode-hook
          (lambda ()
            ;; Because `sgml-mode' overrides the user customization
            ;; sgml-xml-mode=t with the value from `sgml-xml-guess'.
            (setq sgml-xml-mode t)
            ))

(defvar my-auto-insert-html-mode-language "en")
(add-to-list
 'auto-insert-alist
 '(html-mode
   nil
   (when (string-match "\\.\\([^.][^.]\\)\\.html$" buffer-file-name)
     (setq my-auto-insert-html-mode-language
           (match-string 1 buffer-file-name))
     "")
   ;; "<?xml version=\"1.0\" encoding=\""
   ;; (if (equal my-auto-insert-html-mode-language "ru") "KOI8-R" "ISO-8859-1")
   ;; "\"?>\n"
   "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
   "     \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
   "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\""
   my-auto-insert-html-mode-language "\" lang=\""
   my-auto-insert-html-mode-language "\">\n"
   "<head>\n"
   "<meta http-equiv=\"Content-Type\" content=\"text/html; charset="
   (if (equal my-auto-insert-html-mode-language "ru") "koi8-r" "iso-8859-1")
   "\" />\n"
   "<meta http-equiv=\"Content-Language\" content=\""
   my-auto-insert-html-mode-language "\" />\n"
   "<meta name=\"description\" content=\"\" />\n"
   "<meta name=\"keywords\" content=\"\" />\n"
2175
   "<title>" (capitalize (setq str (downcase (read-string "Title: ")))) "</title>\n"
Juri Linkov's avatar
Juri Linkov committed
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
   "<link rel=\"stylesheet\" type=\"text/css\" href=\"/jurta.css\" />\n"
   "</head>\n"
   "<body>\n<h1><a name=\"" str "\" id=\"" str "\">" str "</a></h1>\n"
   _
   "\n"
   "</body>\n"
   "</html>\n"))


;;; htmlize

2187 2188
;; (global-set-key [print] 'htmlize-buffer)
(global-set-key [print] 'htmlfontify-buffer)
Juri Linkov's avatar
Juri Linkov committed
2189

2190 2191 2192

;;; web development

2193 2194 2195 2196
(with-eval-after-load 'cc-mode
  (add-hook 'java-mode-hook
            (lambda ()
              (setq tab-width 4))))
2197

2198 2199 2200 2201
(with-eval-after-load 'css-mode
  (add-hook 'css-mode-hook
            (lambda ()
              (setq tab-width 2))))
2202

2203 2204 2205 2206 2207
(with-eval-after-load 'js
  (add-hook 'js-mode-hook
            (lambda ()
              (setq js-indent-level 2)
              (setq tab-width 2))))
2208