chiark / gitweb /
dot/emacs, el/dot-emacs.el: Add new command for switching window configs.
[profile] / el / dot-emacs.el
1 ;;; -*- mode: emacs-lisp; coding: utf-8 -*-
2 ;;;
3 ;;; Functions and macros for .emacs
4 ;;;
5 ;;; (c) 2004 Mark Wooding
6 ;;;
7
8 ;;;----- Licensing notice ---------------------------------------------------
9 ;;;
10 ;;; This program is free software; you can redistribute it and/or modify
11 ;;; it under the terms of the GNU General Public License as published by
12 ;;; the Free Software Foundation; either version 2 of the License, or
13 ;;; (at your option) any later version.
14 ;;;
15 ;;; This program is distributed in the hope that it will be useful,
16 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;;; GNU General Public License for more details.
19 ;;;
20 ;;; You should have received a copy of the GNU General Public License
21 ;;; along with this program; if not, write to the Free Software Foundation,
22 ;;; Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23
24 ;;;--------------------------------------------------------------------------
25 ;;; Check command-line.
26
27 (defgroup mdw nil
28   "Customization for mdw's Emacs configuration."
29   :prefix "mdw-")
30
31 (defun mdw-check-command-line-switch (switch)
32   (let ((probe nil) (next command-line-args) (found nil))
33     (while next
34       (cond ((string= (car next) switch)
35              (setq found t)
36              (if probe (rplacd probe (cdr next))
37                (setq command-line-args (cdr next))))
38             (t
39              (setq probe next)))
40       (setq next (cdr next)))
41     found))
42
43 (defvar mdw-fast-startup nil
44   "Whether .emacs should optimize for rapid startup.
45 This may be at the expense of cool features.")
46 (setq mdw-fast-startup
47       (mdw-check-command-line-switch "--mdw-fast-startup"))
48
49 (defvar mdw-splashy-startup nil
50   "Whether to show a splash screen and related frippery.")
51 (setq mdw-splashy-startup
52       (mdw-check-command-line-switch "--mdw-splashy-startup"))
53
54 ;;;--------------------------------------------------------------------------
55 ;;; Some general utilities.
56
57 (eval-when-compile
58   (unless (fboundp 'make-regexp) (load "make-regexp"))
59   (require 'cl))
60
61 (defmacro mdw-regexps (&rest list)
62   "Turn a LIST of strings into a single regular expression at compile-time."
63   (declare (indent nil)
64            (debug 0))
65   `',(make-regexp list))
66
67 (defun mdw-wrong ()
68   "This is not the key sequence you're looking for."
69   (interactive)
70   (error "wrong button"))
71
72 (defun mdw-emacs-version-p (major &optional minor)
73   "Return non-nil if the running Emacs is at least version MAJOR.MINOR."
74   (or (> emacs-major-version major)
75       (and (= emacs-major-version major)
76            (>= emacs-minor-version (or minor 0)))))
77
78 ;; Some error trapping.
79 ;;
80 ;; If individual bits of this file go tits-up, we don't particularly want
81 ;; the whole lot to stop right there and then, because it's bloody annoying.
82
83 (defmacro trap (&rest forms)
84   "Execute FORMS without allowing errors to propagate outside."
85   (declare (indent 0)
86            (debug t))
87   `(condition-case err
88        ,(if (cdr forms) (cons 'progn forms) (car forms))
89      (error (message "Error (trapped): %s in %s"
90                      (error-message-string err)
91                      ',forms))))
92
93 ;; Configuration reading.
94
95 (defvar mdw-config nil)
96 (defun mdw-config (sym)
97   "Read the configuration variable named SYM."
98   (unless mdw-config
99     (setq mdw-config
100             (flet ((replace (what with)
101                      (goto-char (point-min))
102                      (while (re-search-forward what nil t)
103                        (replace-match with t))))
104               (with-temp-buffer
105                 (insert-file-contents "~/.mdw.conf")
106                 (replace  "^[ \t]*\\(#.*\\)?\n" "")
107                 (replace (concat "^[ \t]*"
108                                  "\\([-a-zA-Z0-9_.]*\\)"
109                                  "[ \t]*=[ \t]*"
110                                  "\\(.*[^ \t\n]\\)?"
111                                  "[ \t]**\\(\n\\|$\\)")
112                          "(\\1 . \"\\2\")\n")
113                 (car (read-from-string
114                       (concat "(" (buffer-string) ")")))))))
115   (cdr (assq sym mdw-config)))
116
117 ;; Width configuration.
118
119 (defcustom mdw-column-width
120   (string-to-number (or (mdw-config 'emacs-width) "77"))
121   "Width of Emacs columns."
122   :type 'integer)
123 (defcustom mdw-text-width mdw-column-width
124   "Expected width of text within columns."
125   :type 'integer
126   :safe 'integerp)
127
128 ;; Local variables hacking.
129
130 (defun run-local-vars-mode-hook ()
131   "Run a hook for the major-mode after local variables have been processed."
132   (run-hooks (intern (concat (symbol-name major-mode)
133                              "-local-variables-hook"))))
134 (add-hook 'hack-local-variables-hook 'run-local-vars-mode-hook)
135
136 ;; Set up the load path convincingly.
137
138 (dolist (dir (append (and (boundp 'debian-emacs-flavor)
139                           (list (concat "/usr/share/"
140                                         (symbol-name debian-emacs-flavor)
141                                         "/site-lisp")))))
142   (dolist (sub (directory-files dir t))
143     (when (and (file-accessible-directory-p sub)
144                (not (member sub load-path)))
145       (setq load-path (nconc load-path (list sub))))))
146
147 ;; Is an Emacs library available?
148
149 (defun library-exists-p (name)
150   "Return non-nil if NAME is an available library.
151 Return non-nil if NAME.el (or NAME.elc) somewhere on the Emacs
152 load path.  The non-nil value is the filename we found for the
153 library."
154   (let ((path load-path) elt (foundp nil))
155     (while (and path (not foundp))
156       (setq elt (car path))
157       (setq path (cdr path))
158       (setq foundp (or (let ((file (concat elt "/" name ".elc")))
159                          (and (file-exists-p file) file))
160                        (let ((file (concat elt "/" name ".el")))
161                          (and (file-exists-p file) file)))))
162     foundp))
163
164 (defun maybe-autoload (symbol file &optional docstring interactivep type)
165   "Set an autoload if the file actually exists."
166   (and (library-exists-p file)
167        (autoload symbol file docstring interactivep type)))
168
169 (defun mdw-kick-menu-bar (&optional frame)
170   "Regenerate FRAME's menu bar so it doesn't have empty menus."
171   (interactive)
172   (unless frame (setq frame (selected-frame)))
173   (let ((old (frame-parameter frame 'menu-bar-lines)))
174     (set-frame-parameter frame 'menu-bar-lines 0)
175     (set-frame-parameter frame 'menu-bar-lines old)))
176
177 ;; Page motion.
178
179 (defun mdw-fixup-page-position ()
180   (unless (eq (char-before (point)) ?\f)
181     (forward-line 0)))
182
183 (defadvice backward-page (after mdw-fixup compile activate)
184   (mdw-fixup-page-position))
185 (defadvice forward-page (after mdw-fixup compile activate)
186   (mdw-fixup-page-position))
187
188 ;; Splitting windows.
189
190 (unless (fboundp 'scroll-bar-columns)
191   (defun scroll-bar-columns (side)
192     (cond ((eq side 'left) 0)
193           (window-system 3)
194           (t 1))))
195 (unless (fboundp 'fringe-columns)
196   (defun fringe-columns (side)
197     (cond ((not window-system) 0)
198           ((eq side 'left) 1)
199           (t 2))))
200
201 (defun mdw-horizontal-window-overhead ()
202   "Computes the horizontal window overhead.
203 This is the number of columns used by fringes, scroll bars and other such
204 cruft."
205   (if (not window-system)
206       1
207     (let ((tot 0))
208       (dolist (what '(scroll-bar fringe))
209         (dolist (side '(left right))
210           (incf tot (funcall (intern (concat (symbol-name what) "-columns"))
211                              side))))
212       tot)))
213
214 (defun mdw-split-window-horizontally (&optional width)
215   "Split a window horizontally.
216 Without a numeric argument, split the window approximately in
217 half.  With a numeric argument WIDTH, allocate WIDTH columns to
218 the left-hand window (if positive) or -WIDTH columns to the
219 right-hand window (if negative).  Space for scroll bars and
220 fringes is not taken out of the allowance for WIDTH, unlike
221 \\[split-window-horizontally]."
222   (interactive "P")
223   (split-window-horizontally
224    (cond ((null width) nil)
225          ((>= width 0) (+ width (mdw-horizontal-window-overhead)))
226          ((< width 0) width))))
227
228 (defun mdw-preferred-column-width ()
229   "Return the preferred column width."
230   (if (and window-system (mdw-emacs-version-p 22)) mdw-column-width
231     (1+ mdw-column-width)))
232
233 (defun mdw-divvy-window (&optional width)
234   "Split a wide window into appropriate widths."
235   (interactive "P")
236   (setq width (if width (prefix-numeric-value width)
237                 (mdw-preferred-column-width)))
238   (let* ((win (selected-window))
239          (sb-width (mdw-horizontal-window-overhead))
240          (c (/ (+ (window-width) sb-width)
241                (+ width sb-width))))
242     (while (> c 1)
243       (setq c (1- c))
244       (split-window-horizontally (+ width sb-width))
245       (other-window 1))
246     (select-window win)))
247
248 (defun mdw-set-frame-width (columns &optional width)
249   "Set the current frame to be the correct width for COLUMNS columns.
250
251 If WIDTH is non-nil, then it provides the width for the new columns.  (This
252 can be set interactively with a prefix argument.)"
253   (interactive "nColumns: 
254 P")
255   (setq width (if width (prefix-numeric-value width)
256                 (mdw-preferred-column-width)))
257   (let ((sb-width (mdw-horizontal-window-overhead)))
258     (set-frame-width (selected-frame)
259                      (- (* columns (+ width sb-width))
260                         sb-width))
261     (mdw-divvy-window width)))
262
263 (defcustom mdw-frame-width-fudge
264   (cond ((<= emacs-major-version 20) 1)
265         ((= emacs-major-version 26) 3)
266         (t 0))
267   "The number of extra columns to add to the desired frame width.
268
269 This is sadly necessary because Emacs 26 is broken in this regard."
270   :type 'integer)
271
272 (defcustom mdw-frame-colour-alist
273   '((black . ("#000000" . "#ffffff"))
274     (red . ("#2a0000" . "#ffffff"))
275     (green . ("#002a00" . "#ffffff"))
276     (blue . ("#00002a" . "#ffffff")))
277   "Alist mapping symbol names to (FOREGROUND . BACKGROUND) colour pairs."
278   :type '(alist :key-type symbol :value-type (cons color color)))
279
280 (defun mdw-set-frame-colour (colour &optional frame)
281   (interactive "xColour name or (FOREGROUND . BACKGROUND) pair: 
282 ")
283   (when (and colour (symbolp colour))
284     (let ((entry (assq colour mdw-frame-colour-alist)))
285       (unless entry (error "Unknown colour `%s'" colour))
286       (setf colour (cdr entry))))
287   (set-frame-parameter frame 'background-color (car colour))
288   (set-frame-parameter frame 'foreground-color (cdr colour)))
289
290 ;; Window configuration switching.
291
292 (defvar mdw-current-window-configuration nil
293   "The current window configuration register name, or `nil'.")
294
295 (defun mdw-switch-window-configuration (register &optional no-save)
296   "Switch make REGISTER be the new current window configuration.
297 If a current window configuration register is established, and
298 NO-SAVE is nil, then save the current window configuration to
299 that register first.
300
301 Signal an error if the new register contains something other than
302 a window configuration.  If the register is unset then save the
303 current window configuration to it immediately.
304
305 With one or three C-u, or an odd numeric prefix argument, set
306 NO-SAVE, so the previous window configuration register is left
307 unchanged.
308
309 With two or three C-u, or a prefix argument which is an odd
310 multiple of 2, just clear the record of the current window
311 configuration register, so that the next switch doesn't save the
312 prevailing configuration."
313   (interactive
314    (let ((arg current-prefix-arg))
315      (list (if (or (and (consp arg) (= (car arg) 16) (= (car arg) 64))
316                    (and (integerp arg) (not (zerop (logand arg 2)))))
317                nil
318              (register-read-with-preview "Switch to window configuration: "))
319            (or (and (consp arg) (= (car arg) 4) (= (car arg) 64))
320                (and (integerp arg) (not (zerop (logand arg 1))))))))
321
322   (let ((current-windows (list (current-window-configuration)
323                                (point-marker)))
324         (register-value (and register (get-register register))))
325     (when (and mdw-current-window-configuration (not no-save))
326       (set-register mdw-current-window-configuration current-windows))
327     (cond ((null register)
328            (setq mdw-current-window-configuration nil))
329           ((not (or (null register-value)
330                     (and (consp register-value)
331                          (window-configuration-p (car register-value))
332                          (integer-or-marker-p (cadr register-value))
333                          (null (caddr register-value)))))
334            (error "Register `%c' is not a window configuration" register))
335           (t
336            (cond ((null register-value)
337                   (set-register register current-windows))
338                  (t
339                   (set-window-configuration (car register-value))
340                   (goto-char (cadr register-value))))
341            (setq mdw-current-window-configuration register)))))
342
343 ;; Don't raise windows unless I say so.
344
345 (defcustom mdw-inhibit-raise-frame nil
346   "Whether `raise-frame' should do nothing when the frame is mapped."
347   :type 'boolean)
348
349 (defadvice raise-frame
350     (around mdw-inhibit (&optional frame) activate compile)
351   "Don't actually do anything if `mdw-inhibit-raise-frame' is true, and the
352 frame is actually mapped on the screen."
353   (if mdw-inhibit-raise-frame
354       (make-frame-visible frame)
355     ad-do-it))
356
357 (defmacro mdw-advise-to-inhibit-raise-frame (function)
358   "Advise the FUNCTION not to raise frames, even if it wants to."
359   `(defadvice ,function
360        (around mdw-inhibit-raise (&rest hunoz) activate compile)
361      "Don't raise the window unless you have to."
362      (let ((mdw-inhibit-raise-frame t))
363        ad-do-it)))
364
365 (mdw-advise-to-inhibit-raise-frame select-frame-set-input-focus)
366 (mdw-advise-to-inhibit-raise-frame appt-disp-window)
367 (mdw-advise-to-inhibit-raise-frame mouse-select-window)
368
369 ;; Bug fix for markdown-mode, which breaks point positioning during
370 ;; `query-replace'.
371 (defadvice markdown-check-change-for-wiki-link
372     (around mdw-save-match activate compile)
373   "Save match data around the `markdown-mode' `after-change-functions' hook."
374   (save-match-data ad-do-it))
375
376 ;; Bug fix for `bbdb-canonicalize-address': on Emacs 24, `run-hook-with-args'
377 ;; always returns nil, with the result that all email addresses are lost.
378 ;; Replace the function entirely.
379 (defadvice bbdb-canonicalize-address
380     (around mdw-bug-fix activate compile)
381   "Don't use `run-hook-with-args', because that doesn't work."
382   (let ((net (ad-get-arg 0)))
383
384     ;; Make sure this is a proper hook list.
385     (if (functionp bbdb-canonicalize-net-hook)
386         (setq bbdb-canonicalize-net-hook (list bbdb-canonicalize-net-hook)))
387
388     ;; Iterate over the hooks until things converge.
389     (let ((donep nil))
390       (while (not donep)
391         (let (next (changep nil)
392               hook (hooks bbdb-canonicalize-net-hook))
393           (while hooks
394             (setq hook (pop hooks))
395             (setq next (funcall hook net))
396             (if (not (equal next net))
397                 (setq changep t
398                       net next)))
399           (setq donep (not changep)))))
400     (setq ad-return-value net)))
401
402 ;; Transient mark mode hacks.
403
404 (defadvice exchange-point-and-mark
405     (around mdw-highlight (&optional arg) activate compile)
406   "Maybe don't actually exchange point and mark.
407 If `transient-mark-mode' is on and the mark is inactive, then
408 just activate it.  A non-trivial prefix argument will force the
409 usual behaviour.  A trivial prefix argument (i.e., just C-u) will
410 activate the mark and temporarily enable `transient-mark-mode' if
411 it's currently off."
412   (cond ((or mark-active
413              (and (not transient-mark-mode) (not arg))
414              (and arg (or (not (consp arg))
415                           (not (= (car arg) 4)))))
416          ad-do-it)
417         (t
418          (or transient-mark-mode (setq transient-mark-mode 'only))
419          (set-mark (mark t)))))
420
421 ;; Functions for sexp diary entries.
422
423 (defvar mdw-diary-for-org-mode-p nil
424   "Display diary along with the agenda?")
425
426 (defun mdw-not-org-mode (form)
427   "As FORM, but not in Org mode agenda."
428   (and (not mdw-diary-for-org-mode-p)
429        (eval form)))
430
431 (defun mdw-weekday (l)
432   "Return non-nil if `date' falls on one of the days of the week in L.
433 L is a list of day numbers (from 0 to 6 for Sunday through to
434 Saturday) or symbols `sunday', `monday', etc. (or a mixture).  If
435 the date stored in `date' falls on a listed day, then the
436 function returns non-nil."
437   (let ((d (calendar-day-of-week date)))
438     (or (memq d l)
439         (memq (nth d '(sunday monday tuesday wednesday
440                               thursday friday saturday)) l))))
441
442 (defun mdw-discordian-date (date)
443   "Return the Discordian calendar date corresponding to DATE.
444
445 The return value is (YOLD . st-tibs-day) or (YOLD SEASON DAYNUM DOW).
446
447 The original is by David Pearson.  I modified it to produce date components
448 as output rather than a string."
449   (let* ((days ["Sweetmorn" "Boomtime" "Pungenday"
450                 "Prickle-Prickle" "Setting Orange"])
451          (months ["Chaos" "Discord" "Confusion"
452                   "Bureaucracy" "Aftermath"])
453          (day-count [0 31 59 90 120 151 181 212 243 273 304 334])
454          (year (- (calendar-extract-year date) 1900))
455          (month (1- (calendar-extract-month date)))
456          (day (1- (calendar-extract-day date)))
457          (julian (+ (aref day-count month) day))
458          (dyear (+ year 3066)))
459     (if (and (= month 1) (= day 28))
460         (cons dyear 'st-tibs-day)
461       (list dyear
462             (aref months (floor (/ julian 73)))
463             (1+ (mod julian 73))
464             (aref days (mod julian 5))))))
465
466 (defun mdw-diary-discordian-date ()
467   "Convert the date in `date' to a string giving the Discordian date."
468   (let* ((ddate (mdw-discordian-date date))
469          (tail (format "in the YOLD %d" (car ddate))))
470     (if (eq (cdr ddate) 'st-tibs-day)
471         (format "St Tib's Day %s" tail)
472       (let ((season (cadr ddate))
473             (daynum (caddr ddate))
474             (dayname (cadddr ddate)))
475       (format "%s, the %d%s day of %s %s"
476               dayname
477               daynum
478               (let ((ldig (mod daynum 10)))
479                 (cond ((= ldig 1) "st")
480                       ((= ldig 2) "nd")
481                       ((= ldig 3) "rd")
482                       (t "th")))
483               season
484               tail)))))
485
486 (defun mdw-todo (&optional when)
487   "Return non-nil today, or on WHEN, whichever is later."
488   (let ((w (calendar-absolute-from-gregorian (calendar-current-date)))
489         (d (calendar-absolute-from-gregorian date)))
490     (if when
491         (setq w (max w (calendar-absolute-from-gregorian
492                         (cond
493                          ((not european-calendar-style)
494                           when)
495                          ((> (car when) 100)
496                           (list (nth 1 when)
497                                 (nth 2 when)
498                                 (nth 0 when)))
499                          (t
500                           (list (nth 1 when)
501                                 (nth 0 when)
502                                 (nth 2 when))))))))
503     (eq w d)))
504
505 (defadvice org-agenda-list (around mdw-preserve-links activate)
506   (let ((mdw-diary-for-org-mode-p t))
507     ad-do-it))
508
509 (defcustom diary-time-regexp nil
510   "Regexp matching times in the diary buffer."
511   :type 'regexp)
512
513 (defadvice diary-add-to-list (before mdw-trim-leading-space compile activate)
514   "Trim leading space from the diary entry string."
515   (save-match-data
516     (let ((str (ad-get-arg 1))
517           (done nil) old)
518       (while (not done)
519         (setq old str)
520         (setq str (cond ((null str) nil)
521                         ((string-match "\\(^\\|\n\\)[ \t]+" str)
522                          (replace-match "\\1" nil nil str))
523                         ((and mdw-diary-for-org-mode-p
524                               (string-match (concat
525                                              "\\(^\\|\n\\)"
526                                              "\\(" diary-time-regexp
527                                              "\\(-" diary-time-regexp "\\)?"
528                                              "\\)"
529                                              "\\(\t[ \t]*\\| [ \t]+\\)")
530                                             str))
531                          (replace-match "\\1\\2 " nil nil str))
532                         ((and (not mdw-diary-for-org-mode-p)
533                               (string-match "\\[\\[[^][]*]\\[\\([^][]*\\)]]"
534                                             str))
535                          (replace-match "\\1" nil nil str))
536                         (t str)))
537         (if (equal str old) (setq done t)))
538       (ad-set-arg 1 str))))
539
540 (defadvice org-bbdb-anniversaries (after mdw-fixup-list compile activate)
541   "Return a string rather than a list."
542   (with-temp-buffer
543     (let ((anyp nil))
544       (dolist (e (let ((ee ad-return-value))
545                    (if (atom ee) (list ee) ee)))
546         (when e
547           (when anyp (insert ?\n))
548           (insert e)
549           (setq anyp t)))
550       (setq ad-return-value
551               (and anyp (buffer-string))))))
552
553 ;; Fighting with Org-mode's evil key maps.
554
555 (defcustom mdw-evil-keymap-keys
556   '(([S-up] . [?\C-c up])
557     ([S-down] . [?\C-c down])
558     ([S-left] . [?\C-c left])
559     ([S-right] . [?\C-c right])
560     (([M-up] [?\e up]) . [C-up])
561     (([M-down] [?\e down]) . [C-down])
562     (([M-left] [?\e left]) . [C-left])
563     (([M-right] [?\e right]) . [C-right]))
564   "Defines evil keybindings to clobber in `mdw-clobber-evil-keymap'.
565 The value is an alist mapping evil keys (as a list, or singleton)
566 to good keys (in the same form)."
567   :type '(alist :key-type (choice key-sequence (repeat key-sequence))
568                 :value-type key-sequence))
569
570 (defun mdw-clobber-evil-keymap (keymap)
571   "Replace evil key bindings in the KEYMAP.
572 Evil key bindings are defined in `mdw-evil-keymap-keys'."
573   (dolist (entry mdw-evil-keymap-keys)
574     (let ((binding nil)
575           (keys (if (listp (car entry))
576                     (car entry)
577                   (list (car entry))))
578           (replacements (if (listp (cdr entry))
579                             (cdr entry)
580                           (list (cdr entry)))))
581       (catch 'found
582         (dolist (key keys)
583           (setq binding (lookup-key keymap key))
584           (when binding
585             (throw 'found nil))))
586       (when binding
587         (dolist (key keys)
588           (define-key keymap key nil))
589         (dolist (key replacements)
590           (define-key keymap key binding))))))
591
592 (defcustom mdw-org-latex-defs
593   '(("strayman"
594      "\\documentclass{strayman}
595 \\usepackage[utf8]{inputenc}
596 \\usepackage[palatino, helvetica, courier, maths=cmr]{mdwfonts}
597 \\usepackage{graphicx, tikz, mdwtab, mdwmath, crypto, longtable}"
598      ("\\section{%s}" . "\\section*{%s}")
599      ("\\subsection{%s}" . "\\subsection*{%s}")
600      ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
601      ("\\paragraph{%s}" . "\\paragraph*{%s}")
602      ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
603   "Additional LaTeX class definitions."
604   :type '(alist :key-type string
605                 :value-type (list string
606                                   (alist :inline t
607                                          :key-type string
608                                          :value-type string))))
609
610 (eval-after-load "org-latex"
611   '(setq org-export-latex-classes
612            (append mdw-org-latex-defs org-export-latex-classes)))
613
614 (eval-after-load "ox-latex"
615   '(setq org-latex-classes (append mdw-org-latex-defs org-latex-classes)
616          org-latex-caption-above nil
617          org-latex-default-packages-alist '(("AUTO" "inputenc" t)
618                                             ("T1" "fontenc" t)
619                                             ("" "fixltx2e" nil)
620                                             ("" "graphicx" t)
621                                             ("" "longtable" nil)
622                                             ("" "float" nil)
623                                             ("" "wrapfig" nil)
624                                             ("" "rotating" nil)
625                                             ("normalem" "ulem" t)
626                                             ("" "textcomp" t)
627                                             ("" "marvosym" t)
628                                             ("" "wasysym" t)
629                                             ("" "amssymb" t)
630                                             ("" "hyperref" nil)
631                                             "\\tolerance=1000")))
632
633
634 (setq org-export-docbook-xslt-proc-command "xsltproc --output %o %s %i"
635       org-export-docbook-xsl-fo-proc-command "fop %i.safe %o"
636       org-export-docbook-xslt-stylesheet
637         "/usr/share/xml/docbook/stylesheet/docbook-xsl/fo/docbook.xsl")
638
639 ;; Glasses.
640
641 (setq glasses-separator "-"
642       glasses-separate-parentheses-p nil
643       glasses-uncapitalize-p t)
644
645 ;; Some hacks to do with window placement.
646
647 (defun mdw-clobber-other-windows-showing-buffer (buffer-or-name)
648   "Arrange that no windows on other frames are showing BUFFER-OR-NAME."
649   (interactive "bBuffer: ")
650   (let ((home-frame (selected-frame))
651         (buffer (get-buffer buffer-or-name))
652         (safe-buffer (get-buffer "*scratch*")))
653     (dolist (frame (frame-list))
654       (unless (eq frame home-frame)
655         (dolist (window (window-list frame))
656           (when (eq (window-buffer window) buffer)
657             (set-window-buffer window safe-buffer)))))))
658
659 (defvar mdw-inhibit-walk-windows nil
660   "If non-nil, then `walk-windows' does nothing.
661 This is used by advice on `switch-to-buffer-other-frame' to inhibit finding
662 buffers in random frames.")
663
664 (setq display-buffer--other-frame-action
665         '((display-buffer-reuse-window display-buffer-pop-up-frame)
666           (reusable-frames . nil)
667           (inhibit-same-window . t)))
668
669 (defadvice walk-windows (around mdw-inhibit activate)
670   "If `mdw-inhibit-walk-windows' is non-nil, then do nothing."
671   (and (not mdw-inhibit-walk-windows)
672        ad-do-it))
673
674 (defadvice switch-to-buffer-other-frame
675     (around mdw-always-new-frame activate)
676   "Always make a new frame.
677 Even if an existing window in some random frame looks tempting."
678   (let ((mdw-inhibit-walk-windows t)) ad-do-it))
679
680 (defadvice display-buffer (before mdw-inhibit-other-frames activate)
681   "Don't try to do anything fancy with other frames.
682 Pretend they don't exist.  They might be on other display devices."
683   (ad-set-arg 2 nil))
684
685 (setq even-window-sizes nil
686       even-window-heights nil)
687
688 ;; Rename buffers along with files.
689
690 (defvar mdw-inhibit-rename-buffer nil
691   "If non-nil, `rename-file' won't rename the buffer visiting the file.")
692
693 (defmacro mdw-advise-to-inhibit-rename-buffer (function)
694   "Advise FUNCTION to set `mdw-inhibit-rename-buffer' while it runs.
695
696 This will prevent `rename-file' from renaming the buffer."
697   `(defadvice ,function (around mdw-inhibit-rename-buffer compile activate)
698      "Don't rename the buffer when renaming the underlying file."
699      (let ((mdw-inhibit-rename-buffer t))
700        ad-do-it)))
701 (mdw-advise-to-inhibit-rename-buffer recode-file-name)
702 (mdw-advise-to-inhibit-rename-buffer set-visited-file-name)
703 (mdw-advise-to-inhibit-rename-buffer backup-buffer)
704
705 (defadvice rename-file (after mdw-rename-buffers (from to &optional forcep)
706                         compile activate)
707   "If a buffer is visiting the file, rename it to match the new name.
708
709 Don't do this if `mdw-inhibit-rename-buffer' is non-nil."
710   (unless mdw-inhibit-rename-buffer
711     (let ((buffer (get-file-buffer from)))
712       (when buffer
713         (let ((to (if (not (string= (file-name-nondirectory to) "")) to
714                     (concat to (file-name-nondirectory from)))))
715           (with-current-buffer buffer
716             (set-visited-file-name to nil t)))))))
717
718 ;;;--------------------------------------------------------------------------
719 ;;; Improved compilation machinery.
720
721 ;; Uprated version of M-x compile.
722
723 (setq compile-command
724         (let ((ncpu (with-temp-buffer
725                       (insert-file-contents "/proc/cpuinfo")
726                       (buffer-string)
727                       (count-matches "^processor\\s-*:"))))
728           (format "nice make -j%d -k" (* 2 ncpu))))
729
730 (defun mdw-compilation-buffer-name (mode)
731   (concat "*" (downcase mode) ": "
732           (abbreviate-file-name default-directory) "*"))
733 (setq compilation-buffer-name-function 'mdw-compilation-buffer-name)
734
735 (eval-after-load "compile"
736   '(progn
737      (define-key compilation-shell-minor-mode-map "\C-c\M-g" 'recompile)))
738
739 (defadvice compile (around hack-environment compile activate)
740   "Hack the environment inherited by inferiors in the compilation."
741   (let ((process-environment (copy-tree process-environment)))
742     (setenv "LD_PRELOAD" nil)
743     ad-do-it))
744
745 (defun mdw-compile (command &optional directory comint)
746   "Initiate a compilation COMMAND, maybe in a different DIRECTORY.
747 The DIRECTORY may be nil to not change.  If COMINT is t, then
748 start an interactive compilation.
749
750 Interactively, prompt for the command if the variable
751 `compilation-read-command' is non-nil, or if requested through
752 the prefix argument.  Prompt for the directory, and run
753 interactively, if requested through the prefix.
754
755 Use a prefix of 4, 6, 12, or 14, or type C-u between one and three times, to
756 force prompting for a directory.
757
758 Use a prefix of 2, 6, 10, or 14, or type C-u three times, to force
759 prompting for the command.
760
761 Use a prefix of 8, 10, 12, or 14, or type C-u twice or three times,
762 to force interactive compilation."
763   (interactive
764    (let* ((prefix (prefix-numeric-value current-prefix-arg))
765           (command (eval compile-command))
766           (dir (and (plusp (logand prefix #x54))
767                     (read-directory-name "Compile in directory: "))))
768      (list (if (or compilation-read-command
769                    (plusp (logand prefix #x42)))
770                (compilation-read-command command)
771              command)
772            dir
773            (plusp (logand prefix #x58)))))
774   (let ((default-directory (or directory default-directory)))
775     (compile command comint)))
776
777 ;; Flymake support.
778
779 (defun mdw-find-build-dir (build-file)
780   (catch 'found
781     (let* ((src-dir (file-name-as-directory (expand-file-name ".")))
782            (dir src-dir))
783       (loop
784         (when (file-exists-p (concat dir build-file))
785           (throw 'found dir))
786         (let ((sub (expand-file-name (file-relative-name src-dir dir)
787                                      (concat dir "build/"))))
788           (catch 'give-up
789             (loop
790               (when (file-exists-p (concat sub build-file))
791                 (throw 'found sub))
792               (when (string= sub dir) (throw 'give-up nil))
793               (setq sub (file-name-directory (directory-file-name sub))))))
794         (when (string= dir
795                        (setq dir (file-name-directory
796                                   (directory-file-name dir))))
797           (throw 'found nil))))))
798
799 (defun mdw-flymake-make-init ()
800   (let ((build-dir (mdw-find-build-dir "Makefile")))
801     (and build-dir
802          (let ((tmp-src (flymake-init-create-temp-buffer-copy
803                          #'flymake-create-temp-inplace)))
804            (flymake-get-syntax-check-program-args
805             tmp-src build-dir t t
806             #'flymake-get-make-cmdline)))))
807
808 (setq flymake-allowed-file-name-masks
809         '(("\\.\\(?:[cC]\\|cc\\|cpp\\|cxx\\|c\\+\\+\\)\\'"
810            mdw-flymake-make-init)
811           ("\\.\\(?:[hH]\\|hh\\|hpp\\|hxx\\|h\\+\\+\\)\\'"
812            mdw-flymake-master-make-init)
813           ("\\.p[lm]" flymake-perl-init)))
814
815 (setq flymake-mode-map
816         (let ((map (if (boundp 'flymake-mode-map)
817                        flymake-mode-map
818                      (make-sparse-keymap))))
819           (define-key map [?\C-c ?\C-f ?\C-p] 'flymake-goto-prev-error)
820           (define-key map [?\C-c ?\C-f ?\C-n] 'flymake-goto-next-error)
821           (define-key map [?\C-c ?\C-f ?\C-c] 'flymake-compile)
822           (define-key map [?\C-c ?\C-f ?\C-k] 'flymake-stop-all-syntax-checks)
823           (define-key map [?\C-c ?\C-f ?\C-e] 'flymake-popup-current-error-menu)
824           map))
825
826 ;;;--------------------------------------------------------------------------
827 ;;; Mail and news hacking.
828
829 (define-derived-mode  mdwmail-mode mail-mode "[mdw] mail"
830   "Major mode for editing news and mail messages from external programs.
831 Not much right now.  Just support for doing MailCrypt stuff."
832   :syntax-table nil
833   :abbrev-table nil
834   (run-hooks 'mail-setup-hook))
835
836 (define-key mdwmail-mode-map [?\C-c ?\C-c] 'disabled-operation)
837
838 (add-hook 'mdwail-mode-hook
839           (lambda ()
840             (set-buffer-file-coding-system 'utf-8)
841             (make-local-variable 'paragraph-separate)
842             (make-local-variable 'paragraph-start)
843             (setq paragraph-start
844                     (concat "[ \t]*[-_][-_][-_]+$\\|^-- \\|-----\\|"
845                             paragraph-start))
846             (setq paragraph-separate
847                   (concat "[ \t]*[-_][-_][-_]+$\\|^-- \\|-----\\|"
848                           paragraph-separate))))
849
850 ;; How to encrypt in mdwmail.
851
852 (defun mdwmail-mc-encrypt (&optional recip scm start end from sign)
853   (or start
854       (setq start (save-excursion
855                     (goto-char (point-min))
856                     (or (search-forward "\n\n" nil t) (point-min)))))
857   (or end
858       (setq end (point-max)))
859   (mc-encrypt-generic recip scm start end from sign))
860
861 ;; How to sign in mdwmail.
862
863 (defun mdwmail-mc-sign (key scm start end uclr)
864   (or start
865       (setq start (save-excursion
866                     (goto-char (point-min))
867                     (or (search-forward "\n\n" nil t) (point-min)))))
868   (or end
869       (setq end (point-max)))
870   (mc-sign-generic key scm start end uclr))
871
872 ;; Some signature mangling.
873
874 (defun mdwmail-mangle-signature ()
875   (save-excursion
876     (goto-char (point-min))
877     (perform-replace "\n-- \n" "\n-- " nil nil nil)))
878 (add-hook 'mail-setup-hook 'mdwmail-mangle-signature)
879 (add-hook 'message-setup-hook 'mdwmail-mangle-signature)
880
881 ;; Insert my login name into message-ids, so I can score replies.
882
883 (defadvice message-unique-id (after mdw-user-name last activate compile)
884   "Ensure that the user's name appears at the end of the message-id string,
885 so that it can be used for convenient filtering."
886   (setq ad-return-value (concat ad-return-value "." (user-login-name))))
887
888 ;; Tell my movemail hack where movemail is.
889 ;;
890 ;; This is needed to shup up warnings about LD_PRELOAD.
891
892 (let ((path exec-path))
893   (while path
894     (let ((try (expand-file-name "movemail" (car path))))
895       (if (file-executable-p try)
896           (setenv "REAL_MOVEMAIL" try))
897       (setq path (cdr path)))))
898
899 ;; AUTHINFO GENERIC kludge.
900
901 (defcustom nntp-authinfo-generic nil
902   "Set to the `NNTPAUTH' string to pass on to `authinfo-kludge'.
903
904 Use this to arrange for per-server settings."
905   :type '(choice (const :tag "Use `NNTPAUTH' environment variable" nil)
906                  string)
907   :safe 'stringp)
908
909 (defun nntp-open-authinfo-kludge (buffer)
910   "Open a connection to SERVER using `authinfo-kludge'."
911   (let ((proc (start-process "nntpd" buffer
912                              "env" (concat "NNTPAUTH="
913                                            (or nntp-authinfo-generic
914                                                (getenv "NNTPAUTH")
915                                                (error "NNTPAUTH unset")))
916                              "authinfo-kludge" nntp-address)))
917     (set-buffer buffer)
918     (nntp-wait-for-string "^\r*200")
919     (beginning-of-line)
920     (delete-region (point-min) (point))
921     proc))
922
923 (eval-after-load "erc"
924   '(load "~/.ercrc.el"))
925
926 ;; Heavy-duty Gnus patching.
927
928 (defun mdw-nnimap-transform-headers ()
929   (goto-char (point-min))
930   (let (article lines size string)
931     (block nil
932       (while (not (eobp))
933         (while (not (looking-at "\\* [0-9]+ FETCH"))
934           (delete-region (point) (progn (forward-line 1) (point)))
935           (when (eobp)
936             (return)))
937         (goto-char (match-end 0))
938         ;; Unfold quoted {number} strings.
939         (while (re-search-forward
940                 "[^]][ (]{\\([0-9]+\\)}\r?\n"
941                 (save-excursion
942                   ;; Start of the header section.
943                   (or (re-search-forward "] {[0-9]+}\r?\n" nil t)
944                       ;; Start of the next FETCH.
945                       (re-search-forward "\\* [0-9]+ FETCH" nil t)
946                       (point-max)))
947                 t)
948           (setq size (string-to-number (match-string 1)))
949           (delete-region (+ (match-beginning 0) 2) (point))
950           (setq string (buffer-substring (point) (+ (point) size)))
951           (delete-region (point) (+ (point) size))
952           (insert (format "%S" (subst-char-in-string ?\n ?\s string)))
953           ;; [mdw] missing from upstream
954           (backward-char 1))
955         (beginning-of-line)
956         (setq article
957                 (and (re-search-forward "UID \\([0-9]+\\)"
958                                         (line-end-position)
959                                         t)
960                      (match-string 1)))
961         (setq lines nil)
962         (setq size
963                 (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
964                                         (line-end-position)
965                                         t)
966                      (match-string 1)))
967         (beginning-of-line)
968         (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
969           (let ((structure (ignore-errors
970                              (read (current-buffer)))))
971             (while (and (consp structure)
972                         (not (atom (car structure))))
973               (setq structure (car structure)))
974             (setq lines (if (and
975                              (stringp (car structure))
976                              (equal (upcase (nth 0 structure)) "MESSAGE")
977                              (equal (upcase (nth 1 structure)) "RFC822"))
978                             (nth 9 structure)
979                           (nth 7 structure)))))
980         (delete-region (line-beginning-position) (line-end-position))
981         (insert (format "211 %s Article retrieved." article))
982         (forward-line 1)
983         (when size
984           (insert (format "Chars: %s\n" size)))
985         (when lines
986           (insert (format "Lines: %s\n" lines)))
987         ;; Most servers have a blank line after the headers, but
988         ;; Davmail doesn't.
989         (unless (re-search-forward "^\r$\\|^)\r?$" nil t)
990           (goto-char (point-max)))
991         (delete-region (line-beginning-position) (line-end-position))
992         (insert ".")
993         (forward-line 1)))))
994
995 (eval-after-load 'nnimap
996   '(defalias 'nnimap-transform-headers
997      (symbol-function 'mdw-nnimap-transform-headers)))
998
999 (defadvice gnus-other-frame (around mdw-hack-frame-width compile activate)
1000   "Always arrange for mail/news frames to be 80 columns wide."
1001   (let ((default-frame-alist (cons `(width . ,(+ 80 mdw-frame-width-fudge))
1002                                    (cl-delete 'width default-frame-alist
1003                                               :key #'car))))
1004     ad-do-it))
1005
1006 ;; Preferred programs.
1007
1008 (setq mailcap-user-mime-data
1009         '(((type . "application/pdf") (viewer . "mupdf %s"))))
1010
1011 ;;;--------------------------------------------------------------------------
1012 ;;; Utility functions.
1013
1014 (or (fboundp 'line-number-at-pos)
1015     (defun line-number-at-pos (&optional pos)
1016       (let ((opoint (or pos (point))) start)
1017         (save-excursion
1018           (save-restriction
1019             (goto-char (point-min))
1020             (widen)
1021             (forward-line 0)
1022             (setq start (point))
1023             (goto-char opoint)
1024             (forward-line 0)
1025             (1+ (count-lines 1 (point))))))))
1026
1027 (defun mdw-uniquify-alist (&rest alists)
1028   "Return the concatenation of the ALISTS with duplicate elements removed.
1029 The first association with a given key prevails; others are
1030 ignored.  The input lists are not modified, although they'll
1031 probably become garbage."
1032   (and alists
1033        (let ((start-list (cons nil nil)))
1034          (mdw-do-uniquify start-list
1035                           start-list
1036                           (car alists)
1037                           (cdr alists)))))
1038
1039 (defun mdw-do-uniquify (done end l rest)
1040   "A helper function for mdw-uniquify-alist.
1041 The DONE argument is a list whose first element is `nil'.  It
1042 contains the uniquified alist built so far.  The leading `nil' is
1043 stripped off at the end of the operation; it's only there so that
1044 DONE always references a cons cell.  END refers to the final cons
1045 cell in the DONE list; it is modified in place each time to avoid
1046 the overheads of `append'ing all the time.  The L argument is the
1047 alist we're currently processing; the remaining alists are given
1048 in REST."
1049
1050   ;; There are several different cases to deal with here.
1051   (cond
1052
1053    ;; Current list isn't empty.  Add the first item to the DONE list if
1054    ;; there's not an item with the same KEY already there.
1055    (l (or (assoc (car (car l)) done)
1056           (progn
1057             (setcdr end (cons (car l) nil))
1058             (setq end (cdr end))))
1059       (mdw-do-uniquify done end (cdr l) rest))
1060
1061    ;; The list we were working on is empty.  Shunt the next list into the
1062    ;; current list position and go round again.
1063    (rest (mdw-do-uniquify done end (car rest) (cdr rest)))
1064
1065    ;; Everything's done.  Remove the leading `nil' from the DONE list and
1066    ;; return it.  Finished!
1067    (t (cdr done))))
1068
1069 (defun date ()
1070   "Insert the current date in a pleasing way."
1071   (interactive)
1072   (insert (save-excursion
1073             (let ((buffer (get-buffer-create "*tmp*")))
1074               (unwind-protect (progn (set-buffer buffer)
1075                                      (erase-buffer)
1076                                      (shell-command "date +%Y-%m-%d" t)
1077                                      (goto-char (mark))
1078                                      (delete-char -1)
1079                                      (buffer-string))
1080                 (kill-buffer buffer))))))
1081
1082 (defun uuencode (file &optional name)
1083   "UUencodes a file, maybe calling it NAME, into the current buffer."
1084   (interactive "fInput file name: ")
1085
1086   ;; If NAME isn't specified, then guess from the filename.
1087   (if (not name)
1088       (setq name
1089             (substring file
1090                        (or (string-match "[^/]*$" file) 0))))
1091   (print (format "uuencode `%s' `%s'" file name))
1092
1093   ;; Now actually do the thing.
1094   (call-process "uuencode" file t nil name))
1095
1096 (defcustom np-file "~/.np"
1097   "Where the `now-playing' file is."
1098   :type 'file
1099   :safe 'stringp)
1100
1101 (defun np (&optional arg)
1102   "Grabs a `now-playing' string."
1103   (interactive)
1104   (save-excursion
1105     (or arg (progn
1106               (goto-char (point-max))
1107               (insert "\nNP: ")
1108               (insert-file-contents np-file)))))
1109
1110 (defun mdw-version-< (ver-a ver-b)
1111   "Answer whether VER-A is strictly earlier than VER-B.
1112 VER-A and VER-B are version numbers, which are strings containing digit
1113 sequences separated by `.'."
1114   (let* ((la (mapcar (lambda (x) (car (read-from-string x)))
1115                      (split-string ver-a "\\.")))
1116          (lb (mapcar (lambda (x) (car (read-from-string x)))
1117                      (split-string ver-b "\\."))))
1118     (catch 'done
1119       (while t
1120         (cond ((null la) (throw 'done lb))
1121               ((null lb) (throw 'done nil))
1122               ((< (car la) (car lb)) (throw 'done t))
1123               ((= (car la) (car lb)) (setq la (cdr la) lb (cdr lb)))
1124               (t (throw 'done nil)))))))
1125
1126 (defun mdw-check-autorevert ()
1127   "Sets global-auto-revert-ignore-buffer appropriately for this buffer.
1128 This takes into consideration whether it's been found using
1129 tramp, which seems to get itself into a twist."
1130   (cond ((not (boundp 'global-auto-revert-ignore-buffer))
1131          nil)
1132         ((and (buffer-file-name)
1133               (fboundp 'tramp-tramp-file-p)
1134               (tramp-tramp-file-p (buffer-file-name)))
1135          (unless global-auto-revert-ignore-buffer
1136            (setq global-auto-revert-ignore-buffer 'tramp)))
1137         ((eq global-auto-revert-ignore-buffer 'tramp)
1138          (setq global-auto-revert-ignore-buffer nil))))
1139
1140 (defadvice find-file (after mdw-autorevert activate)
1141   (mdw-check-autorevert))
1142 (defadvice write-file (after mdw-autorevert activate)
1143   (mdw-check-autorevert))
1144
1145 (defun mdw-auto-revert ()
1146   "Recheck all of the autorevertable buffers, and update VC modelines."
1147   (interactive)
1148   (let ((auto-revert-check-vc-info t))
1149     (auto-revert-buffers)))
1150
1151 ;;;--------------------------------------------------------------------------
1152 ;;; Dired hacking.
1153
1154 (defadvice dired-maybe-insert-subdir
1155     (around mdw-marked-insertion first activate)
1156   "The DIRNAME may be a list of directory names to insert.
1157 Interactively, if files are marked, then insert all of them.
1158 With a numeric prefix argument, select that many entries near
1159 point; with a non-numeric prefix argument, prompt for listing
1160 options."
1161   (interactive
1162    (list (dired-get-marked-files nil
1163                                  (and (integerp current-prefix-arg)
1164                                       current-prefix-arg)
1165                                  #'file-directory-p)
1166          (and current-prefix-arg
1167               (not (integerp current-prefix-arg))
1168               (read-string "Switches for listing: "
1169                            (or dired-subdir-switches
1170                                dired-actual-switches)))))
1171   (let ((dirs (ad-get-arg 0)))
1172     (dolist (dir (if (listp dirs) dirs (list dirs)))
1173       (ad-set-arg 0 dir)
1174       ad-do-it)))
1175
1176 (defun mdw-dired-run (args &optional syncp)
1177   (interactive (let ((file (dired-get-filename t)))
1178                  (list (read-string (format "Arguments for %s: " file))
1179                        current-prefix-arg)))
1180   (funcall (if syncp 'shell-command 'async-shell-command)
1181            (concat (shell-quote-argument (dired-get-filename nil))
1182                    " " args)))
1183
1184 (defadvice dired-do-flagged-delete
1185     (around mdw-delete-if-prefix-argument activate compile)
1186   (let ((delete-by-moving-to-trash (and (null current-prefix-arg)
1187                                         delete-by-moving-to-trash)))
1188     ad-do-it))
1189
1190 (eval-after-load "dired"
1191   '(define-key dired-mode-map "X" 'mdw-dired-run))
1192
1193 ;;;--------------------------------------------------------------------------
1194 ;;; URL viewing.
1195
1196 (defun mdw-w3m-browse-url (url &optional new-session-p)
1197   "Invoke w3m on the URL in its current window, or at least a different one.
1198 If NEW-SESSION-P, start a new session."
1199   (interactive "sURL: \nP")
1200   (save-excursion
1201     (let ((window (selected-window)))
1202       (unwind-protect
1203           (progn
1204             (select-window (or (and (not new-session-p)
1205                                     (get-buffer-window "*w3m*"))
1206                                (progn
1207                                  (if (one-window-p t) (split-window))
1208                                  (get-lru-window))))
1209             (w3m-browse-url url new-session-p))
1210         (select-window window)))))
1211
1212 (eval-after-load 'w3m
1213   '(define-key w3m-mode-map [?\e ?\r] 'w3m-view-this-url-new-session))
1214
1215 (defcustom mdw-good-url-browsers
1216   '(browse-url-mozilla
1217     browse-url-generic
1218     (w3m . mdw-w3m-browse-url)
1219     browse-url-w3)
1220   "List of good browsers for mdw-good-url-browsers.
1221 Each item is a browser function name, or a cons (CHECK . FUNC).
1222 A symbol FOO stands for (FOO . FOO)."
1223   :type '(repeat (choice function (cons function function))))
1224
1225 (defun mdw-good-url-browser ()
1226   "Return a good URL browser.
1227 Trundle the list of such things, finding the first item for which
1228 CHECK is fboundp, and returning the correponding FUNC."
1229   (let ((bs mdw-good-url-browsers) b check func answer)
1230     (while (and bs (not answer))
1231       (setq b (car bs)
1232             bs (cdr bs))
1233       (if (consp b)
1234           (setq check (car b) func (cdr b))
1235         (setq check b func b))
1236       (if (fboundp check)
1237           (setq answer func)))
1238     answer))
1239
1240 (eval-after-load "w3m-search"
1241   '(progn
1242      (dolist
1243          (item
1244           '(("g" "Google" "http://www.google.co.uk/search?q=%s")
1245             ("gd" "Google Directory"
1246              "http://www.google.com/search?cat=gwd/Top&q=%s")
1247             ("gg" "Google Groups" "http://groups.google.com/groups?q=%s")
1248             ("ward" "Ward's wiki" "http://c2.com/cgi/wiki?%s")
1249             ("gi" "Images" "http://images.google.com/images?q=%s")
1250             ("rfc" "RFC"
1251              "http://metalzone.distorted.org.uk/ftp/pub/mirrors/rfc/rfc%s.txt.gz")
1252             ("wp" "Wikipedia"
1253              "http://en.wikipedia.org/wiki/Special:Search?go=Go&search=%s")
1254             ("imdb" "IMDb" "http://www.imdb.com/Find?%s")
1255             ("nc-wiki" "nCipher wiki"
1256              "http://wiki.ncipher.com/wiki/bin/view/Devel/?topic=%s")
1257             ("map" "Google maps" "http://maps.google.co.uk/maps?q=%s&hl=en")
1258             ("lp" "Launchpad bug by number"
1259              "https://bugs.launchpad.net/bugs/%s")
1260             ("lppkg" "Launchpad bugs by package"
1261              "https://bugs.launchpad.net/%s")
1262             ("msdn" "MSDN"
1263              "http://social.msdn.microsoft.com/Search/en-GB/?query=%s&ac=8")
1264             ("debbug" "Debian bug by number"
1265              "http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=%s")
1266             ("debbugpkg" "Debian bugs by package"
1267              "http://bugs.debian.org/cgi-bin/pkgreport.cgi?pkg=%s")
1268             ("ljlogin" "LJ login" "http://www.livejournal.com/login.bml")))
1269        (add-to-list 'w3m-search-engine-alist
1270                     (list (cadr item) (caddr item) nil))
1271        (add-to-list 'w3m-uri-replace-alist
1272                     (list (concat "\\`" (car item) ":")
1273                           'w3m-search-uri-replace
1274                           (cadr item))))))
1275
1276 ;;;--------------------------------------------------------------------------
1277 ;;; Paragraph filling.
1278
1279 ;; Useful variables.
1280
1281 (defcustom mdw-fill-prefix nil
1282   "Used by `mdw-line-prefix' and `mdw-fill-paragraph'.
1283 If there's no fill prefix currently set (by the `fill-prefix'
1284 variable) and there's a match from one of the regexps here, it
1285 gets used to set the fill-prefix for the current operation.
1286
1287 The variable is a list of items of the form `PATTERN . PREFIX'; if
1288 the PATTERN matches, the PREFIX is used to set the fill prefix.
1289
1290 A PATTERN is one of the following.
1291
1292   * STRING -- a regular expression, expected to match at point
1293   * (eval . FORM) -- a Lisp form which must evaluate non-nil
1294   * (if COND CONSEQ-PAT ALT-PAT) -- if COND evaluates non-nil, must match
1295     CONSEQ-PAT; otherwise must match ALT-PAT
1296   * (and PATTERN ...) -- must match all of the PATTERNs
1297   * (or PATTERN ...) -- must match at least one PATTERN
1298   * (not PATTERN) -- mustn't match (probably not useful)
1299
1300 A PREFIX is a list of the following kinds of things:
1301
1302   * STRING -- insert a literal string
1303   * (match . N) -- insert the thing matched by bracketed subexpression N
1304   * (pad . N) -- a string of whitespace the same width as subexpression N
1305   * (expr . FORM) -- the result of evaluating FORM
1306
1307 Information about `bracketed subexpressions' comes from the match data,
1308 as modified during matching.")
1309
1310 (make-variable-buffer-local 'mdw-fill-prefix)
1311
1312 (defcustom mdw-hanging-indents
1313   (concat "\\(\\("
1314             "\\([*o+]\\|-[-#]?\\|[0-9]+\\.\\|\\[[0-9]+\\]\\|([a-zA-Z])\\)"
1315             "[ \t]+"
1316           "\\)?\\)")
1317   "Standard regexp matching parts of a hanging indent.
1318 This is mainly useful in `auto-fill-mode'."
1319   :type 'regexp)
1320
1321 ;; Utility functions.
1322
1323 (defun mdw-maybe-tabify (s)
1324   "Tabify or untabify the string S, according to `indent-tabs-mode'."
1325   (let ((tabfun (if indent-tabs-mode #'tabify #'untabify)))
1326     (with-temp-buffer
1327       (save-match-data
1328         (insert s "\n")
1329         (let ((start (point-min)) (end (point-max)))
1330           (funcall tabfun (point-min) (point-max))
1331           (setq s (buffer-substring (point-min) (1- (point-max)))))))))
1332
1333 (defun mdw-fill-prefix-match-p (pat)
1334   "Return non-nil if PAT matches at the current position."
1335   (cond ((stringp pat) (looking-at pat))
1336         ((not (consp pat)) (error "Unknown pattern item `%S'" pat))
1337         ((eq (car pat) 'eval) (eval (cdr pat)))
1338         ((eq (car pat) 'if)
1339          (if (or (null (cdr pat))
1340                  (null (cddr pat))
1341                  (null (cdddr pat))
1342                  (cddddr pat))
1343              (error "Invalid `if' pattern `%S'" pat))
1344          (mdw-fill-prefix-match-p (if (eval (cadr pat))
1345                                       (caddr pat)
1346                                     (cadddr pat))))
1347         ((eq (car pat) 'and)
1348          (let ((pats (cdr pat))
1349                (ok t))
1350            (while (and pats
1351                        (or (mdw-fill-prefix-match-p (car pats))
1352                            (setq ok nil)))
1353              (setq pats (cdr pats)))
1354            ok))
1355         ((eq (car pat) 'or)
1356          (let ((pats (cdr pat))
1357                (ok nil))
1358            (while (and pats
1359                        (or (not (mdw-fill-prefix-match-p (car pats)))
1360                            (progn (setq ok t) nil)))
1361              (setq pats (cdr pats)))
1362            ok))
1363         ((eq (car pat) 'not)
1364          (if (or (null (cdr pat)) (cddr pat))
1365              (error "Invalid `not' pattern `%S'" pat))
1366          (not (mdw-fill-prefix-match-p (car pats))))
1367         (t (error "Unknown pattern form `%S'" pat))))
1368
1369 (defun mdw-maybe-car (p)
1370   "If P is a pair, return (car P), otherwise just return P."
1371   (if (consp p) (car p) p))
1372
1373 (defun mdw-padding (s)
1374   "Return a string the same width as S but made entirely from whitespace."
1375   (let* ((l (length s)) (i 0) (n (make-string l ? )))
1376     (while (< i l)
1377       (if (= 9 (aref s i))
1378           (aset n i 9))
1379       (setq i (1+ i)))
1380     n))
1381
1382 (defun mdw-do-prefix-match (m)
1383   "Expand a dynamic prefix match element.
1384 See `mdw-fill-prefix' for details."
1385   (cond ((not (consp m)) (format "%s" m))
1386         ((eq (car m) 'match) (match-string (mdw-maybe-car (cdr m))))
1387         ((eq (car m) 'pad) (mdw-padding (match-string
1388                                          (mdw-maybe-car (cdr m)))))
1389         ((eq (car m) 'eval) (eval (cdr m)))
1390         (t "")))
1391
1392 (defun mdw-examine-fill-prefixes (l)
1393   "Given a list of dynamic fill prefixes, pick one which matches
1394 context and return the static fill prefix to use.  Point must be
1395 at the start of a line, and match data must be saved."
1396   (let ((prefix nil))
1397     (while (cond ((null l) nil)
1398                  ((mdw-fill-prefix-match-p (caar l))
1399                   (setq prefix
1400                           (mdw-maybe-tabify
1401                            (apply #'concat
1402                                   (mapcar #'mdw-do-prefix-match
1403                                           (cdr (car l))))))
1404                   nil))
1405       (setq l (cdr l)))
1406     prefix))
1407
1408 (defun mdw-choose-dynamic-fill-prefix ()
1409   "Work out the dynamic fill prefix based on the variable `mdw-fill-prefix'."
1410   (cond ((and fill-prefix (not (string= fill-prefix ""))) fill-prefix)
1411         ((not mdw-fill-prefix) fill-prefix)
1412         (t (save-excursion
1413              (beginning-of-line)
1414              (save-match-data
1415                (mdw-examine-fill-prefixes mdw-fill-prefix))))))
1416
1417 (defadvice do-auto-fill (around mdw-dynamic-fill-prefix () activate compile)
1418   "Handle auto-filling, working out a dynamic fill prefix in the
1419 case where there isn't a sensible static one."
1420   (let ((fill-prefix (mdw-choose-dynamic-fill-prefix)))
1421     ad-do-it))
1422
1423 (defun mdw-fill-paragraph ()
1424   "Fill paragraph, getting a dynamic fill prefix."
1425   (interactive)
1426   (let ((fill-prefix (mdw-choose-dynamic-fill-prefix)))
1427     (fill-paragraph nil)))
1428
1429 (defun mdw-point-within-string-p ()
1430   "Return non-nil if point is within a string."
1431   (let ((state (syntax-ppss)))
1432     (elt state 3)))
1433
1434 (defun mdw-standard-fill-prefix (rx &optional mat)
1435   "Set the dynamic fill prefix, handling standard hanging indents and stuff.
1436 This is just a short-cut for setting the thing by hand, and by
1437 design it doesn't cope with anything approximating a complicated
1438 case."
1439   (setq mdw-fill-prefix
1440           `(((if (mdw-point-within-string-p)
1441                  ,(concat "\\(\\s-*\\)" mdw-hanging-indents)
1442                ,(concat rx mdw-hanging-indents))
1443              (match . 1)
1444              (pad . ,(or mat 2))))))
1445
1446 ;;;--------------------------------------------------------------------------
1447 ;;; Printing.
1448
1449 ;; Teach PostScript about a condensed variant of Courier.  I'm using 85% of
1450 ;; the usual width, which happens to match `mdwfonts', and David Carlisle's
1451 ;; `pslatex'.  (Once upon a time, I used 80%, but decided consistency with
1452 ;; `pslatex' was useful.)
1453 (setq ps-user-defined-prologue "
1454 /CourierCondensed /Courier
1455 /CourierCondensed-Bold /Courier-Bold
1456 /CourierCondensed-Oblique /Courier-Oblique
1457 /CourierCondensed-BoldOblique /Courier-BoldOblique
1458   4 { findfont [0.85 0 0 1 0 0] makefont definefont pop } repeat
1459 ")
1460
1461 ;; Hack `ps-print''s settings.
1462 (eval-after-load 'ps-print
1463   '(progn
1464
1465      ;; Notice that the comment-delimiters should be in italics too.
1466      (pushnew 'font-lock-comment-delimiter-face ps-italic-faces)
1467
1468      ;; Select more suitable colours for the main kinds of tokens.  The
1469      ;; colours set on the Emacs faces are chosen for use against a dark
1470      ;; background, and work very badly on white paper.
1471      (ps-extend-face '(font-lock-comment-face "darkgreen" nil italic))
1472      (ps-extend-face '(font-lock-comment-delimiter-face "darkgreen" nil italic))
1473      (ps-extend-face '(font-lock-string-face "RoyalBlue4" nil))
1474      (ps-extend-face '(mdw-punct-face "sienna" nil))
1475      (ps-extend-face '(mdw-number-face "OrangeRed3" nil))
1476
1477      ;; Teach `ps-print' about my condensed varsions of Courier.
1478      (setq ps-font-info-database
1479              (append '((CourierCondensed
1480                         (fonts (normal . "CourierCondensed")
1481                                (bold . "CourierCondensed-Bold")
1482                                (italic . "CourierCondensed-Oblique")
1483                                (bold-italic . "CourierCondensed-BoldOblique"))
1484                         (size . 10.0)
1485                         (line-height . 10.55)
1486                         (space-width . 5.1)
1487                         (avg-char-width . 5.1)))
1488                      (cl-remove 'CourierCondensed ps-font-info-database
1489                                 :key #'car)))))
1490
1491 ;; Arrange to strip overlays from the buffer before we print .  This will
1492 ;; prevent `flyspell' from interfering with the printout.  (It would be less
1493 ;; bad if `ps-print' could merge the `flyspell' overlay face with the
1494 ;; underlying `font-lock' face, but it can't (and that seems hard).  So
1495 ;; instead we have this hack.
1496 ;;
1497 ;; The basic trick is to copy the relevant text from the buffer being printed
1498 ;; into a temporary buffer and... just print that.  The text properties come
1499 ;; with the text and end up in the new buffer, and the overlays get lost
1500 ;; along the way.  Only problem is that the headers identifying the file
1501 ;; being printed get confused, so remember the original buffer and reinstate
1502 ;; it when constructing the headers.
1503 (defvar mdw-printing-buffer)
1504
1505 (defadvice ps-generate-header
1506     (around mdw-use-correct-buffer () activate compile)
1507   "Print the correct name of the buffer being printed."
1508   (with-current-buffer mdw-printing-buffer
1509     ad-do-it))
1510
1511 (defadvice ps-generate
1512     (around mdw-strip-overlays (buffer from to genfunc) activate compile)
1513   "Strip overlays -- in particular, from `flyspell' -- before printout."
1514   (with-temp-buffer
1515     (let ((mdw-printing-buffer buffer))
1516       (insert-buffer-substring buffer from to)
1517       (ad-set-arg 0 (current-buffer))
1518       (ad-set-arg 1 (point-min))
1519       (ad-set-arg 2 (point-max))
1520       ad-do-it)))
1521
1522 ;;;--------------------------------------------------------------------------
1523 ;;; Other common declarations.
1524
1525 ;; Common mode settings.
1526
1527 (defcustom mdw-auto-indent t
1528   "Whether to indent automatically after a newline."
1529   :type 'boolean
1530   :safe 'booleanp)
1531
1532 (defun mdw-whitespace-mode (&optional arg)
1533   "Turn on/off whitespace mode, but don't highlight trailing space."
1534   (interactive "P")
1535   (when (and (boundp 'whitespace-style)
1536              (fboundp 'whitespace-mode))
1537     (let ((whitespace-style (remove 'trailing whitespace-style)))
1538       (whitespace-mode arg))
1539     (setq show-trailing-whitespace whitespace-mode)))
1540
1541 (defvar mdw-do-misc-mode-hacking nil)
1542
1543 (defun mdw-misc-mode-config ()
1544   (and mdw-auto-indent
1545        (cond ((eq major-mode 'lisp-mode)
1546               (local-set-key "\C-m" 'mdw-indent-newline-and-indent))
1547              ((derived-mode-p 'slime-repl-mode 'asm-mode 'comint-mode)
1548               nil)
1549              (t
1550               (local-set-key "\C-m" 'newline-and-indent))))
1551   (set (make-local-variable 'mdw-do-misc-mode-hacking) t)
1552   (local-set-key [C-return] 'newline)
1553   (make-local-variable 'page-delimiter)
1554   (setq page-delimiter (concat       "^" "\f"
1555                                "\\|" "^"
1556                                      ".\\{0,4\\}"
1557                                      "-\\{5\\}"
1558                                      "\\(" " " ".*" " " "\\)?"
1559                                      "-+"
1560                                      ".\\{0,2\\}"
1561                                      "$"))
1562   (setq comment-column 40)
1563   (auto-fill-mode 1)
1564   (setq fill-column mdw-text-width)
1565   (flyspell-prog-mode)
1566   (and (fboundp 'gtags-mode)
1567        (gtags-mode))
1568   (if (fboundp 'hs-minor-mode)
1569       (trap (hs-minor-mode t))
1570     (outline-minor-mode t))
1571   (reveal-mode t)
1572   (trap (turn-on-font-lock)))
1573
1574 (defun mdw-post-local-vars-misc-mode-config ()
1575   (setq whitespace-line-column mdw-text-width)
1576   (when (and mdw-do-misc-mode-hacking
1577              (not buffer-read-only))
1578     (setq show-trailing-whitespace t)
1579     (mdw-whitespace-mode 1)))
1580 (add-hook 'hack-local-variables-hook 'mdw-post-local-vars-misc-mode-config)
1581
1582 (defmacro mdw-advise-update-angry-fruit-salad (&rest funcs)
1583   `(progn ,@(mapcar (lambda (func)
1584                       `(defadvice ,func
1585                            (after mdw-angry-fruit-salad activate)
1586                          (when mdw-do-misc-mode-hacking
1587                            (setq show-trailing-whitespace
1588                                  (not buffer-read-only))
1589                            (mdw-whitespace-mode (if buffer-read-only 0 1)))))
1590                     funcs)))
1591 (mdw-advise-update-angry-fruit-salad toggle-read-only
1592                                      read-only-mode
1593                                      view-mode
1594                                      view-mode-enable
1595                                      view-mode-disable)
1596
1597 (eval-after-load 'gtags
1598   '(progn
1599      (dolist (key '([mouse-2] [mouse-3]))
1600        (define-key gtags-mode-map key nil))
1601      (define-key gtags-mode-map [C-S-mouse-2] 'gtags-find-tag-by-event)
1602      (define-key gtags-select-mode-map [C-S-mouse-2]
1603        'gtags-select-tag-by-event)
1604      (dolist (map (list gtags-mode-map gtags-select-mode-map))
1605        (define-key map [C-S-mouse-3] 'gtags-pop-stack))))
1606
1607 ;; Backup file handling.
1608
1609 (defcustom mdw-backup-disable-regexps nil
1610   "List of regular expressions: if a file name matches any of
1611 these then the file is not backed up."
1612   :type '(repeat regexp))
1613
1614 (defun mdw-backup-enable-predicate (name)
1615   "[mdw]'s default backup predicate.
1616 Allows a backup if the standard predicate would allow it, and it
1617 doesn't match any of the regular expressions in
1618 `mdw-backup-disable-regexps'."
1619   (and (normal-backup-enable-predicate name)
1620        (let ((answer t) (list mdw-backup-disable-regexps))
1621          (save-match-data
1622            (while list
1623              (if (string-match (car list) name)
1624                  (setq answer nil))
1625              (setq list (cdr list)))
1626            answer))))
1627 (setq backup-enable-predicate 'mdw-backup-enable-predicate)
1628
1629 ;; Frame cleanup.
1630
1631 (defun mdw-last-one-out-turn-off-the-lights (frame)
1632   "Disconnect from an X display if this was the last frame on that display."
1633   (let ((frame-display (frame-parameter frame 'display)))
1634     (when (and frame-display
1635                (eq window-system 'x)
1636                (not (some (lambda (fr)
1637                             (and (not (eq fr frame))
1638                                  (string= (frame-parameter fr 'display)
1639                                           frame-display)))
1640                           (frame-list))))
1641       (run-with-idle-timer 0 nil #'x-close-connection frame-display))))
1642 (add-hook 'delete-frame-functions 'mdw-last-one-out-turn-off-the-lights)
1643
1644 ;;;--------------------------------------------------------------------------
1645 ;;; Fullscreen-ness.
1646
1647 (defcustom mdw-full-screen-parameters
1648   '((menu-bar-lines . 0)
1649     ;;(vertical-scroll-bars . nil)
1650     )
1651   "Frame parameters to set when making a frame fullscreen."
1652   :type '(alist :key-type symbol))
1653
1654 (defcustom mdw-full-screen-save
1655   '(width height)
1656   "Extra frame parameters to save when setting fullscreen."
1657   :type '(repeat symbol))
1658
1659 (defun mdw-toggle-full-screen (&optional frame)
1660   "Show the FRAME fullscreen."
1661   (interactive)
1662   (when window-system
1663     (cond ((frame-parameter frame 'fullscreen)
1664            (set-frame-parameter frame 'fullscreen nil)
1665            (modify-frame-parameters
1666             nil
1667             (or (frame-parameter frame 'mdw-full-screen-saved)
1668                 (mapcar (lambda (assoc)
1669                           (assq (car assoc) default-frame-alist))
1670                         mdw-full-screen-parameters))))
1671           (t
1672            (let ((saved (mapcar (lambda (param)
1673                                   (cons param (frame-parameter frame param)))
1674                                 (append (mapcar #'car
1675                                                 mdw-full-screen-parameters)
1676                                         mdw-full-screen-save))))
1677              (set-frame-parameter frame 'mdw-full-screen-saved saved))
1678            (modify-frame-parameters frame mdw-full-screen-parameters)
1679            (set-frame-parameter frame 'fullscreen 'fullboth)))))
1680
1681 ;;;--------------------------------------------------------------------------
1682 ;;; General fontification.
1683
1684 (make-face 'mdw-virgin-face)
1685
1686 (defmacro mdw-define-face (name &rest body)
1687   "Define a face, and make sure it's actually set as the definition."
1688   (declare (indent 1)
1689            (debug 0))
1690   `(progn
1691      (copy-face 'mdw-virgin-face ',name)
1692      (defvar ,name ',name)
1693      (put ',name 'face-defface-spec ',body)
1694      (face-spec-set ',name ',body nil)))
1695
1696 (mdw-define-face default
1697   (((type w32)) :family "courier new" :height 85)
1698   (((type x)) :family "6x13" :foundry "trad" :height 130)
1699   (((type color)) :foreground "white" :background "black")
1700   (t nil))
1701 (mdw-define-face fixed-pitch
1702   (((type w32)) :family "courier new" :height 85)
1703   (((type x)) :family "6x13" :foundry "trad" :height 130)
1704   (t :foreground "white" :background "black"))
1705 (mdw-define-face fixed-pitch-serif
1706   (((type w32)) :family "courier new" :height 85 :weight bold)
1707   (((type x)) :family "6x13" :foundry "trad" :height 130 :weight bold)
1708   (t :foreground "white" :background "black" :weight bold))
1709 (mdw-define-face variable-pitch
1710   (((type x)) :family "helvetica" :height 120))
1711 (mdw-define-face region
1712   (((min-colors 64)) :background "grey30")
1713   (((class color)) :background "blue")
1714   (t :inverse-video t))
1715 (mdw-define-face match
1716   (((class color)) :background "blue")
1717   (t :inverse-video t))
1718 (mdw-define-face mc/cursor-face
1719   (((class color)) :background "red")
1720   (t :inverse-video t))
1721 (mdw-define-face minibuffer-prompt
1722   (t :weight bold))
1723 (mdw-define-face mode-line
1724   (((class color)) :foreground "blue" :background "yellow"
1725                    :box (:line-width 1 :style released-button))
1726   (t :inverse-video t))
1727 (mdw-define-face mode-line-inactive
1728   (((class color)) :foreground "yellow" :background "blue"
1729                    :box (:line-width 1 :style released-button))
1730   (t :inverse-video t))
1731 (mdw-define-face nobreak-space
1732   (((type tty)))
1733   (t :inherit escape-glyph :underline t))
1734 (mdw-define-face scroll-bar
1735   (t :foreground "black" :background "lightgrey"))
1736 (mdw-define-face fringe
1737   (t :foreground "yellow"))
1738 (mdw-define-face show-paren-match
1739   (((min-colors 64)) :background "darkgreen")
1740   (((class color)) :background "green")
1741   (t :underline t))
1742 (mdw-define-face show-paren-mismatch
1743   (((class color)) :background "red")
1744   (t :inverse-video t))
1745 (mdw-define-face highlight
1746   (((min-colors 64)) :background "DarkSeaGreen4")
1747   (((class color)) :background "cyan")
1748   (t :inverse-video t))
1749
1750 (mdw-define-face viper-minibuffer-emacs (t nil))
1751 (mdw-define-face viper-minibuffer-insert (t nil))
1752 (mdw-define-face viper-minibuffer-vi (t nil))
1753 (mdw-define-face viper-replace-overlay
1754   (((min-colors 64)) :background "darkred")
1755   (((class color)) :background "red")
1756   (t :inverse-video t))
1757 (mdw-define-face viper-search (t :inherit isearch))
1758
1759 (mdw-define-face holiday-face
1760   (t :background "red"))
1761 (mdw-define-face calendar-today-face
1762   (t :foreground "yellow" :weight bold))
1763
1764 (mdw-define-face comint-highlight-prompt
1765   (t :weight bold))
1766 (mdw-define-face comint-highlight-input
1767   (t nil))
1768
1769 (mdw-define-face Man-underline
1770   (((type tty)) :underline t)
1771   (t :slant italic))
1772
1773 (mdw-define-face ido-subdir
1774   (t :foreground "cyan" :weight bold))
1775
1776 (mdw-define-face dired-directory
1777   (t :foreground "cyan" :weight bold))
1778 (mdw-define-face dired-symlink
1779   (t :foreground "cyan"))
1780 (mdw-define-face dired-perm-write
1781   (t nil))
1782
1783 (mdw-define-face trailing-whitespace
1784   (((class color)) :background "red")
1785   (t :inverse-video t))
1786 (mdw-define-face whitespace-line
1787   (((class color)) :background "darkred")
1788   (t :inverse-video t))
1789 (mdw-define-face mdw-punct-face
1790   (((min-colors 64)) :foreground "burlywood2")
1791   (((class color)) :foreground "yellow"))
1792 (mdw-define-face mdw-number-face
1793   (t :foreground "yellow"))
1794 (mdw-define-face mdw-trivial-face)
1795 (mdw-define-face font-lock-function-name-face
1796   (t :slant italic))
1797 (mdw-define-face font-lock-keyword-face
1798   (t :weight bold))
1799 (mdw-define-face font-lock-constant-face
1800   (t :slant italic))
1801 (mdw-define-face font-lock-builtin-face
1802   (t :weight bold))
1803 (mdw-define-face font-lock-type-face
1804   (t :weight bold :slant italic))
1805 (mdw-define-face font-lock-reference-face
1806   (t :weight bold))
1807 (mdw-define-face font-lock-variable-name-face
1808   (t :slant italic))
1809 (mdw-define-face font-lock-comment-delimiter-face
1810   (((min-colors 64)) :slant italic :foreground "SeaGreen1")
1811   (((class color)) :foreground "green")
1812   (t :weight bold))
1813 (mdw-define-face font-lock-comment-face
1814   (((min-colors 64)) :slant italic :foreground "SeaGreen1")
1815   (((class color)) :foreground "green")
1816   (t :weight bold))
1817 (mdw-define-face font-lock-string-face
1818   (((min-colors 64)) :foreground "SkyBlue1")
1819   (((class color)) :foreground "cyan")
1820   (t :weight bold))
1821
1822 (mdw-define-face message-separator
1823   (t :background "red" :foreground "white" :weight bold))
1824 (mdw-define-face message-cited-text
1825   (default :slant italic)
1826   (((min-colors 64)) :foreground "SkyBlue1")
1827   (((class color)) :foreground "cyan"))
1828 (mdw-define-face message-header-cc
1829   (default :slant italic)
1830   (((min-colors 64)) :foreground "SeaGreen1")
1831   (((class color)) :foreground "green"))
1832 (mdw-define-face message-header-newsgroups
1833   (default :slant italic)
1834   (((min-colors 64)) :foreground "SeaGreen1")
1835   (((class color)) :foreground "green"))
1836 (mdw-define-face message-header-subject
1837   (((min-colors 64)) :foreground "SeaGreen1")
1838   (((class color)) :foreground "green"))
1839 (mdw-define-face message-header-to
1840   (((min-colors 64)) :foreground "SeaGreen1")
1841   (((class color)) :foreground "green"))
1842 (mdw-define-face message-header-xheader
1843   (default :slant italic)
1844   (((min-colors 64)) :foreground "SeaGreen1")
1845   (((class color)) :foreground "green"))
1846 (mdw-define-face message-header-other
1847   (default :slant italic)
1848   (((min-colors 64)) :foreground "SeaGreen1")
1849   (((class color)) :foreground "green"))
1850 (mdw-define-face message-header-name
1851   (default :weight bold)
1852   (((min-colors 64)) :foreground "SeaGreen1")
1853   (((class color)) :foreground "green"))
1854
1855 (mdw-define-face which-func
1856   (t nil))
1857
1858 (mdw-define-face gnus-header-name
1859   (default :weight bold)
1860   (((min-colors 64)) :foreground "SeaGreen1")
1861   (((class color)) :foreground "green"))
1862 (mdw-define-face gnus-header-subject
1863   (((min-colors 64)) :foreground "SeaGreen1")
1864   (((class color)) :foreground "green"))
1865 (mdw-define-face gnus-header-from
1866   (((min-colors 64)) :foreground "SeaGreen1")
1867   (((class color)) :foreground "green"))
1868 (mdw-define-face gnus-header-to
1869   (((min-colors 64)) :foreground "SeaGreen1")
1870   (((class color)) :foreground "green"))
1871 (mdw-define-face gnus-header-content
1872   (default :slant italic)
1873   (((min-colors 64)) :foreground "SeaGreen1")
1874   (((class color)) :foreground "green"))
1875
1876 (mdw-define-face gnus-cite-1
1877   (((min-colors 64)) :foreground "SkyBlue1")
1878   (((class color)) :foreground "cyan"))
1879 (mdw-define-face gnus-cite-2
1880   (((min-colors 64)) :foreground "RoyalBlue2")
1881   (((class color)) :foreground "blue"))
1882 (mdw-define-face gnus-cite-3
1883   (((min-colors 64)) :foreground "MediumOrchid")
1884   (((class color)) :foreground "magenta"))
1885 (mdw-define-face gnus-cite-4
1886   (((min-colors 64)) :foreground "firebrick2")
1887   (((class color)) :foreground "red"))
1888 (mdw-define-face gnus-cite-5
1889   (((min-colors 64)) :foreground "burlywood2")
1890   (((class color)) :foreground "yellow"))
1891 (mdw-define-face gnus-cite-6
1892   (((min-colors 64)) :foreground "SeaGreen1")
1893   (((class color)) :foreground "green"))
1894 (mdw-define-face gnus-cite-7
1895   (((min-colors 64)) :foreground "SlateBlue1")
1896   (((class color)) :foreground "cyan"))
1897 (mdw-define-face gnus-cite-8
1898   (((min-colors 64)) :foreground "RoyalBlue2")
1899   (((class color)) :foreground "blue"))
1900 (mdw-define-face gnus-cite-9
1901   (((min-colors 64)) :foreground "purple2")
1902   (((class color)) :foreground "magenta"))
1903 (mdw-define-face gnus-cite-10
1904   (((min-colors 64)) :foreground "DarkOrange2")
1905   (((class color)) :foreground "red"))
1906 (mdw-define-face gnus-cite-11
1907   (t :foreground "grey"))
1908
1909 (mdw-define-face gnus-emphasis-underline
1910   (((type tty)) :underline t)
1911   (t :slant italic))
1912
1913 (mdw-define-face diff-header
1914   (t nil))
1915 (mdw-define-face diff-index
1916   (t :weight bold))
1917 (mdw-define-face diff-file-header
1918   (t :weight bold))
1919 (mdw-define-face diff-hunk-header
1920   (((min-colors 64)) :foreground "SkyBlue1")
1921   (((class color)) :foreground "cyan"))
1922 (mdw-define-face diff-function
1923   (default :weight bold)
1924   (((min-colors 64)) :foreground "SkyBlue1")
1925   (((class color)) :foreground "cyan"))
1926 (mdw-define-face diff-header
1927   (((min-colors 64)) :background "grey10"))
1928 (mdw-define-face diff-added
1929   (((class color)) :foreground "green"))
1930 (mdw-define-face diff-removed
1931   (((class color)) :foreground "red"))
1932 (mdw-define-face diff-context
1933   (t nil))
1934 (mdw-define-face diff-refine-change
1935   (((min-colors 64)) :background "RoyalBlue4")
1936   (t :underline t))
1937 (mdw-define-face diff-refine-removed
1938   (((min-colors 64)) :background "#500")
1939   (t :underline t))
1940 (mdw-define-face diff-refine-added
1941   (((min-colors 64)) :background "#050")
1942   (t :underline t))
1943
1944 (setq ediff-force-faces t)
1945 (mdw-define-face ediff-current-diff-A
1946   (((min-colors 64)) :background "darkred")
1947   (((class color)) :background "red")
1948   (t :inverse-video t))
1949 (mdw-define-face ediff-fine-diff-A
1950   (((min-colors 64)) :background "red3")
1951   (((class color)) :inverse-video t)
1952   (t :inverse-video nil))
1953 (mdw-define-face ediff-even-diff-A
1954   (((min-colors 64)) :background "#300"))
1955 (mdw-define-face ediff-odd-diff-A
1956   (((min-colors 64)) :background "#300"))
1957 (mdw-define-face ediff-current-diff-B
1958   (((min-colors 64)) :background "darkgreen")
1959   (((class color)) :background "magenta")
1960   (t :inverse-video t))
1961 (mdw-define-face ediff-fine-diff-B
1962   (((min-colors 64)) :background "green4")
1963   (((class color)) :inverse-video t)
1964   (t :inverse-video nil))
1965 (mdw-define-face ediff-even-diff-B
1966   (((min-colors 64)) :background "#020"))
1967 (mdw-define-face ediff-odd-diff-B
1968   (((min-colors 64)) :background "#020"))
1969 (mdw-define-face ediff-current-diff-C
1970   (((min-colors 64)) :background "darkblue")
1971   (((class color)) :background "blue")
1972   (t :inverse-video t))
1973 (mdw-define-face ediff-fine-diff-C
1974   (((min-colors 64)) :background "blue1")
1975   (((class color)) :inverse-video t)
1976   (t :inverse-video nil))
1977 (mdw-define-face ediff-even-diff-C
1978   (((min-colors 64)) :background "#004"))
1979 (mdw-define-face ediff-odd-diff-C
1980   (((min-colors 64)) :background "#004"))
1981 (mdw-define-face ediff-current-diff-Ancestor
1982   (((min-colors 64)) :background "#630")
1983   (((class color)) :background "blue")
1984   (t :inverse-video t))
1985 (mdw-define-face ediff-even-diff-Ancestor
1986   (((min-colors 64)) :background "#320"))
1987 (mdw-define-face ediff-odd-diff-Ancestor
1988   (((min-colors 64)) :background "#320"))
1989
1990 (mdw-define-face magit-hash
1991   (((min-colors 64)) :foreground "grey40")
1992   (((class color)) :foreground "blue"))
1993 (mdw-define-face magit-diff-hunk-heading
1994   (((min-colors 64)) :foreground "grey70" :background "grey25")
1995   (((class color)) :foreground "yellow"))
1996 (mdw-define-face magit-diff-hunk-heading-highlight
1997   (((min-colors 64)) :foreground "grey70" :background "grey35")
1998   (((class color)) :foreground "yellow" :background "blue"))
1999 (mdw-define-face magit-diff-added
2000   (((min-colors 64)) :foreground "#ddffdd" :background "#335533")
2001   (((class color)) :foreground "green"))
2002 (mdw-define-face magit-diff-added-highlight
2003   (((min-colors 64)) :foreground "#cceecc" :background "#336633")
2004   (((class color)) :foreground "green" :background "blue"))
2005 (mdw-define-face magit-diff-removed
2006   (((min-colors 64)) :foreground "#ffdddd" :background "#553333")
2007   (((class color)) :foreground "red"))
2008 (mdw-define-face magit-diff-removed-highlight
2009   (((min-colors 64)) :foreground "#eecccc" :background "#663333")
2010   (((class color)) :foreground "red" :background "blue"))
2011 (mdw-define-face magit-blame-heading
2012   (((min-colors 64)) :foreground "white" :background "grey25"
2013                      :weight normal :slant normal)
2014   (((class color)) :foreground "white" :background "blue"
2015                    :weight normal :slant normal))
2016 (mdw-define-face magit-blame-name
2017   (t :inherit magit-blame-heading :slant italic))
2018 (mdw-define-face magit-blame-date
2019   (((min-colors 64)) :inherit magit-blame-heading :foreground "grey60")
2020   (((class color)) :inherit magit-blame-heading :foreground "cyan"))
2021 (mdw-define-face magit-blame-summary
2022   (t :inherit magit-blame-heading :weight bold))
2023
2024 (mdw-define-face dylan-header-background
2025   (((min-colors 64)) :background "NavyBlue")
2026   (((class color)) :background "blue"))
2027
2028 (mdw-define-face erc-input-face
2029   (t :foreground "red"))
2030
2031 (mdw-define-face woman-bold
2032   (t :weight bold))
2033 (mdw-define-face woman-italic
2034   (t :slant italic))
2035
2036 (eval-after-load "rst"
2037   '(progn
2038      (mdw-define-face rst-level-1-face
2039        (t :foreground "SkyBlue1" :weight bold))
2040      (mdw-define-face rst-level-2-face
2041        (t :foreground "SeaGreen1" :weight bold))
2042      (mdw-define-face rst-level-3-face
2043        (t :weight bold))
2044      (mdw-define-face rst-level-4-face
2045        (t :slant italic))
2046      (mdw-define-face rst-level-5-face
2047        (t :underline t))
2048      (mdw-define-face rst-level-6-face
2049        ())))
2050
2051 (mdw-define-face p4-depot-added-face
2052   (t :foreground "green"))
2053 (mdw-define-face p4-depot-branch-op-face
2054   (t :foreground "yellow"))
2055 (mdw-define-face p4-depot-deleted-face
2056   (t :foreground "red"))
2057 (mdw-define-face p4-depot-unmapped-face
2058   (t :foreground "SkyBlue1"))
2059 (mdw-define-face p4-diff-change-face
2060   (t :foreground "yellow"))
2061 (mdw-define-face p4-diff-del-face
2062   (t :foreground "red"))
2063 (mdw-define-face p4-diff-file-face
2064   (t :foreground "SkyBlue1"))
2065 (mdw-define-face p4-diff-head-face
2066   (t :background "grey10"))
2067 (mdw-define-face p4-diff-ins-face
2068   (t :foreground "green"))
2069
2070 (mdw-define-face w3m-anchor-face
2071   (t :foreground "SkyBlue1" :underline t))
2072 (mdw-define-face w3m-arrived-anchor-face
2073   (t :foreground "SkyBlue1" :underline t))
2074
2075 (mdw-define-face whizzy-slice-face
2076   (t :background "grey10"))
2077 (mdw-define-face whizzy-error-face
2078   (t :background "darkred"))
2079
2080 ;; Ellipses used to indicate hidden text (and similar).
2081 (mdw-define-face mdw-ellipsis-face
2082   (((type tty)) :foreground "blue") (t :foreground "grey60"))
2083 (let ((dollar (make-glyph-code ?$ 'mdw-ellipsis-face))
2084       (backslash (make-glyph-code ?\\ 'mdw-ellipsis-face))
2085       (dot (make-glyph-code ?. 'mdw-ellipsis-face))
2086       (bar (make-glyph-code ?| mdw-ellipsis-face)))
2087   (set-display-table-slot standard-display-table 0 dollar)
2088   (set-display-table-slot standard-display-table 1 backslash)
2089   (set-display-table-slot standard-display-table 4
2090                           (vector dot dot dot))
2091   (set-display-table-slot standard-display-table 5 bar))
2092
2093 ;;;--------------------------------------------------------------------------
2094 ;;; Where is point?
2095
2096 (mdw-define-face mdw-point-overlay-face
2097   (((type graphic)))
2098   (((min-colors 64)) :background "darkblue")
2099   (((class color)) :background "blue")
2100   (((type tty) (class mono)) :inverse-video t))
2101
2102 (defcustom mdw-point-overlay-fringe-display '(vertical-bar . vertical-bar)
2103   "Bitmaps to display in the left and right fringes in the current line."
2104   :type '(cons symbol symbol))
2105
2106 (defun mdw-configure-point-overlay ()
2107   (let ((ov (make-overlay 0 0)))
2108     (overlay-put ov 'priority 0)
2109     (let* ((fringe (or mdw-point-overlay-fringe-display (cons nil nil)))
2110            (left (car fringe)) (right (cdr fringe))
2111            (s ""))
2112       (when left
2113         (let ((ss "."))
2114           (put-text-property 0 1 'display `(left-fringe ,left) ss)
2115           (setq s (concat s ss))))
2116       (when right
2117         (let ((ss "."))
2118           (put-text-property 0 1 'display `(right-fringe ,right) ss)
2119           (setq s (concat s ss))))
2120       (when (or left right)
2121         (overlay-put ov 'before-string s)))
2122     (overlay-put ov 'face 'mdw-point-overlay-face)
2123     (delete-overlay ov)
2124     ov))
2125
2126 (defvar mdw-point-overlay (mdw-configure-point-overlay)
2127   "An overlay used for showing where point is in the selected window.")
2128 (defun mdw-reconfigure-point-overlay ()
2129   (interactive)
2130   (setq mdw-point-overlay (mdw-configure-point-overlay)))
2131
2132 (defun mdw-remove-point-overlay ()
2133   "Remove the current-point overlay."
2134   (delete-overlay mdw-point-overlay))
2135
2136 (defun mdw-update-point-overlay ()
2137   "Mark the current point position with an overlay."
2138   (if (not mdw-point-overlay-mode)
2139       (mdw-remove-point-overlay)
2140     (overlay-put mdw-point-overlay 'window (selected-window))
2141     (move-overlay mdw-point-overlay
2142                   (line-beginning-position)
2143                   (+ (line-end-position) 1))))
2144
2145 (defvar mdw-point-overlay-buffers nil
2146   "List of buffers using `mdw-point-overlay-mode'.")
2147
2148 (define-minor-mode mdw-point-overlay-mode
2149   "Indicate current line with an overlay."
2150   :global nil
2151   (let ((buffer (current-buffer)))
2152     (setq mdw-point-overlay-buffers
2153             (mapcan (lambda (buf)
2154                       (if (and (buffer-live-p buf)
2155                                (not (eq buf buffer)))
2156                           (list buf)))
2157                     mdw-point-overlay-buffers))
2158     (if mdw-point-overlay-mode
2159         (setq mdw-point-overlay-buffers
2160                 (cons buffer mdw-point-overlay-buffers))))
2161   (cond (mdw-point-overlay-buffers
2162          (add-hook 'pre-command-hook 'mdw-remove-point-overlay)
2163          (add-hook 'post-command-hook 'mdw-update-point-overlay))
2164         (t
2165          (mdw-remove-point-overlay)
2166          (remove-hook 'pre-command-hook 'mdw-remove-point-overlay)
2167          (remove-hook 'post-command-hook 'mdw-update-point-overlay))))
2168
2169 (define-globalized-minor-mode mdw-global-point-overlay-mode
2170   mdw-point-overlay-mode
2171   (lambda () (if (not (minibufferp)) (mdw-point-overlay-mode t))))
2172
2173 (defvar mdw-terminal-title-alist nil)
2174 (defun mdw-update-terminal-title ()
2175   (when (let ((term (frame-parameter nil 'tty-type)))
2176           (and term (string-match "^xterm" term)))
2177     (let* ((tty (frame-parameter nil 'tty))
2178            (old (assoc tty mdw-terminal-title-alist))
2179            (new (format-mode-line frame-title-format)))
2180       (unless (and old (equal (cdr old) new))
2181         (if old (rplacd old new)
2182           (setq mdw-terminal-title-alist
2183                   (cons (cons tty new) mdw-terminal-title-alist)))
2184         (send-string-to-terminal (concat "\e]2;" new "\e\\"))))))
2185
2186 (add-hook 'post-command-hook 'mdw-update-terminal-title)
2187
2188 ;;;--------------------------------------------------------------------------
2189 ;;; C programming configuration.
2190
2191 ;; Make C indentation nice.
2192
2193 (defun mdw-c-lineup-arglist (langelem)
2194   "Hack for DWIMmery in c-lineup-arglist."
2195   (if (save-excursion
2196         (c-block-in-arglist-dwim (c-langelem-2nd-pos c-syntactic-element)))
2197       0
2198     (c-lineup-arglist langelem)))
2199
2200 (defun mdw-c-indent-extern-mumble (langelem)
2201   "Indent `extern \"...\" {' lines."
2202   (save-excursion
2203     (back-to-indentation)
2204     (if (looking-at
2205          "\\s-*\\<extern\\>\\s-*\"\\([^\\\\\"]+\\|\\.\\)*\"\\s-*{")
2206         c-basic-offset
2207       nil)))
2208
2209 (defun mdw-c-indent-arglist-nested (langelem)
2210   "Indent continued argument lists.
2211 If we've nested more than one argument list, then only introduce a single
2212 indentation anyway."
2213   (let ((context c-syntactic-context)
2214         (pos (c-langelem-2nd-pos c-syntactic-element))
2215         (should-indent-p t))
2216     (while (and context
2217                 (eq (caar context) 'arglist-cont-nonempty))
2218       (when (and (= (caddr (pop context)) pos)
2219                  context
2220                  (memq (caar context) '(arglist-intro
2221                                         arglist-cont-nonempty)))
2222         (setq should-indent-p nil)))
2223     (if should-indent-p '+ 0)))
2224
2225 (defvar mdw-define-c-styles-hook nil
2226   "Hook run when `cc-mode' starts up to define styles.")
2227
2228 (defun mdw-merge-style-alists (first second)
2229   (let ((output nil))
2230     (dolist (item first)
2231       (let ((key (car item)) (value (cdr item)))
2232         (if (string-suffix-p "-alist" (symbol-name key))
2233             (push (cons key
2234                         (mdw-merge-style-alists value
2235                                                 (cdr (assoc key second))))
2236                   output)
2237           (push item output))))
2238     (dolist (item second)
2239       (unless (assoc (car item) first)
2240         (push item output)))
2241     (nreverse output)))
2242
2243 (cl-defmacro mdw-define-c-style (name (&optional parent) &rest assocs)
2244   "Define a C style, called NAME (a symbol) based on PARENT, setting ASSOCs.
2245 A function, named `mdw-define-c-style/NAME', is defined to actually install
2246 the style using `c-add-style', and added to the hook
2247 `mdw-define-c-styles-hook'.  If CC Mode is already loaded, then the style is
2248 set."
2249   (declare (indent defun))
2250   (let* ((name-string (symbol-name name))
2251          (var (intern (concat "mdw-c-style/" name-string)))
2252          (func (intern (concat "mdw-define-c-style/" name-string))))
2253     `(progn
2254        (setq ,var
2255                ,(if (null parent)
2256                     `',assocs
2257                   (let ((parent-list (intern (concat "mdw-c-style/"
2258                                                      (symbol-name parent)))))
2259                     `(mdw-merge-style-alists ',assocs ,parent-list))))
2260        (defun ,func () (c-add-style ,name-string ,var))
2261        (and (featurep 'cc-mode) (,func))
2262        (add-hook 'mdw-define-c-styles-hook ',func)
2263        ',name)))
2264
2265 (eval-after-load "cc-mode"
2266   '(run-hooks 'mdw-define-c-styles-hook))
2267
2268 (mdw-define-c-style mdw-c ()
2269   (c-basic-offset . 2)
2270   (comment-column . 40)
2271   (c-class-key . "class")
2272   (c-backslash-column . 72)
2273   (c-label-minimum-indentation . 0)
2274   (c-offsets-alist (substatement-open . (add 0 c-indent-one-line-block))
2275                    (defun-open . (add 0 c-indent-one-line-block))
2276                    (arglist-cont-nonempty . mdw-c-lineup-arglist)
2277                    (topmost-intro . mdw-c-indent-extern-mumble)
2278                    (cpp-define-intro . 0)
2279                    (knr-argdecl . 0)
2280                    (inextern-lang . [0])
2281                    (label . 0)
2282                    (case-label . +)
2283                    (access-label . -)
2284                    (inclass . +)
2285                    (inline-open . ++)
2286                    (statement-cont . +)
2287                    (statement-case-intro . +)))
2288
2289 (mdw-define-c-style mdw-trustonic-c (mdw-c)
2290   (c-basic-offset . 4)
2291   (c-offsets-alist (access-label . -2)))
2292
2293 (mdw-define-c-style mdw-trustonic-alec-c (mdw-trustonic-c)
2294   (comment-column . 0)
2295   (c-indent-comment-alist (anchored-comment . (column . 0))
2296                           (end-block . (space . 1))
2297                           (cpp-end-block . (space . 1))
2298                           (other . (space . 1)))
2299   (c-offsets-alist (arglist-cont-nonempty . mdw-c-indent-arglist-nested)))
2300
2301 (defun mdw-set-default-c-style (modes style)
2302   "Update the default CC Mode style for MODES to be STYLE.
2303
2304 MODES may be a list of major mode names or a singleton.  STYLE is a style
2305 name, as a symbol."
2306   (let ((modes (if (listp modes) modes (list modes)))
2307         (style (symbol-name style)))
2308     (setq c-default-style
2309             (append (mapcar (lambda (mode)
2310                               (cons mode style))
2311                             modes)
2312                     (remove-if (lambda (assoc)
2313                                  (memq (car assoc) modes))
2314                                (if (listp c-default-style)
2315                                    c-default-style
2316                                  (list (cons 'other c-default-style))))))))
2317 (setq c-default-style "mdw-c")
2318
2319 (mdw-set-default-c-style '(c-mode c++-mode) 'mdw-c)
2320
2321 (defvar mdw-c-comment-fill-prefix
2322   `((,(concat "\\([ \t]*/?\\)"
2323               "\\(\\*\\|//\\)"
2324               "\\([ \t]*\\)"
2325               "\\([A-Za-z]+:[ \t]*\\)?"
2326               mdw-hanging-indents)
2327      (pad . 1) (match . 2) (pad . 3) (pad . 4) (pad . 5)))
2328   "Fill prefix matching C comments (both kinds).")
2329
2330 (defun mdw-fontify-c-and-c++ ()
2331
2332   ;; Fiddle with some syntax codes.
2333   (modify-syntax-entry ?* ". 23")
2334   (modify-syntax-entry ?/ ". 124b")
2335   (modify-syntax-entry ?\n "> b")
2336
2337   ;; Other stuff.
2338   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
2339
2340   ;; Now define things to be fontified.
2341   (make-local-variable 'font-lock-keywords)
2342   (let ((c-keywords
2343          (mdw-regexps "alignas"          ;C11 macro, C++11
2344                       "alignof"          ;C++11
2345                       "and"              ;C++, C95 macro
2346                       "and_eq"           ;C++, C95 macro
2347                       "asm"              ;K&R, C++, GCC
2348                       "atomic"           ;C11 macro, C++11 template type
2349                       "auto"             ;K&R, C89
2350                       "bitand"           ;C++, C95 macro
2351                       "bitor"            ;C++, C95 macro
2352                       "bool"             ;C++, C99 macro
2353                       "break"            ;K&R, C89
2354                       "case"             ;K&R, C89
2355                       "catch"            ;C++
2356                       "char"             ;K&R, C89
2357                       "char16_t"         ;C++11, C11 library type
2358                       "char32_t"         ;C++11, C11 library type
2359                       "class"            ;C++
2360                       "complex"          ;C99 macro, C++ template type
2361                       "compl"            ;C++, C95 macro
2362                       "const"            ;C89
2363                       "constexpr"        ;C++11
2364                       "const_cast"       ;C++
2365                       "continue"         ;K&R, C89
2366                       "decltype"         ;C++11
2367                       "defined"          ;C89 preprocessor
2368                       "default"          ;K&R, C89
2369                       "delete"           ;C++
2370                       "do"               ;K&R, C89
2371                       "double"           ;K&R, C89
2372                       "dynamic_cast"     ;C++
2373                       "else"             ;K&R, C89
2374                       ;; "entry"         ;K&R -- never used
2375                       "enum"             ;C89
2376                       "explicit"         ;C++
2377                       "export"           ;C++
2378                       "extern"           ;K&R, C89
2379                       "float"            ;K&R, C89
2380                       "for"              ;K&R, C89
2381                       ;; "fortran"       ;K&R
2382                       "friend"           ;C++
2383                       "goto"             ;K&R, C89
2384                       "if"               ;K&R, C89
2385                       "imaginary"        ;C99 macro
2386                       "inline"           ;C++, C99, GCC
2387                       "int"              ;K&R, C89
2388                       "long"             ;K&R, C89
2389                       "mutable"          ;C++
2390                       "namespace"        ;C++
2391                       "new"              ;C++
2392                       "noexcept"         ;C++11
2393                       "noreturn"         ;C11 macro
2394                       "not"              ;C++, C95 macro
2395                       "not_eq"           ;C++, C95 macro
2396                       "nullptr"          ;C++11
2397                       "operator"         ;C++
2398                       "or"               ;C++, C95 macro
2399                       "or_eq"            ;C++, C95 macro
2400                       "private"          ;C++
2401                       "protected"        ;C++
2402                       "public"           ;C++
2403                       "register"         ;K&R, C89
2404                       "reinterpret_cast" ;C++
2405                       "restrict"         ;C99
2406                       "return"           ;K&R, C89
2407                       "short"            ;K&R, C89
2408                       "signed"           ;C89
2409                       "sizeof"           ;K&R, C89
2410                       "static"           ;K&R, C89
2411                       "static_assert"    ;C11 macro, C++11
2412                       "static_cast"      ;C++
2413                       "struct"           ;K&R, C89
2414                       "switch"           ;K&R, C89
2415                       "template"         ;C++
2416                       "throw"            ;C++
2417                       "try"              ;C++
2418                       "thread_local"     ;C11 macro, C++11
2419                       "typedef"          ;C89
2420                       "typeid"           ;C++
2421                       "typeof"           ;GCC
2422                       "typename"         ;C++
2423                       "union"            ;K&R, C89
2424                       "unsigned"         ;K&R, C89
2425                       "using"            ;C++
2426                       "virtual"          ;C++
2427                       "void"             ;C89
2428                       "volatile"         ;C89
2429                       "wchar_t"          ;C++, C89 library type
2430                       "while"            ;K&R, C89
2431                       "xor"              ;C++, C95 macro
2432                       "xor_eq"           ;C++, C95 macro
2433                       "_Alignas"         ;C11
2434                       "_Alignof"         ;C11
2435                       "_Atomic"          ;C11
2436                       "_Bool"            ;C99
2437                       "_Complex"         ;C99
2438                       "_Generic"         ;C11
2439                       "_Imaginary"       ;C99
2440                       "_Noreturn"        ;C11
2441                       "_Pragma"          ;C99 preprocessor
2442                       "_Static_assert"   ;C11
2443                       "_Thread_local"    ;C11
2444                       "__alignof__"      ;GCC
2445                       "__asm__"          ;GCC
2446                       "__attribute__"    ;GCC
2447                       "__complex__"      ;GCC
2448                       "__const__"        ;GCC
2449                       "__extension__"    ;GCC
2450                       "__imag__"         ;GCC
2451                       "__inline__"       ;GCC
2452                       "__label__"        ;GCC
2453                       "__real__"         ;GCC
2454                       "__signed__"       ;GCC
2455                       "__typeof__"       ;GCC
2456                       "__volatile__"     ;GCC
2457                       ))
2458         (c-builtins
2459          (mdw-regexps "false"            ;C++, C99 macro
2460                       "this"             ;C++
2461                       "true"             ;C++, C99 macro
2462                       ))
2463         (preprocessor-keywords
2464          (mdw-regexps "assert" "define" "elif" "else" "endif" "error"
2465                       "ident" "if" "ifdef" "ifndef" "import" "include"
2466                       "line" "pragma" "unassert" "undef" "warning"))
2467         (objc-keywords
2468          (mdw-regexps "class" "defs" "encode" "end" "implementation"
2469                       "interface" "private" "protected" "protocol" "public"
2470                       "selector")))
2471
2472     (setq font-lock-keywords
2473             (list
2474
2475              ;; Fontify include files as strings.
2476              (list (concat "^[ \t]*\\#[ \t]*"
2477                            "\\(include\\|import\\)"
2478                            "[ \t]*\\(<[^>]+>?\\)")
2479                    '(2 font-lock-string-face))
2480
2481              ;; Preprocessor directives are `references'?.
2482              (list (concat "^\\([ \t]*#[ \t]*\\(\\("
2483                            preprocessor-keywords
2484                            "\\)\\>\\|[0-9]+\\|$\\)\\)")
2485                    '(1 font-lock-keyword-face))
2486
2487              ;; Handle the keywords defined above.
2488              (list (concat "@\\<\\(" objc-keywords "\\)\\>")
2489                    '(0 font-lock-keyword-face))
2490
2491              (list (concat "\\<\\(" c-keywords "\\)\\>")
2492                    '(0 font-lock-keyword-face))
2493
2494              (list (concat "\\<\\(" c-builtins "\\)\\>")
2495                    '(0 font-lock-variable-name-face))
2496
2497              ;; Handle numbers too.
2498              ;;
2499              ;; This looks strange, I know.  It corresponds to the
2500              ;; preprocessor's idea of what a number looks like, rather than
2501              ;; anything sensible.
2502              (list (concat "\\(\\<[0-9]\\|\\.[0-9]\\)"
2503                            "\\([Ee][+-]\\|[0-9A-Za-z_.]\\)*")
2504                    '(0 mdw-number-face))
2505
2506              ;; And anything else is punctuation.
2507              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2508                    '(0 mdw-punct-face))))))
2509
2510 (define-derived-mode sod-mode c-mode "Sod"
2511   "Major mode for editing Sod code.")
2512 (push '("\\.sod$" . sod-mode) auto-mode-alist)
2513
2514 (dolist (hook '(c-mode-hook objc-mode-hook c++-mode-hook))
2515   (add-hook hook 'mdw-misc-mode-config t)
2516   (add-hook hook 'mdw-fontify-c-and-c++ t))
2517
2518 ;;;--------------------------------------------------------------------------
2519 ;;; AP calc mode.
2520
2521 (define-derived-mode apcalc-mode c-mode "AP Calc"
2522   "Major mode for editing Calc code.")
2523
2524 (defun mdw-fontify-apcalc ()
2525
2526   ;; Fiddle with some syntax codes.
2527   (modify-syntax-entry ?* ". 23")
2528   (modify-syntax-entry ?/ ". 14")
2529
2530   ;; Other stuff.
2531   (setq comment-start "/* ")
2532   (setq comment-end " */")
2533   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
2534
2535   ;; Now define things to be fontified.
2536   (make-local-variable 'font-lock-keywords)
2537   (let ((c-keywords
2538          (mdw-regexps "break" "case" "cd" "continue" "define" "default"
2539                       "do" "else" "exit" "for" "global" "goto" "help" "if"
2540                       "local" "mat" "obj" "print" "quit" "read" "return"
2541                       "show" "static" "switch" "while" "write")))
2542
2543     (setq font-lock-keywords
2544             (list
2545
2546              ;; Handle the keywords defined above.
2547              (list (concat "\\<\\(" c-keywords "\\)\\>")
2548                    '(0 font-lock-keyword-face))
2549
2550              ;; Handle numbers too.
2551              ;;
2552              ;; This looks strange, I know.  It corresponds to the
2553              ;; preprocessor's idea of what a number looks like, rather than
2554              ;; anything sensible.
2555              (list (concat "\\(\\<[0-9]\\|\\.[0-9]\\)"
2556                            "\\([Ee][+-]\\|[0-9A-Za-z_.]\\)*")
2557                    '(0 mdw-number-face))
2558
2559              ;; And anything else is punctuation.
2560              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2561                    '(0 mdw-punct-face))))))
2562
2563 (progn
2564   (add-hook 'apcalc-mode-hook 'mdw-misc-mode-config t)
2565   (add-hook 'apcalc-mode-hook 'mdw-fontify-apcalc t))
2566
2567 ;;;--------------------------------------------------------------------------
2568 ;;; Java programming configuration.
2569
2570 ;; Make indentation nice.
2571
2572 (mdw-define-c-style mdw-java ()
2573   (c-basic-offset . 2)
2574   (c-backslash-column . 72)
2575   (c-offsets-alist (substatement-open . 0)
2576                    (label . +)
2577                    (case-label . +)
2578                    (access-label . 0)
2579                    (inclass . +)
2580                    (statement-case-intro . +)))
2581 (mdw-set-default-c-style 'java-mode 'mdw-java)
2582
2583 ;; Declare Java fontification style.
2584
2585 (defun mdw-fontify-java ()
2586
2587   ;; Fiddle with some syntax codes.
2588   (modify-syntax-entry ?@ ".")
2589   (modify-syntax-entry ?@ "." font-lock-syntax-table)
2590
2591   ;; Other stuff.
2592   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
2593
2594   ;; Now define things to be fontified.
2595   (make-local-variable 'font-lock-keywords)
2596   (let ((java-keywords
2597          (mdw-regexps "abstract" "assert"
2598                       "boolean" "break" "byte"
2599                       "case" "catch" "char" "class" "const" "continue"
2600                       "default" "do" "double"
2601                       "else" "enum" "extends"
2602                       "final" "finally" "float" "for"
2603                       "goto"
2604                       "if" "implements" "import" "instanceof" "int"
2605                       "interface"
2606                       "long"
2607                       "native" "new"
2608                       "package" "private" "protected" "public"
2609                       "return"
2610                       "short" "static" "strictfp" "switch" "synchronized"
2611                       "throw" "throws" "transient" "try"
2612                       "void" "volatile"
2613                       "while"))
2614
2615         (java-builtins
2616          (mdw-regexps "false" "null" "super" "this" "true")))
2617
2618     (setq font-lock-keywords
2619             (list
2620
2621              ;; Handle the keywords defined above.
2622              (list (concat "\\<\\(" java-keywords "\\)\\>")
2623                    '(0 font-lock-keyword-face))
2624
2625              ;; Handle the magic builtins defined above.
2626              (list (concat "\\<\\(" java-builtins "\\)\\>")
2627                    '(0 font-lock-variable-name-face))
2628
2629              ;; Handle numbers too.
2630              ;;
2631              ;; The following isn't quite right, but it's close enough.
2632              (list (concat "\\<\\("
2633                            "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
2634                            "[0-9]+\\(\\.[0-9]*\\)?"
2635                            "\\([eE][-+]?[0-9]+\\)?\\)"
2636                            "[lLfFdD]?")
2637                    '(0 mdw-number-face))
2638
2639              ;; And anything else is punctuation.
2640              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2641                    '(0 mdw-punct-face))))))
2642
2643 (progn
2644   (add-hook 'java-mode-hook 'mdw-misc-mode-config t)
2645   (add-hook 'java-mode-hook 'mdw-fontify-java t))
2646
2647 ;;;--------------------------------------------------------------------------
2648 ;;; Javascript programming configuration.
2649
2650 (defun mdw-javascript-style ()
2651   (setq js-indent-level 2)
2652   (setq js-expr-indent-offset 0))
2653
2654 (defun mdw-fontify-javascript ()
2655
2656   ;; Other stuff.
2657   (mdw-javascript-style)
2658   (setq js-auto-indent-flag t)
2659
2660   ;; Now define things to be fontified.
2661   (make-local-variable 'font-lock-keywords)
2662   (let ((javascript-keywords
2663          (mdw-regexps "abstract" "boolean" "break" "byte" "case" "catch"
2664                       "char" "class" "const" "continue" "debugger" "default"
2665                       "delete" "do" "double" "else" "enum" "export" "extends"
2666                       "final" "finally" "float" "for" "function" "goto" "if"
2667                       "implements" "import" "in" "instanceof" "int"
2668                       "interface" "let" "long" "native" "new" "package"
2669                       "private" "protected" "public" "return" "short"
2670                       "static" "super" "switch" "synchronized" "throw"
2671                       "throws" "transient" "try" "typeof" "var" "void"
2672                       "volatile" "while" "with" "yield"))
2673         (javascript-builtins
2674          (mdw-regexps "false" "null" "undefined" "Infinity" "NaN" "true"
2675                       "arguments" "this")))
2676
2677     (setq font-lock-keywords
2678             (list
2679
2680              ;; Handle the keywords defined above.
2681              (list (concat "\\_<\\(" javascript-keywords "\\)\\_>")
2682                    '(0 font-lock-keyword-face))
2683
2684              ;; Handle the predefined builtins defined above.
2685              (list (concat "\\_<\\(" javascript-builtins "\\)\\_>")
2686                    '(0 font-lock-variable-name-face))
2687
2688              ;; Handle numbers too.
2689              ;;
2690              ;; The following isn't quite right, but it's close enough.
2691              (list (concat "\\_<\\("
2692                            "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
2693                            "[0-9]+\\(\\.[0-9]*\\)?"
2694                            "\\([eE][-+]?[0-9]+\\)?\\)"
2695                            "[lLfFdD]?")
2696                    '(0 mdw-number-face))
2697
2698              ;; And anything else is punctuation.
2699              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2700                    '(0 mdw-punct-face))))))
2701
2702 (progn
2703   (add-hook 'js-mode-hook 'mdw-misc-mode-config t)
2704   (add-hook 'js-mode-hook 'mdw-fontify-javascript t))
2705
2706 ;;;--------------------------------------------------------------------------
2707 ;;; Scala programming configuration.
2708
2709 (defun mdw-fontify-scala ()
2710
2711   ;; Comment filling.
2712   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
2713
2714   ;; Define things to be fontified.
2715   (make-local-variable 'font-lock-keywords)
2716   (let ((scala-keywords
2717          (mdw-regexps "abstract" "case" "catch" "class" "def" "do" "else"
2718                       "extends" "final" "finally" "for" "forSome" "if"
2719                       "implicit" "import" "lazy" "match" "new" "object"
2720                       "override" "package" "private" "protected" "return"
2721                       "sealed" "throw" "trait" "try" "type" "val"
2722                       "var" "while" "with" "yield"))
2723         (scala-constants
2724          (mdw-regexps "false" "null" "super" "this" "true"))
2725         (punctuation "[-!%^&*=+:@#~/?\\|`]"))
2726
2727     (setq font-lock-keywords
2728             (list
2729
2730              ;; Magical identifiers between backticks.
2731              (list (concat "`\\([^`]+\\)`")
2732                    '(1 font-lock-variable-name-face))
2733
2734              ;; Handle the keywords defined above.
2735              (list (concat "\\_<\\(" scala-keywords "\\)\\_>")
2736                    '(0 font-lock-keyword-face))
2737
2738              ;; Handle the constants defined above.
2739              (list (concat "\\_<\\(" scala-constants "\\)\\_>")
2740                    '(0 font-lock-variable-name-face))
2741
2742              ;; Magical identifiers between backticks.
2743              (list (concat "`\\([^`]+\\)`")
2744                    '(1 font-lock-variable-name-face))
2745
2746              ;; Handle numbers too.
2747              ;;
2748              ;; As usual, not quite right.
2749              (list (concat "\\_<\\("
2750                            "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
2751                            "[0-9]+\\(\\.[0-9]*\\)?"
2752                            "\\([eE][-+]?[0-9]+\\)?\\)"
2753                            "[lLfFdD]?")
2754                    '(0 mdw-number-face))
2755
2756              ;; And everything else is punctuation.
2757              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2758                    '(0 mdw-punct-face)))
2759
2760           font-lock-syntactic-keywords
2761             (list
2762
2763              ;; Single quotes around characters.  But not when used to quote
2764              ;; symbol names.  Ugh.
2765              (list (concat "\\('\\)"
2766                            "\\(" "."
2767                            "\\|" "\\\\" "\\(" "\\\\\\\\" "\\)*"
2768                            "u+" "[0-9a-fA-F]\\{4\\}"
2769                            "\\|" "\\\\" "[0-7]\\{1,3\\}"
2770                            "\\|" "\\\\" "." "\\)"
2771                            "\\('\\)")
2772                    '(1 "\"")
2773                    '(4 "\""))))))
2774
2775 (progn
2776   (add-hook 'scala-mode-hook 'mdw-misc-mode-config t)
2777   (add-hook 'scala-mode-hook 'mdw-fontify-scala t))
2778
2779 ;;;--------------------------------------------------------------------------
2780 ;;; C# programming configuration.
2781
2782 ;; Make indentation nice.
2783
2784 (mdw-define-c-style mdw-csharp ()
2785   (c-basic-offset . 2)
2786   (c-backslash-column . 72)
2787   (c-offsets-alist (substatement-open . 0)
2788                    (label . 0)
2789                    (case-label . +)
2790                    (access-label . 0)
2791                    (inclass . +)
2792                    (statement-case-intro . +)))
2793 (mdw-set-default-c-style 'csharp-mode 'mdw-csharp)
2794
2795 ;; Declare C# fontification style.
2796
2797 (defun mdw-fontify-csharp ()
2798
2799   ;; Other stuff.
2800   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
2801
2802   ;; Now define things to be fontified.
2803   (make-local-variable 'font-lock-keywords)
2804   (let ((csharp-keywords
2805          (mdw-regexps "abstract" "as" "bool" "break" "byte" "case" "catch"
2806                       "char" "checked" "class" "const" "continue" "decimal"
2807                       "default" "delegate" "do" "double" "else" "enum"
2808                       "event" "explicit" "extern" "finally" "fixed" "float"
2809                       "for" "foreach" "goto" "if" "implicit" "in" "int"
2810                       "interface" "internal" "is" "lock" "long" "namespace"
2811                       "new" "object" "operator" "out" "override" "params"
2812                       "private" "protected" "public" "readonly" "ref"
2813                       "return" "sbyte" "sealed" "short" "sizeof"
2814                       "stackalloc" "static" "string" "struct" "switch"
2815                       "throw" "try" "typeof" "uint" "ulong" "unchecked"
2816                       "unsafe" "ushort" "using" "virtual" "void" "volatile"
2817                       "while" "yield"))
2818
2819         (csharp-builtins
2820          (mdw-regexps "base" "false" "null" "this" "true")))
2821
2822     (setq font-lock-keywords
2823             (list
2824
2825              ;; Handle the keywords defined above.
2826              (list (concat "\\<\\(" csharp-keywords "\\)\\>")
2827                    '(0 font-lock-keyword-face))
2828
2829              ;; Handle the magic builtins defined above.
2830              (list (concat "\\<\\(" csharp-builtins "\\)\\>")
2831                    '(0 font-lock-variable-name-face))
2832
2833              ;; Handle numbers too.
2834              ;;
2835              ;; The following isn't quite right, but it's close enough.
2836              (list (concat "\\<\\("
2837                            "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
2838                            "[0-9]+\\(\\.[0-9]*\\)?"
2839                            "\\([eE][-+]?[0-9]+\\)?\\)"
2840                            "[lLfFdD]?")
2841                    '(0 mdw-number-face))
2842
2843              ;; And anything else is punctuation.
2844              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2845                    '(0 mdw-punct-face))))))
2846
2847 (define-derived-mode csharp-mode java-mode "C#"
2848   "Major mode for editing C# code.")
2849
2850 (add-hook 'csharp-mode-hook 'mdw-fontify-csharp t)
2851
2852 ;;;--------------------------------------------------------------------------
2853 ;;; F# programming configuration.
2854
2855 (setq fsharp-indent-offset 2)
2856
2857 (defun mdw-fontify-fsharp ()
2858
2859   (let ((punct "=<>+-*/|&%!@?"))
2860     (do ((i 0 (1+ i)))
2861         ((>= i (length punct)))
2862       (modify-syntax-entry (aref punct i) ".")))
2863
2864   (modify-syntax-entry ?_ "_")
2865   (modify-syntax-entry ?( "(")
2866   (modify-syntax-entry ?) ")")
2867
2868   (setq indent-tabs-mode nil)
2869
2870   (let ((fsharp-keywords
2871          (mdw-regexps "abstract" "and" "as" "assert" "atomic"
2872                       "begin" "break"
2873                       "checked" "class" "component" "const" "constraint"
2874                       "constructor" "continue"
2875                       "default" "delegate" "do" "done" "downcast" "downto"
2876                       "eager" "elif" "else" "end" "exception" "extern"
2877                       "finally" "fixed" "for" "fori" "fun" "function"
2878                       "functor"
2879                       "global"
2880                       "if" "in" "include" "inherit" "inline" "interface"
2881                       "internal"
2882                       "lazy" "let"
2883                       "match" "measure" "member" "method" "mixin" "module"
2884                       "mutable"
2885                       "namespace" "new"
2886                       "object" "of" "open" "or" "override"
2887                       "parallel" "params" "private" "process" "protected"
2888                       "public" "pure"
2889                       "rec" "recursive" "return"
2890                       "sealed" "sig" "static" "struct"
2891                       "tailcall" "then" "to" "trait" "try" "type"
2892                       "upcast" "use"
2893                       "val" "virtual" "void" "volatile"
2894                       "when" "while" "with"
2895                       "yield"))
2896
2897         (fsharp-builtins
2898          (mdw-regexps "asr" "land" "lor" "lsl" "lsr" "lxor" "mod"
2899                       "base" "false" "null" "true"))
2900
2901         (bang-keywords
2902          (mdw-regexps "do" "let" "return" "use" "yield"))
2903
2904         (preprocessor-keywords
2905          (mdw-regexps "if" "indent" "else" "endif")))
2906
2907     (setq font-lock-keywords
2908             (list (list (concat "\\(^\\|[^\"]\\)"
2909                                 "\\(" "(\\*"
2910                                       "[^*]*\\*+"
2911                                       "\\(" "[^)*]" "[^*]*" "\\*+" "\\)*"
2912                                       ")"
2913                                 "\\|"
2914                                       "//.*"
2915                                 "\\)")
2916                         '(2 font-lock-comment-face))
2917
2918                   (list (concat "'" "\\("
2919                                       "\\\\"
2920                                       "\\(" "[ntbr'\\]"
2921                                       "\\|" "[0-9][0-9][0-9]"
2922                                       "\\|" "u" "[0-9a-fA-F]\\{4\\}"
2923                                       "\\|" "U" "[0-9a-fA-F]\\{8\\}"
2924                                       "\\)"
2925                                     "\\|"
2926                                     "." "\\)" "'"
2927                                 "\\|"
2928                                 "\"" "[^\"\\]*"
2929                                       "\\(" "\\\\" "\\(.\\|\n\\)"
2930                                             "[^\"\\]*" "\\)*"
2931                                 "\\(\"\\|\\'\\)")
2932                         '(0 font-lock-string-face))
2933
2934                   (list (concat "\\_<\\(" bang-keywords "\\)!" "\\|"
2935                                 "^#[ \t]*\\(" preprocessor-keywords "\\)\\_>"
2936                                 "\\|"
2937                                 "\\_<\\(" fsharp-keywords "\\)\\_>")
2938                         '(0 font-lock-keyword-face))
2939                   (list (concat "\\<\\(" fsharp-builtins "\\)\\_>")
2940                         '(0 font-lock-variable-name-face))
2941
2942                   (list (concat "\\_<"
2943                                 "\\(" "0[bB][01]+" "\\|"
2944                                       "0[oO][0-7]+" "\\|"
2945                                       "0[xX][0-9a-fA-F]+" "\\)"
2946                                 "\\(" "lf\\|LF" "\\|"
2947                                       "[uU]?[ysnlL]?" "\\)"
2948                                 "\\|"
2949                                 "\\_<"
2950                                 "[0-9]+" "\\("
2951                                   "[mMQRZING]"
2952                                   "\\|"
2953                                   "\\(\\.[0-9]*\\)?"
2954                                   "\\([eE][-+]?[0-9]+\\)?"
2955                                   "[fFmM]?"
2956                                   "\\|"
2957                                   "[uU]?[ysnlL]?"
2958                                 "\\)")
2959                         '(0 mdw-number-face))
2960
2961                   (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2962                         '(0 mdw-punct-face))))))
2963
2964 (defun mdw-fontify-inferior-fsharp ()
2965   (mdw-fontify-fsharp)
2966   (setq font-lock-keywords
2967           (append (list (list "^[#-]" '(0 font-lock-comment-face))
2968                         (list "^>" '(0 font-lock-keyword-face)))
2969                   font-lock-keywords)))
2970
2971 (progn
2972   (add-hook 'fsharp-mode-hook 'mdw-misc-mode-config t)
2973   (add-hook 'fsharp-mode-hook 'mdw-fontify-fsharp t)
2974   (add-hook 'inferior-fsharp-mode-hooks 'mdw-fontify-inferior-fsharp t))
2975
2976 ;;;--------------------------------------------------------------------------
2977 ;;; Go programming configuration.
2978
2979 (defun mdw-fontify-go ()
2980
2981   (make-local-variable 'font-lock-keywords)
2982   (let ((go-keywords
2983          (mdw-regexps "break" "case" "chan" "const" "continue"
2984                       "default" "defer" "else" "fallthrough" "for"
2985                       "func" "go" "goto" "if" "import"
2986                       "interface" "map" "package" "range" "return"
2987                       "select" "struct" "switch" "type" "var"))
2988         (go-intrinsics
2989          (mdw-regexps "bool" "byte" "complex64" "complex128" "error"
2990                       "float32" "float64" "int" "uint8" "int16" "int32"
2991                       "int64" "rune" "string" "uint" "uint8" "uint16"
2992                       "uint32" "uint64" "uintptr" "void"
2993                       "false" "iota" "nil" "true"
2994                       "init" "main"
2995                       "append" "cap" "copy" "delete" "imag" "len" "make"
2996                       "new" "panic" "real" "recover")))
2997
2998     (setq font-lock-keywords
2999             (list
3000
3001              ;; Handle the keywords defined above.
3002              (list (concat "\\<\\(" go-keywords "\\)\\>")
3003                    '(0 font-lock-keyword-face))
3004              (list (concat "\\<\\(" go-intrinsics "\\)\\>")
3005                    '(0 font-lock-variable-name-face))
3006
3007              ;; Strings and characters.
3008              (list (concat "'"
3009                            "\\(" "[^\\']" "\\|"
3010                                  "\\\\"
3011                                  "\\(" "[abfnrtv\\'\"]" "\\|"
3012                                        "[0-7]\\{3\\}" "\\|"
3013                                        "x" "[0-9A-Fa-f]\\{2\\}" "\\|"
3014                                        "u" "[0-9A-Fa-f]\\{4\\}" "\\|"
3015                                        "U" "[0-9A-Fa-f]\\{8\\}" "\\)" "\\)"
3016                            "'"
3017                            "\\|"
3018                            "\""
3019                            "\\(" "[^\n\\\"]+" "\\|" "\\\\." "\\)*"
3020                            "\\(\"\\|$\\)"
3021                            "\\|"
3022                            "`" "[^`]+" "`")
3023                    '(0 font-lock-string-face))
3024
3025              ;; Handle numbers too.
3026              ;;
3027              ;; The following isn't quite right, but it's close enough.
3028              (list (concat "\\<\\("
3029                            "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
3030                            "[0-9]+\\(\\.[0-9]*\\)?"
3031                            "\\([eE][-+]?[0-9]+\\)?\\)")
3032                    '(0 mdw-number-face))
3033
3034              ;; And anything else is punctuation.
3035              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3036                    '(0 mdw-punct-face))))))
3037 (progn
3038   (add-hook 'go-mode-hook 'mdw-misc-mode-config t)
3039   (add-hook 'go-mode-hook 'mdw-fontify-go t))
3040
3041 ;;;--------------------------------------------------------------------------
3042 ;;; Rust programming configuration.
3043
3044 (setq-default rust-indent-offset 2)
3045
3046 (defun mdw-self-insert-and-indent (count)
3047   (interactive "p")
3048   (self-insert-command count)
3049   (indent-according-to-mode))
3050
3051 (defun mdw-fontify-rust ()
3052
3053   ;; Hack syntax categories.
3054   (modify-syntax-entry ?$ ".")
3055   (modify-syntax-entry ?% ".")
3056   (modify-syntax-entry ?= ".")
3057
3058   ;; Fontify keywords and things.
3059   (make-local-variable 'font-lock-keywords)
3060   (let ((rust-keywords
3061          (mdw-regexps "abstract" "alignof" "as" "async" "await"
3062                       "become" "box" "break"
3063                       "const" "continue" "crate"
3064                       "do" "dyn"
3065                       "else" "enum" "extern"
3066                       "final" "fn" "for"
3067                       "if" "impl" "in"
3068                       "let" "loop"
3069                       "macro" "match" "mod" "move" "mut"
3070                       "offsetof" "override"
3071                       "priv" "proc" "pub" "pure"
3072                       "ref" "return"
3073                       "sizeof" "static" "struct" "super"
3074                       "trait" "try" "type" "typeof"
3075                       "union" "unsafe" "unsized" "use"
3076                       "virtual"
3077                       "where" "while"
3078                       "yield"))
3079         (rust-builtins
3080          (mdw-regexps "array" "pointer" "slice" "tuple"
3081                       "bool" "true" "false"
3082                       "f32" "f64"
3083                       "i8" "i16" "i32" "i64" "isize"
3084                       "u8" "u16" "u32" "u64" "usize"
3085                       "char" "str"
3086                       "self" "Self")))
3087     (setq font-lock-keywords
3088             (list
3089
3090              ;; Handle the keywords defined above.
3091              (list (concat "\\_<\\(" rust-keywords "\\)\\_>")
3092                    '(0 font-lock-keyword-face))
3093              (list (concat "\\_<\\(" rust-builtins "\\)\\_>")
3094                    '(0 font-lock-variable-name-face))
3095
3096              ;; Handle numbers too.
3097              (list (concat "\\_<\\("
3098                                  "[0-9][0-9_]*"
3099                                  "\\(" "\\(\\.[0-9_]+\\)?[eE][-+]?[0-9_]+"
3100                                  "\\|" "\\.[0-9_]+"
3101                                  "\\)"
3102                                  "\\(f32\\|f64\\)?"
3103                            "\\|" "\\(" "[0-9][0-9_]*"
3104                                  "\\|" "0x[0-9a-fA-F_]+"
3105                                  "\\|" "0o[0-7_]+"
3106                                  "\\|" "0b[01_]+"
3107                                  "\\)"
3108                                  "\\([ui]\\(8\\|16\\|32\\|64\\|size\\)\\)?"
3109                            "\\)\\_>")
3110                    '(0 mdw-number-face))
3111
3112              ;; And anything else is punctuation.
3113              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3114                    '(0 mdw-punct-face)))))
3115
3116   ;; Hack key bindings.
3117   (local-set-key [?{] 'mdw-self-insert-and-indent)
3118   (local-set-key [?}] 'mdw-self-insert-and-indent))
3119
3120 (progn
3121   (add-hook 'rust-mode-hook 'mdw-misc-mode-config t)
3122   (add-hook 'rust-mode-hook 'mdw-fontify-rust t))
3123
3124 ;;;--------------------------------------------------------------------------
3125 ;;; Awk programming configuration.
3126
3127 ;; Make Awk indentation nice.
3128
3129 (mdw-define-c-style mdw-awk ()
3130   (c-basic-offset . 2)
3131   (c-offsets-alist (substatement-open . 0)
3132                    (c-backslash-column . 72)
3133                    (statement-cont . 0)
3134                    (statement-case-intro . +)))
3135 (mdw-set-default-c-style 'awk-mode 'mdw-awk)
3136
3137 ;; Declare Awk fontification style.
3138
3139 (defun mdw-fontify-awk ()
3140
3141   ;; Miscellaneous fiddling.
3142   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
3143
3144   ;; Now define things to be fontified.
3145   (make-local-variable 'font-lock-keywords)
3146   (let ((c-keywords
3147          (mdw-regexps "BEGIN" "END" "ARGC" "ARGIND" "ARGV" "CONVFMT"
3148                       "ENVIRON" "ERRNO" "FIELDWIDTHS" "FILENAME" "FNR"
3149                       "FS" "IGNORECASE" "NF" "NR" "OFMT" "OFS" "ORS" "RS"
3150                       "RSTART" "RLENGTH" "RT"   "SUBSEP"
3151                       "atan2" "break" "close" "continue" "cos" "delete"
3152                       "do" "else" "exit" "exp" "fflush" "file" "for" "func"
3153                       "function" "gensub" "getline" "gsub" "if" "in"
3154                       "index" "int" "length" "log" "match" "next" "rand"
3155                       "return" "print" "printf" "sin" "split" "sprintf"
3156                       "sqrt" "srand" "strftime" "sub" "substr" "system"
3157                       "systime" "tolower" "toupper" "while")))
3158
3159     (setq font-lock-keywords
3160             (list
3161
3162              ;; Handle the keywords defined above.
3163              (list (concat "\\<\\(" c-keywords "\\)\\>")
3164                    '(0 font-lock-keyword-face))
3165
3166              ;; Handle numbers too.
3167              ;;
3168              ;; The following isn't quite right, but it's close enough.
3169              (list (concat "\\<\\("
3170                            "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
3171                            "[0-9]+\\(\\.[0-9]*\\)?"
3172                            "\\([eE][-+]?[0-9]+\\)?\\)"
3173                            "[uUlL]*")
3174                    '(0 mdw-number-face))
3175
3176              ;; And anything else is punctuation.
3177              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3178                    '(0 mdw-punct-face))))))
3179
3180 (progn
3181   (add-hook 'awk-mode-hook 'mdw-misc-mode-config t)
3182   (add-hook 'awk-mode-hook 'mdw-fontify-awk t))
3183
3184 ;;;--------------------------------------------------------------------------
3185 ;;; Perl programming style.
3186
3187 ;; Perl indentation style.
3188
3189 (setq-default perl-indent-level 2)
3190
3191 (setq-default cperl-indent-level 2
3192               cperl-continued-statement-offset 2
3193               cperl-indent-region-fix-constructs nil
3194               cperl-continued-brace-offset 0
3195               cperl-brace-offset -2
3196               cperl-brace-imaginary-offset 0
3197               cperl-label-offset 0)
3198
3199 ;; Define perl fontification style.
3200
3201 (defun mdw-fontify-perl ()
3202
3203   ;; Miscellaneous fiddling.
3204   (modify-syntax-entry ?$ "\\")
3205   (modify-syntax-entry ?$ "\\" font-lock-syntax-table)
3206   (modify-syntax-entry ?: "." font-lock-syntax-table)
3207   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
3208
3209   ;; Now define fontification things.
3210   (make-local-variable 'font-lock-keywords)
3211   (let ((perl-keywords
3212          (mdw-regexps "and"
3213                       "break"
3214                       "cmp" "continue"
3215                       "default" "do"
3216                       "else" "elsif" "eq"
3217                       "for" "foreach"
3218                       "ge" "given" "gt" "goto"
3219                       "if"
3220                       "last" "le" "local" "lt"
3221                       "my"
3222                       "ne" "next"
3223                       "or" "our"
3224                       "package"
3225                       "redo" "require" "return"
3226                       "sub"
3227                       "undef" "unless" "until" "use"
3228                       "when" "while")))
3229
3230     (setq font-lock-keywords
3231             (list
3232
3233              ;; Set up the keywords defined above.
3234              (list (concat "\\<\\(" perl-keywords "\\)\\>")
3235                    '(0 font-lock-keyword-face))
3236
3237              ;; At least numbers are simpler than C.
3238              (list (concat "\\<0\\([xX][0-9a-fA-F_]+\\|[0-7_]+\\)\\|"
3239                            "\\<[0-9][0-9_]*\\(\\.[0-9_]*\\)?"
3240                            "\\([eE][-+]?[0-9_]+\\)?")
3241                    '(0 mdw-number-face))
3242
3243              ;; And anything else is punctuation.
3244              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3245                    '(0 mdw-punct-face))))))
3246
3247 (defun perl-number-tests (&optional arg)
3248   "Assign consecutive numbers to lines containing `#t'.  With ARG,
3249 strip numbers instead."
3250   (interactive "P")
3251   (save-excursion
3252     (goto-char (point-min))
3253     (let ((i 0) (fmt (if arg "" " %4d")))
3254       (while (search-forward "#t" nil t)
3255         (delete-region (point) (line-end-position))
3256         (setq i (1+ i))
3257         (insert (format fmt i)))
3258       (goto-char (point-min))
3259       (if (re-search-forward "\\(tests\\s-*=>\\s-*\\)\\w*" nil t)
3260           (replace-match (format "\\1%d" i))))))
3261
3262 (dolist (hook '(perl-mode-hook cperl-mode-hook))
3263   (add-hook hook 'mdw-misc-mode-config t)
3264   (add-hook hook 'mdw-fontify-perl t))
3265
3266 ;;;--------------------------------------------------------------------------
3267 ;;; Python programming style.
3268
3269 (setq-default py-indent-offset 2
3270               python-indent 2
3271               python-indent-offset 2
3272               python-fill-docstring-style 'symmetric)
3273
3274 (defun mdw-fontify-pythonic (keywords)
3275
3276   ;; Miscellaneous fiddling.
3277   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
3278   (setq indent-tabs-mode nil)
3279   (set (make-local-variable 'forward-sexp-function) nil)
3280
3281   ;; Now define fontification things.
3282   (make-local-variable 'font-lock-keywords)
3283   (setq font-lock-keywords
3284           (list
3285
3286            ;; Set up the keywords defined above.
3287            (list (concat "\\_<\\(" keywords "\\)\\_>")
3288                  '(0 font-lock-keyword-face))
3289
3290            ;; At least numbers are simpler than C.
3291            (list (concat "\\_<0\\([xX][0-9a-fA-F]+\\|[oO]?[0-7]+\\|[bB][01]+\\)\\|"
3292                          "\\_<[0-9][0-9]*\\(\\.[0-9]*\\)?"
3293                          "\\([eE][-+]?[0-9]+\\|[lL]\\)?")
3294                  '(0 mdw-number-face))
3295
3296            ;; And anything else is punctuation.
3297            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3298                  '(0 mdw-punct-face)))))
3299
3300 ;; Define Python fontification styles.
3301
3302 (defun mdw-fontify-python ()
3303   (mdw-fontify-pythonic
3304    (mdw-regexps "and" "as" "assert" "break" "class" "continue" "def"
3305                 "del" "elif" "else" "except" "exec" "finally" "for"
3306                 "from" "global" "if" "import" "in" "is" "lambda"
3307                 "not" "or" "pass" "print" "raise" "return" "try"
3308                 "while" "with" "yield")))
3309
3310 (defun mdw-fontify-pyrex ()
3311   (mdw-fontify-pythonic
3312    (mdw-regexps "and" "as" "assert" "break" "cdef" "class" "continue"
3313                 "ctypedef" "def" "del" "elif" "else" "enum" "except" "exec"
3314                 "extern" "finally" "for" "from" "global" "if"
3315                 "import" "in" "is" "lambda" "not" "or" "pass" "print"
3316                 "property" "raise" "return" "struct" "try" "while" "with"
3317                 "yield")))
3318
3319 (define-derived-mode pyrex-mode python-mode "Pyrex"
3320   "Major mode for editing Pyrex source code")
3321 (setq auto-mode-alist
3322         (append '(("\\.pyx$" . pyrex-mode)
3323                   ("\\.pxd$" . pyrex-mode)
3324                   ("\\.pxi$" . pyrex-mode))
3325                 auto-mode-alist))
3326
3327 (progn
3328   (add-hook 'python-mode-hook 'mdw-misc-mode-config t)
3329   (add-hook 'python-mode-hook 'mdw-fontify-python t)
3330   (add-hook 'pyrex-mode-hook 'mdw-fontify-pyrex t))
3331
3332 ;;;--------------------------------------------------------------------------
3333 ;;; Lua programming style.
3334
3335 (setq-default lua-indent-level 2)
3336
3337 (defun mdw-fontify-lua ()
3338
3339   ;; Miscellaneous fiddling.
3340   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
3341
3342   ;; Now define fontification things.
3343   (make-local-variable 'font-lock-keywords)
3344   (let ((lua-keywords
3345          (mdw-regexps "and" "break" "do" "else" "elseif" "end"
3346                       "false" "for" "function" "goto" "if" "in" "local"
3347                       "nil" "not" "or" "repeat" "return" "then" "true"
3348                       "until" "while")))
3349     (setq font-lock-keywords
3350             (list
3351
3352              ;; Set up the keywords defined above.
3353              (list (concat "\\_<\\(" lua-keywords "\\)\\_>")
3354                    '(0 font-lock-keyword-face))
3355
3356              ;; At least numbers are simpler than C.
3357              (list (concat "\\_<\\(" "0[xX]"
3358                                      "\\(" "[0-9a-fA-F]+"
3359                                            "\\(\\.[0-9a-fA-F]*\\)?"
3360                                      "\\|" "\\.[0-9a-fA-F]+"
3361                                      "\\)"
3362                                      "\\([pP][-+]?[0-9]+\\)?"
3363                                "\\|" "\\(" "[0-9]+"
3364                                            "\\(\\.[0-9]*\\)?"
3365                                      "\\|" "\\.[0-9]+"
3366                                      "\\)"
3367                                      "\\([eE][-+]?[0-9]+\\)?"
3368                                "\\)")
3369                    '(0 mdw-number-face))
3370
3371              ;; And anything else is punctuation.
3372              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3373                    '(0 mdw-punct-face))))))
3374
3375 (progn
3376   (add-hook 'lua-mode-hook 'mdw-misc-mode-config t)
3377   (add-hook 'lua-mode-hook 'mdw-fontify-lua t))
3378
3379 ;;;--------------------------------------------------------------------------
3380 ;;; Icon programming style.
3381
3382 ;; Icon indentation style.
3383
3384 (setq-default icon-brace-offset 0
3385               icon-continued-brace-offset 0
3386               icon-continued-statement-offset 2
3387               icon-indent-level 2)
3388
3389 ;; Define Icon fontification style.
3390
3391 (defun mdw-fontify-icon ()
3392
3393   ;; Miscellaneous fiddling.
3394   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
3395
3396   ;; Now define fontification things.
3397   (make-local-variable 'font-lock-keywords)
3398   (let ((icon-keywords
3399          (mdw-regexps "break" "by" "case" "create" "default" "do" "else"
3400                       "end" "every" "fail" "global" "if" "initial"
3401                       "invocable" "link" "local" "next" "not" "of"
3402                       "procedure" "record" "repeat" "return" "static"
3403                       "suspend" "then" "to" "until" "while"))
3404         (preprocessor-keywords
3405          (mdw-regexps "define" "else" "endif" "error" "ifdef" "ifndef"
3406                       "include" "line" "undef")))
3407     (setq font-lock-keywords
3408             (list
3409
3410              ;; Set up the keywords defined above.
3411              (list (concat "\\<\\(" icon-keywords "\\)\\>")
3412                    '(0 font-lock-keyword-face))
3413
3414              ;; The things that Icon calls keywords.
3415              (list "&\\sw+\\>" '(0 font-lock-variable-name-face))
3416
3417              ;; At least numbers are simpler than C.
3418              (list (concat "\\<[0-9]+"
3419                            "\\([rR][0-9a-zA-Z]+\\|"
3420                            "\\.[0-9]+\\([eE][+-]?[0-9]+\\)?\\)\\>\\|"
3421                            "\\.[0-9]+\\([eE][+-]?[0-9]+\\)?\\>")
3422                    '(0 mdw-number-face))
3423
3424              ;; Preprocessor.
3425              (list (concat "^[ \t]*$[ \t]*\\<\\("
3426                            preprocessor-keywords
3427                            "\\)\\>")
3428                    '(0 font-lock-keyword-face))
3429
3430              ;; And anything else is punctuation.
3431              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3432                    '(0 mdw-punct-face))))))
3433
3434 (progn
3435   (add-hook 'icon-mode-hook 'mdw-misc-mode-config t)
3436   (add-hook 'icon-mode-hook 'mdw-fontify-icon t))
3437
3438 ;;;--------------------------------------------------------------------------
3439 ;;; Fortran mode.
3440
3441 (defun mdw-fontify-fortran-common ()
3442   (let ((fortran-keywords
3443          (mdw-regexps "access"
3444                       "assign"
3445                       "associate"
3446                       "backspace"
3447                       "blank"
3448                       "block\\s-*data"
3449                       "call"
3450                       "case"
3451                       "character"
3452                       "class"
3453                       "close"
3454                       "common"
3455                       "complex"
3456                       "continue"
3457                       "critical"
3458                       "data"
3459                       "dimension"
3460                       "do"
3461                       "double\\s-*precision"
3462                       "else" "elseif" "elsewhere"
3463                       "end"
3464                         "endblock" "endblockdata"
3465                         "endcritical"
3466                         "enddo"
3467                         "endinterface"
3468                         "endmodule"
3469                         "endprocedure"
3470                         "endprogram"
3471                         "endselect"
3472                         "endsubmodule"
3473                         "endsubroutine"
3474                         "endtype"
3475                         "endwhere"
3476                         "endenum"
3477                         "end\\s-*file"
3478                         "endforall"
3479                         "endfunction"
3480                         "endif"
3481                       "entry"
3482                       "enum"
3483                       "equivalence"
3484                       "err"
3485                       "external"
3486                       "file"
3487                       "fmt"
3488                       "forall"
3489                       "form"
3490                       "format"
3491                       "function"
3492                       "go\\s-*to"
3493                       "if"
3494                       "implicit"
3495                       "in" "inout"
3496                       "inquire"
3497                       "include"
3498                       "integer"
3499                       "interface"
3500                       "intrinsic"
3501                       "iostat"
3502                       "len"
3503                       "logical"
3504                       "module"
3505                       "open"
3506                       "out"
3507                       "parameter"
3508                       "pause"
3509                       "procedure"
3510                       "program"
3511                       "precision"
3512                       "program"
3513                       "read"
3514                       "real"
3515                       "rec"
3516                       "recl"
3517                       "return"
3518                       "rewind"
3519                       "save"
3520                       "select" "selectcase" "selecttype"
3521                       "status"
3522                       "stop"
3523                       "submodule"
3524                       "subroutine"
3525                       "then"
3526                       "to"
3527                       "type"
3528                       "unit"
3529                       "where"
3530                       "write"))
3531         (fortran-operators (mdw-regexps "and"
3532                                         "eq"
3533                                         "eqv"
3534                                         "false"
3535                                         "ge"
3536                                         "gt"
3537                                         "le"
3538                                         "lt"
3539                                         "ne"
3540                                         "neqv"
3541                                         "not"
3542                                         "or"
3543                                         "true"))
3544         (fortran-intrinsics (mdw-regexps "abs" "dabs" "iabs" "cabs"
3545                                          "atan" "datan" "atan2" "datan2"
3546                                          "cmplx"
3547                                          "conjg"
3548                                          "cos" "dcos" "ccos"
3549                                          "dble"
3550                                          "dim" "idim"
3551                                          "exp" "dexp" "cexp"
3552                                          "float"
3553                                          "ifix"
3554                                          "aimag"
3555                                          "int" "aint" "idint"
3556                                          "alog" "dlog" "clog"
3557                                          "alog10" "dlog10"
3558                                          "max"
3559                                          "amax0" "amax1"
3560                                          "max0" "max1"
3561                                          "dmax1"
3562                                          "min"
3563                                          "amin0" "amin1"
3564                                          "min0" "min1"
3565                                          "dmin1"
3566                                          "mod" "amod" "dmod"
3567                                          "sin" "dsin" "csin"
3568                                          "sign" "isign" "dsign"
3569                                          "sngl"
3570                                          "sqrt" "dsqrt" "csqrt"
3571                                          "tanh"))
3572         (preprocessor-keywords
3573          (mdw-regexps "assert" "define" "elif" "else" "endif" "error"
3574                       "ident" "if" "ifdef" "ifndef" "import" "include"
3575                       "line" "pragma" "unassert" "undef" "warning")))
3576     (setq font-lock-keywords-case-fold-search t
3577             font-lock-keywords
3578             (list
3579
3580              ;; Fontify include files as strings.
3581              (list (concat "^[ \t]*\\#[ \t]*" "include"
3582                            "[ \t]*\\(<[^>]+>?\\)")
3583                    '(1 font-lock-string-face))
3584
3585              ;; Preprocessor directives are `references'?.
3586              (list (concat "^\\([ \t]*#[ \t]*\\(\\("
3587                            preprocessor-keywords
3588                            "\\)\\>\\|[0-9]+\\|$\\)\\)")
3589                    '(1 font-lock-keyword-face))
3590
3591              ;; Set up the keywords defined above.
3592              (list (concat "\\<\\(" fortran-keywords "\\)\\>")
3593                    '(0 font-lock-keyword-face))
3594
3595              ;; Set up the `.foo.' operators.
3596              (list (concat "\\.\\(" fortran-operators "\\)\\.")
3597                    '(0 font-lock-keyword-face))
3598
3599              ;; Set up the intrinsic functions.
3600              (list (concat "\\<\\(" fortran-intrinsics "\\)\\>")
3601                    '(0 font-lock-variable-name-face))
3602
3603              ;; Numbers.
3604              (list (concat       "\\(" "\\<" "[0-9]+" "\\(\\.[0-9]*\\)?"
3605                                  "\\|" "\\.[0-9]+"
3606                                  "\\)"
3607                                  "\\(" "[de]" "[+-]?" "[0-9]+" "\\)?"
3608                                  "\\(" "_" "\\sw+" "\\)?"
3609                            "\\|" "b'[01]*'" "\\|" "'[01]*'b"
3610                            "\\|" "b\"[01]*\"" "\\|" "\"[01]*\"b"
3611                            "\\|" "o'[0-7]*'" "\\|" "'[0-7]*'o"
3612                            "\\|" "o\"[0-7]*\"" "\\|" "\"[0-7]*\"o"
3613                            "\\|" "[xz]'[0-9a-f]*'" "\\|" "'[0-9a-f]*'[xz]"
3614                            "\\|" "[xz]\"[0-9a-f]*\"" "\\|" "\"[0-9a-f]*\"[xz]")
3615                    '(0 mdw-number-face))
3616
3617              ;; Any anything else is punctuation.
3618              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3619                    '(0 mdw-punct-face))))
3620
3621     (modify-syntax-entry ?/ "." font-lock-syntax-table)
3622     (modify-syntax-entry ?< ".")
3623     (modify-syntax-entry ?> ".")))
3624
3625 (defun mdw-fontify-fortran () (mdw-fontify-fortran-common))
3626 (defun mdw-fontify-f90 () (mdw-fontify-fortran-common))
3627
3628 (setq fortran-do-indent 2
3629       fortran-if-indent 2
3630       fortran-structure-indent 2
3631       fortran-comment-line-start "*"
3632       fortran-comment-indent-style 'relative
3633       fortran-continuation-string "&"
3634       fortran-continuation-indent 4)
3635
3636 (setq f90-do-indent 2
3637       f90-if-indent 2
3638       f90-program-indent 2
3639       f90-continuation-indent 4
3640       f90-smart-end-names nil
3641       f90-smart-end 'no-blink)
3642
3643 (progn
3644   (add-hook 'fortran-mode-hook 'mdw-misc-mode-config t)
3645   (add-hook 'fortran-mode-hook 'mdw-fontify-fortran t)
3646   (add-hook 'f90-mode-hook 'mdw-misc-mode-config t)
3647   (add-hook 'f90-mode-hook 'mdw-fontify-f90 t))
3648
3649 ;;;--------------------------------------------------------------------------
3650 ;;; Assembler mode.
3651
3652 (defun mdw-fontify-asm ()
3653   (modify-syntax-entry ?' "\"")
3654   (modify-syntax-entry ?. "w")
3655   (modify-syntax-entry ?\n ">")
3656   (setf fill-prefix nil)
3657   (modify-syntax-entry ?. "_")
3658   (modify-syntax-entry ?* ". 23")
3659   (modify-syntax-entry ?/ ". 124b")
3660   (modify-syntax-entry ?\n "> b")
3661   (local-set-key ";" 'self-insert-command)
3662   (mdw-standard-fill-prefix "\\([ \t]*;+[ \t]*\\)"))
3663
3664 (defun mdw-asm-set-comment ()
3665   (modify-syntax-entry ?; "."
3666                        )
3667   (modify-syntax-entry asm-comment-char "< b")
3668   (setq comment-start (string asm-comment-char ? )))
3669 (add-hook 'asm-mode-local-variables-hook 'mdw-asm-set-comment)
3670 (put 'asm-comment-char 'safe-local-variable 'characterp)
3671
3672 (progn
3673   (add-hook 'asm-mode-hook 'mdw-misc-mode-config t)
3674   (add-hook 'asm-mode-hook 'mdw-fontify-asm t))
3675
3676 ;;;--------------------------------------------------------------------------
3677 ;;; TCL configuration.
3678
3679 (setq-default tcl-indent-level 2)
3680
3681 (defun mdw-fontify-tcl ()
3682   (dolist (ch '(?$))
3683     (modify-syntax-entry ch "."))
3684   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
3685   (make-local-variable 'font-lock-keywords)
3686   (setq font-lock-keywords
3687           (list
3688            (list (concat "\\<0\\([xX][0-9a-fA-F_]+\\|[0-7_]+\\)\\|"
3689                          "\\<[0-9][0-9_]*\\(\\.[0-9_]*\\)?"
3690                          "\\([eE][-+]?[0-9_]+\\)?")
3691                  '(0 mdw-number-face))
3692            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3693                  '(0 mdw-punct-face)))))
3694
3695 (progn
3696   (add-hook 'tcl-mode-hook 'mdw-misc-mode-config t)
3697   (add-hook 'tcl-mode-hook 'mdw-fontify-tcl t))
3698
3699 ;;;--------------------------------------------------------------------------
3700 ;;; Dylan programming configuration.
3701
3702 (defun mdw-fontify-dylan ()
3703
3704   (make-local-variable 'font-lock-keywords)
3705
3706   ;; Horrors.  `dylan-mode' sets the `major-mode' name after calling this
3707   ;; hook, which undoes all of our configuration.
3708   (setq major-mode 'dylan-mode)
3709   (font-lock-set-defaults)
3710
3711   (let* ((word "[-_a-zA-Z!*@<>$%]+")
3712          (dylan-keywords (mdw-regexps
3713
3714                           "C-address" "C-callable-wrapper" "C-function"
3715                           "C-mapped-subtype" "C-pointer-type" "C-struct"
3716                           "C-subtype" "C-union" "C-variable"
3717
3718                           "above" "abstract" "afterwards" "all"
3719                           "begin" "below" "block" "by"
3720                           "case" "class" "cleanup" "constant" "create"
3721                           "define" "domain"
3722                           "else" "elseif" "end" "exception" "export"
3723                           "finally" "for" "from" "function"
3724                           "generic"
3725                           "handler"
3726                           "if" "in" "instance" "interface" "iterate"
3727                           "keyed-by"
3728                           "let" "library" "local"
3729                           "macro" "method" "module"
3730                           "otherwise"
3731                           "profiling"
3732                           "select" "slot" "subclass"
3733                           "table" "then" "to"
3734                           "unless" "until" "use"
3735                           "variable" "virtual"
3736                           "when" "while"))
3737          (sharp-keywords (mdw-regexps
3738                           "all-keys" "key" "next" "rest" "include"
3739                           "t" "f")))
3740     (setq font-lock-keywords
3741             (list (list (concat "\\<\\(" dylan-keywords
3742                                 "\\|" "with\\(out\\)?-" word
3743                                 "\\)\\>")
3744                         '(0 font-lock-keyword-face))
3745                   (list (concat "\\<" word ":" "\\|"
3746                                 "#\\(" sharp-keywords "\\)\\>")
3747                         '(0 font-lock-variable-name-face))
3748                   (list (concat "\\("
3749                                 "\\([-+]\\|\\<\\)[0-9]+" "\\("
3750                                   "\\(\\.[0-9]+\\)?" "\\([eE][-+][0-9]+\\)?"
3751                                   "\\|" "/[0-9]+"
3752                                 "\\)"
3753                                 "\\|" "\\.[0-9]+" "\\([eE][-+][0-9]+\\)?"
3754                                 "\\|" "#b[01]+"
3755                                 "\\|" "#o[0-7]+"
3756                                 "\\|" "#x[0-9a-zA-Z]+"
3757                                 "\\)\\>")
3758                         '(0 mdw-number-face))
3759                   (list (concat "\\("
3760                                 "\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\|"
3761                                 "\\_<[-+*/=<>:&|]+\\_>"
3762                                 "\\)")
3763                         '(0 mdw-punct-face))))))
3764
3765 (progn
3766   (add-hook 'dylan-mode-hook 'mdw-misc-mode-config t)
3767   (add-hook 'dylan-mode-hook 'mdw-fontify-dylan t))
3768
3769 ;;;--------------------------------------------------------------------------
3770 ;;; Algol 68 configuration.
3771
3772 (setq-default a68-indent-step 2)
3773
3774 (defun mdw-fontify-algol-68 ()
3775
3776   ;; Fix up the syntax table.
3777   (modify-syntax-entry ?# "!" a68-mode-syntax-table)
3778   (dolist (ch '(?- ?+ ?= ?< ?> ?* ?/ ?| ?&))
3779     (modify-syntax-entry ch "." a68-mode-syntax-table))
3780
3781   (make-local-variable 'font-lock-keywords)
3782
3783   (let ((not-comment
3784          (let ((word "COMMENT"))
3785            (do ((regexp (concat "[^" (substring word 0 1) "]+")
3786                         (concat regexp "\\|"
3787                                 (substring word 0 i)
3788                                 "[^" (substring word i (1+ i)) "]"))
3789                 (i 1 (1+ i)))
3790                ((>= i (length word)) regexp)))))
3791     (setq font-lock-keywords
3792             (list (list (concat "\\<COMMENT\\>"
3793                                 "\\(" not-comment "\\)\\{0,5\\}"
3794                                 "\\(\\'\\|\\<COMMENT\\>\\)")
3795                         '(0 font-lock-comment-face))
3796                   (list (concat "\\<CO\\>"
3797                                 "\\([^C]+\\|C[^O]\\)\\{0,5\\}"
3798                                 "\\($\\|\\<CO\\>\\)")
3799                         '(0 font-lock-comment-face))
3800                   (list "\\<[A-Z_]+\\>"
3801                         '(0 font-lock-keyword-face))
3802                   (list (concat "\\<"
3803                                 "[0-9]+"
3804                                 "\\(\\.[0-9]+\\)?"
3805                                 "\\([eE][-+]?[0-9]+\\)?"
3806                                 "\\>")
3807                         '(0 mdw-number-face))
3808                   (list "\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/"
3809                         '(0 mdw-punct-face))))))
3810
3811 (dolist (hook '(a68-mode-hook a68-mode-hooks))
3812   (add-hook hook 'mdw-misc-mode-config t)
3813   (add-hook hook 'mdw-fontify-algol-68 t))
3814
3815 ;;;--------------------------------------------------------------------------
3816 ;;; REXX configuration.
3817
3818 (defun mdw-rexx-electric-* ()
3819   (interactive)
3820   (insert ?*)
3821   (rexx-indent-line))
3822
3823 (defun mdw-rexx-indent-newline-indent ()
3824   (interactive)
3825   (rexx-indent-line)
3826   (if abbrev-mode (expand-abbrev))
3827   (newline-and-indent))
3828
3829 (defun mdw-fontify-rexx ()
3830
3831   ;; Various bits of fiddling.
3832   (setq mdw-auto-indent nil)
3833   (local-set-key [?\C-m] 'mdw-rexx-indent-newline-indent)
3834   (local-set-key [?*] 'mdw-rexx-electric-*)
3835   (dolist (ch '(?! ?? ?# ?@ ?$)) (modify-syntax-entry ch "w"))
3836   (dolist (ch '(?¬)) (modify-syntax-entry ch "."))
3837   (mdw-standard-fill-prefix "\\([ \t]*/?\*[ \t]*\\)")
3838
3839   ;; Set up keywords and things for fontification.
3840   (make-local-variable 'font-lock-keywords-case-fold-search)
3841   (setq font-lock-keywords-case-fold-search t)
3842
3843   (setq rexx-indent 2)
3844   (setq rexx-end-indent rexx-indent)
3845   (setq rexx-cont-indent rexx-indent)
3846
3847   (make-local-variable 'font-lock-keywords)
3848   (let ((rexx-keywords
3849          (mdw-regexps "address" "arg" "by" "call" "digits" "do" "drop"
3850                       "else" "end" "engineering" "exit" "expose" "for"
3851                       "forever" "form" "fuzz" "if" "interpret" "iterate"
3852                       "leave" "linein" "name" "nop" "numeric" "off" "on"
3853                       "options" "otherwise" "parse" "procedure" "pull"
3854                       "push" "queue" "return" "say" "select" "signal"
3855                       "scientific" "source" "then" "trace" "to" "until"
3856                       "upper" "value" "var" "version" "when" "while"
3857                       "with"
3858
3859                       "abbrev" "abs" "bitand" "bitor" "bitxor" "b2x"
3860                       "center" "center" "charin" "charout" "chars"
3861                       "compare" "condition" "copies" "c2d" "c2x"
3862                       "datatype" "date" "delstr" "delword" "d2c" "d2x"
3863                       "errortext" "format" "fuzz" "insert" "lastpos"
3864                       "left" "length" "lineout" "lines" "max" "min"
3865                       "overlay" "pos" "queued" "random" "reverse" "right"
3866                       "sign" "sourceline" "space" "stream" "strip"
3867                       "substr" "subword" "symbol" "time" "translate"
3868                       "trunc" "value" "verify" "word" "wordindex"
3869                       "wordlength" "wordpos" "words" "xrange" "x2b" "x2c"
3870                       "x2d")))
3871
3872     (setq font-lock-keywords
3873             (list
3874
3875              ;; Set up the keywords defined above.
3876              (list (concat "\\<\\(" rexx-keywords "\\)\\>")
3877                    '(0 font-lock-keyword-face))
3878
3879              ;; Fontify all symbols the same way.
3880              (list (concat "\\<\\([0-9.][A-Za-z0-9.!?_#@$]*[Ee][+-]?[0-9]+\\|"
3881                            "[A-Za-z0-9.!?_#@$]+\\)")
3882                    '(0 font-lock-variable-name-face))
3883
3884              ;; And everything else is punctuation.
3885              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3886                    '(0 mdw-punct-face))))))
3887
3888 (progn
3889   (add-hook 'rexx-mode-hook 'mdw-misc-mode-config t)
3890   (add-hook 'rexx-mode-hook 'mdw-fontify-rexx t))
3891
3892 ;;;--------------------------------------------------------------------------
3893 ;;; Standard ML programming style.
3894
3895 (setq-default sml-nested-if-indent t
3896               sml-case-indent nil
3897               sml-indent-level 4
3898               sml-type-of-indent nil)
3899
3900 (defun mdw-fontify-sml ()
3901
3902   ;; Make underscore an honorary letter.
3903   (modify-syntax-entry ?' "w")
3904
3905   ;; Set fill prefix.
3906   (mdw-standard-fill-prefix "\\([ \t]*(\*[ \t]*\\)")
3907
3908   ;; Now define fontification things.
3909   (make-local-variable 'font-lock-keywords)
3910   (let ((sml-keywords
3911          (mdw-regexps "abstype" "and" "andalso" "as"
3912                       "case"
3913                       "datatype" "do"
3914                       "else" "end" "eqtype" "exception"
3915                       "fn" "fun" "functor"
3916                       "handle"
3917                       "if" "in" "include" "infix" "infixr"
3918                       "let" "local"
3919                       "nonfix"
3920                       "of" "op" "open" "orelse"
3921                       "raise" "rec"
3922                       "sharing" "sig" "signature" "struct" "structure"
3923                       "then" "type"
3924                       "val"
3925                       "where" "while" "with" "withtype")))
3926
3927     (setq font-lock-keywords
3928             (list
3929
3930              ;; Set up the keywords defined above.
3931              (list (concat "\\<\\(" sml-keywords "\\)\\>")
3932                    '(0 font-lock-keyword-face))
3933
3934              ;; At least numbers are simpler than C.
3935              (list (concat "\\<\\~?"
3936                               "\\(0\\([wW]?[xX][0-9a-fA-F]+\\|"
3937                                      "[wW][0-9]+\\)\\|"
3938                                   "\\([0-9]+\\(\\.[0-9]+\\)?"
3939                                            "\\([eE]\\~?"
3940                                                   "[0-9]+\\)?\\)\\)")
3941                    '(0 mdw-number-face))
3942
3943              ;; And anything else is punctuation.
3944              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3945                    '(0 mdw-punct-face))))))
3946
3947 (progn
3948   (add-hook 'sml-mode-hook 'mdw-misc-mode-config t)
3949   (add-hook 'sml-mode-hook 'mdw-fontify-sml t))
3950
3951 ;;;--------------------------------------------------------------------------
3952 ;;; Haskell configuration.
3953
3954 (setq-default haskell-indent-offset 2)
3955
3956 (defun mdw-fontify-haskell ()
3957
3958   ;; Fiddle with syntax table to get comments right.
3959   (modify-syntax-entry ?' "_")
3960   (modify-syntax-entry ?- ". 12")
3961   (modify-syntax-entry ?\n ">")
3962
3963   ;; Make punctuation be punctuation
3964   (let ((punct "=<>+-*/|&%!@?$.^:#`"))
3965     (do ((i 0 (1+ i)))
3966         ((>= i (length punct)))
3967       (modify-syntax-entry (aref punct i) ".")))
3968
3969   ;; Set fill prefix.
3970   (mdw-standard-fill-prefix "\\([ \t]*{?--?[ \t]*\\)")
3971
3972   ;; Fiddle with fontification.
3973   (make-local-variable 'font-lock-keywords)
3974   (let ((haskell-keywords
3975          (mdw-regexps "as"
3976                       "case" "ccall" "class"
3977                       "data" "default" "deriving" "do"
3978                       "else" "exists"
3979                       "forall" "foreign"
3980                       "hiding"
3981                       "if" "import" "in" "infix" "infixl" "infixr" "instance"
3982                       "let"
3983                       "mdo" "module"
3984                       "newtype"
3985                       "of"
3986                       "proc"
3987                       "qualified"
3988                       "rec"
3989                       "safe" "stdcall"
3990                       "then" "type"
3991                       "unsafe"
3992                       "where"))
3993         (control-sequences
3994          (mdw-regexps "ACK" "BEL" "BS" "CAN" "CR" "DC1" "DC2" "DC3" "DC4"
3995                       "DEL" "DLE" "EM" "ENQ" "EOT" "ESC" "ETB" "ETX" "FF"
3996                       "FS" "GS" "HT" "LF" "NAK" "NUL" "RS" "SI" "SO" "SOH"
3997                       "SP" "STX" "SUB" "SYN" "US" "VT")))
3998
3999     (setq font-lock-keywords
4000             (list
4001              (list (concat "{-" "[^-]*" "\\(-+[^-}][^-]*\\)*"
4002                                 "\\(-+}\\|-*\\'\\)"
4003                            "\\|"
4004                            "--.*$")
4005                    '(0 font-lock-comment-face))
4006              (list (concat "\\_<\\(" haskell-keywords "\\)\\_>")
4007                    '(0 font-lock-keyword-face))
4008              (list (concat "'\\("
4009                            "[^\\]"
4010                            "\\|"
4011                            "\\\\"
4012                            "\\(" "[abfnrtv\\\"']" "\\|"
4013                                  "^" "\\(" control-sequences "\\|"
4014                                            "[]A-Z@[\\^_]" "\\)" "\\|"
4015                                  "\\|"
4016                                  "[0-9]+" "\\|"
4017                                  "[oO][0-7]+" "\\|"
4018                                  "[xX][0-9A-Fa-f]+"
4019                            "\\)"
4020                            "\\)'")
4021                    '(0 font-lock-string-face))
4022              (list "\\_<[A-Z]\\(\\sw+\\|\\s_+\\)*\\_>"
4023                    '(0 font-lock-variable-name-face))
4024              (list (concat "\\_<0\\([xX][0-9a-fA-F]+\\|[oO][0-7]+\\)\\|"
4025                            "\\_<[0-9]+\\(\\.[0-9]*\\)?"
4026                            "\\([eE][-+]?[0-9]+\\)?")
4027                    '(0 mdw-number-face))
4028              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
4029                    '(0 mdw-punct-face))))))
4030
4031 (progn
4032   (add-hook 'haskell-mode-hook 'mdw-misc-mode-config t)
4033   (add-hook 'haskell-mode-hook 'mdw-fontify-haskell t))
4034
4035 ;;;--------------------------------------------------------------------------
4036 ;;; Erlang configuration.
4037
4038 (setq-default erlang-electric-commands nil)
4039
4040 (defun mdw-fontify-erlang ()
4041
4042   ;; Set fill prefix.
4043   (mdw-standard-fill-prefix "\\([ \t]*{?%*[ \t]*\\)")
4044
4045   ;; Fiddle with fontification.
4046   (make-local-variable 'font-lock-keywords)
4047   (let ((erlang-keywords
4048          (mdw-regexps "after" "and" "andalso"
4049                       "band" "begin" "bnot" "bor" "bsl" "bsr" "bxor"
4050                       "case" "catch" "cond"
4051                       "div" "end" "fun" "if" "let" "not"
4052                       "of" "or" "orelse"
4053                       "query" "receive" "rem" "try" "when" "xor")))
4054
4055     (setq font-lock-keywords
4056             (list
4057              (list "%.*$"
4058                    '(0 font-lock-comment-face))
4059              (list (concat "\\<\\(" erlang-keywords "\\)\\>")
4060                    '(0 font-lock-keyword-face))
4061              (list (concat "^-\\sw+\\>")
4062                    '(0 font-lock-keyword-face))
4063              (list "\\<[0-9]+\\(#[0-9a-zA-Z]+\\|[eE][+-]?[0-9]+\\)?\\>"
4064                    '(0 mdw-number-face))
4065              (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
4066                    '(0 mdw-punct-face))))))
4067
4068 (progn
4069   (add-hook 'erlang-mode-hook 'mdw-misc-mode-config t)
4070   (add-hook 'erlang-mode-hook 'mdw-fontify-erlang t))
4071
4072 ;;;--------------------------------------------------------------------------
4073 ;;; Texinfo configuration.
4074
4075 (defun mdw-fontify-texinfo ()
4076
4077   ;; Set fill prefix.
4078   (mdw-standard-fill-prefix "\\([ \t]*@c[ \t]+\\)")
4079
4080   ;; Real fontification things.
4081   (make-local-variable 'font-lock-keywords)
4082   (setq font-lock-keywords
4083           (list
4084
4085            ;; Environment names are keywords.
4086            (list "@\\(end\\)  *\\([a-zA-Z]*\\)?"
4087                  '(2 font-lock-keyword-face))
4088
4089            ;; Unmark escaped magic characters.
4090            (list "\\(@\\)\\([@{}]\\)"
4091                  '(1 font-lock-keyword-face)
4092                  '(2 font-lock-variable-name-face))
4093
4094            ;; Make sure we get comments properly.
4095            (list "@c\\(omment\\)?\\( .*\\)?$"
4096                  '(0 font-lock-comment-face))
4097
4098            ;; Command names are keywords.
4099            (list "@\\([^a-zA-Z@]\\|[a-zA-Z@]*\\)"
4100                  '(0 font-lock-keyword-face))
4101
4102            ;; Fontify TeX special characters as punctuation.
4103            (list "[{}]+"
4104                  '(0 mdw-punct-face)))))
4105
4106 (dolist (hook '(texinfo-mode-hook TeXinfo-mode-hook))
4107   (add-hook hook 'mdw-misc-mode-config t)
4108   (add-hook hook 'mdw-fontify-texinfo t))
4109
4110 ;;;--------------------------------------------------------------------------
4111 ;;; TeX and LaTeX configuration.
4112
4113 (setq-default LaTeX-table-label "tbl:"
4114               TeX-auto-untabify nil
4115               LaTeX-syntactic-comments nil
4116               LaTeX-fill-break-at-separators '(\\\[))
4117
4118 (defun mdw-fontify-tex ()
4119   (setq ispell-parser 'tex)
4120   (turn-on-reftex)
4121
4122   ;; Don't make maths into a string.
4123   (modify-syntax-entry ?$ ".")
4124   (modify-syntax-entry ?$ "." font-lock-syntax-table)
4125   (local-set-key [?$] 'self-insert-command)
4126
4127   ;; Make `tab' be useful, given that tab stops in TeX don't work well.
4128   (local-set-key "\C-\M-i" 'indent-relative)
4129   (setq indent-tabs-mode nil)
4130
4131   ;; Set fill prefix.
4132   (mdw-standard-fill-prefix "\\([ \t]*%+[ \t]*\\)")
4133
4134   ;; Real fontification things.
4135   (make-local-variable 'font-lock-keywords)
4136   (setq font-lock-keywords
4137           (list
4138
4139            ;; Environment names are keywords.
4140            (list (concat "\\\\\\(begin\\|end\\|newenvironment\\)"
4141                          "{\\([^}\n]*\\)}")
4142                  '(2 font-lock-keyword-face))
4143
4144            ;; Suspended environment names are keywords too.
4145            (list (concat "\\\\\\(suspend\\|resume\\)\\(\\[[^]]*\\]\\)?"
4146                          "{\\([^}\n]*\\)}")
4147                  '(3 font-lock-keyword-face))
4148
4149            ;; Command names are keywords.
4150            (list "\\\\\\([^a-zA-Z@]\\|[a-zA-Z@]*\\)"
4151                  '(0 font-lock-keyword-face))
4152
4153            ;; Handle @/.../ for italics.
4154            ;; (list "\\(@/\\)\\([^/]*\\)\\(/\\)"
4155            ;;     '(1 font-lock-keyword-face)
4156            ;;     '(3 font-lock-keyword-face))
4157
4158            ;; Handle @*...* for boldness.
4159            ;; (list "\\(@\\*\\)\\([^*]*\\)\\(\\*\\)"
4160            ;;     '(1 font-lock-keyword-face)
4161            ;;     '(3 font-lock-keyword-face))
4162
4163            ;; Handle @`...' for literal syntax things.
4164            ;; (list "\\(@`\\)\\([^']*\\)\\('\\)"
4165            ;;     '(1 font-lock-keyword-face)
4166            ;;     '(3 font-lock-keyword-face))
4167
4168            ;; Handle @<...> for nonterminals.
4169            ;; (list "\\(@<\\)\\([^>]*\\)\\(>\\)"
4170            ;;     '(1 font-lock-keyword-face)
4171            ;;     '(3 font-lock-keyword-face))
4172
4173            ;; Handle other @-commands.
4174            ;; (list "@\\([^a-zA-Z]\\|[a-zA-Z]*\\)"
4175            ;;     '(0 font-lock-keyword-face))
4176
4177            ;; Make sure we get comments properly.
4178            (list "%.*"
4179                  '(0 font-lock-comment-face))
4180
4181            ;; Fontify TeX special characters as punctuation.
4182            (list "[$^_{}#&]"
4183                  '(0 mdw-punct-face)))))
4184
4185 (setq TeX-install-font-lock 'tex-font-setup)
4186
4187 (eval-after-load 'font-latex
4188   '(defun font-latex-jit-lock-force-redisplay (buf start end)
4189      "Compatibility for Emacsen not offering `jit-lock-force-redisplay'."
4190      ;; The following block is an expansion of `jit-lock-force-redisplay'
4191      ;; and involved macros taken from CVS Emacs on 2007-04-28.
4192      (with-current-buffer buf
4193        (let ((modified (buffer-modified-p)))
4194          (unwind-protect
4195              (let ((buffer-undo-list t)
4196                    (inhibit-read-only t)
4197                    (inhibit-point-motion-hooks t)
4198                    (inhibit-modification-hooks t)
4199                    deactivate-mark
4200                    buffer-file-name
4201                    buffer-file-truename)
4202                (put-text-property start end 'fontified t))
4203            (unless modified
4204              (restore-buffer-modified-p nil)))))))
4205
4206 (setq TeX-output-view-style
4207         '(("^dvi$"
4208            ("^landscape$" "^pstricks$\\|^pst-\\|^psfrag$")
4209            "%(o?)dvips -t landscape %d -o && xdg-open %f")
4210           ("^dvi$" "^pstricks$\\|^pst-\\|^psfrag$"
4211            "%(o?)dvips %d -o && xdg-open %f")
4212           ("^dvi$"
4213            ("^a4\\(?:dutch\\|paper\\|wide\\)\\|sem-a4$" "^landscape$")
4214            "%(o?)xdvi %dS -paper a4r -s 0 %d")
4215           ("^dvi$" "^a4\\(?:dutch\\|paper\\|wide\\)\\|sem-a4$"
4216            "%(o?)xdvi %dS -paper a4 %d")
4217           ("^dvi$"
4218            ("^a5\\(?:comb\\|paper\\)$" "^landscape$")
4219            "%(o?)xdvi %dS -paper a5r -s 0 %d")
4220           ("^dvi$" "^a5\\(?:comb\\|paper\\)$" "%(o?)xdvi %dS -paper a5 %d")
4221           ("^dvi$" "^b5paper$" "%(o?)xdvi %dS -paper b5 %d")
4222           ("^dvi$" "^letterpaper$" "%(o?)xdvi %dS -paper us %d")
4223           ("^dvi$" "^legalpaper$" "%(o?)xdvi %dS -paper legal %d")
4224           ("^dvi$" "^executivepaper$" "%(o?)xdvi %dS -paper 7.25x10.5in %d")
4225           ("^dvi$" "." "%(o?)xdvi %dS %d")
4226           ("^pdf$" "." "xdg-open %o")
4227           ("^html?$" "." "sensible-browser %o")))
4228
4229 (setq TeX-view-program-list
4230         '(("mupdf" ("mupdf %o" (mode-io-correlate " %(outpage)")))))
4231
4232 (setq TeX-view-program-selection
4233         '(((output-dvi style-pstricks) "dvips and gv")
4234           (output-dvi "xdvi")
4235           (output-pdf "mupdf")
4236           (output-html "sensible-browser")))
4237
4238 (setq TeX-open-quote "\""
4239       TeX-close-quote "\"")
4240
4241 (setq reftex-use-external-file-finders t
4242       reftex-auto-recenter-toc t)
4243
4244 (setq reftex-label-alist
4245         '(("theorem" ?T "th:" "~\\ref{%s}" t ("theorems?" "th\\.") -2)
4246           ("axiom" ?A "ax:" "~\\ref{%s}" t ("axioms?" "ax\\.") -2)
4247           ("definition" ?D "def:" "~\\ref{%s}" t ("definitions?" "def\\.") -2)
4248           ("proposition" ?P "prop:" "~\\ref{%s}" t
4249            ("propositions?" "prop\\.") -2)
4250           ("lemma" ?L "lem:" "~\\ref{%s}" t ("lemmas?" "lem\\.") -2)
4251           ("example" ?X "eg:" "~\\ref{%s}" t ("examples?") -2)
4252           ("exercise" ?E "ex:" "~\\ref{%s}" t ("exercises?" "ex\\.") -2)
4253           ("enumerate" ?i "i:" "~\\ref{%s}" item ("items?"))))
4254 (setq reftex-section-prefixes
4255         '((0 . "part:")
4256           (1 . "ch:")
4257           (t . "sec:")))
4258
4259 (setq bibtex-field-delimiters 'double-quotes
4260       bibtex-align-at-equal-sign t
4261       bibtex-entry-format '(realign opts-or-alts required-fields
4262                             numerical-fields last-comma delimiters
4263                             unify-case sort-fields braces)
4264       bibtex-sort-ignore-string-entries nil
4265       bibtex-maintain-sorted-entries 'entry-class
4266       bibtex-include-OPTkey t
4267       bibtex-autokey-names-stretch 1
4268       bibtex-autokey-expand-strings t
4269       bibtex-autokey-name-separator "-"
4270       bibtex-autokey-year-length 4
4271       bibtex-autokey-titleword-separator "-"
4272       bibtex-autokey-name-year-separator "-"
4273       bibtex-autokey-year-title-separator ":")
4274
4275 (progn
4276   (dolist (hook '(tex-mode-hook latex-mode-hook
4277                                 TeX-mode-hook LaTeX-mode-hook))
4278     (add-hook hook 'mdw-misc-mode-config t)
4279     (add-hook hook 'mdw-fontify-tex t))
4280   (add-hook 'bibtex-mode-hook (lambda () (setq fill-column 76))))
4281
4282 ;;;--------------------------------------------------------------------------
4283 ;;; HTML, CSS, and other web foolishness.
4284
4285 (setq-default css-indent-offset 8)
4286
4287 ;;;--------------------------------------------------------------------------
4288 ;;; SGML hacking.
4289
4290 (setq-default psgml-html-build-new-buffer nil)
4291
4292 (defun mdw-sgml-mode ()
4293   (interactive)
4294   (sgml-mode)
4295   (mdw-standard-fill-prefix "")
4296   (make-local-variable 'sgml-delimiters)
4297   (setq sgml-delimiters
4298           '("AND" "&" "COM" "--" "CRO" "&#" "DSC" "]" "DSO" "[" "DTGC" "]"
4299             "DTGO" "[" "ERO" "&" "ETAGO" ":e" "GRPC" ")" "GRPO" "(" "LIT"
4300             "\"" "LITA" "'" "MDC" ">" "MDO" "<!" "MINUS" "-" "MSC" "]]"
4301             "NESTC" "{" "NET" "}" "OPT" "?" "OR" "|" "PERO" "%" "PIC" ">"
4302             "PIO" "<?" "PLUS" "+" "REFC" "." "REP" "*" "RNI" "#" "SEQ" ","
4303             "STAGO" ":" "TAGC" "." "VI" "=" "MS-START" "<![" "MS-END" "]]>"
4304             "XML-ECOM" "-->" "XML-PIC" "?>" "XML-SCOM" "<!--" "XML-TAGCE"
4305             "/>" "NULL" ""))
4306   (setq major-mode 'mdw-sgml-mode)
4307   (setq mode-name "[mdw] SGML")
4308   (run-hooks 'mdw-sgml-mode-hook))
4309
4310 ;;;--------------------------------------------------------------------------
4311 ;;; Configuration files.
4312
4313 (defcustom mdw-conf-quote-normal nil
4314   "Control syntax category of quote characters `\"' and `''.
4315 If this is `t', consider quote characters to be normal
4316 punctuation, as for `conf-quote-normal'.  If this is `nil' then
4317 leave quote characters as quotes.  If this is a list, then
4318 consider the quote characters in the list to be normal
4319 punctuation.  If this is a single quote character, then consider
4320 that character only to be normal punctuation."
4321   :type '(choice boolean character (repeat character))
4322   :safe 'mdw-conf-quote-normal-acceptable-value-p)
4323 (defun mdw-conf-quote-normal-acceptable-value-p (value)
4324   "Is the VALUE is an acceptable value for `mdw-conf-quote-normal'?"
4325   (or (booleanp value)
4326       (every (lambda (v) (memq v '(?\" ?')))
4327              (if (listp value) value (list value)))))
4328
4329 (defun mdw-fix-up-quote ()
4330   "Apply the setting of `mdw-conf-quote-normal'."
4331   (let ((flag mdw-conf-quote-normal))
4332     (cond ((eq flag t)
4333            (conf-quote-normal t))
4334           ((not flag)
4335            nil)
4336           (t
4337            (let ((table (copy-syntax-table (syntax-table))))
4338              (dolist (ch (if (listp flag) flag (list flag)))
4339                (modify-syntax-entry ch "." table))
4340              (set-syntax-table table)
4341              (and font-lock-mode (font-lock-fontify-buffer)))))))
4342
4343 (progn
4344   (add-hook 'conf-mode-hook 'mdw-misc-mode-config t)
4345   (add-hook 'conf-mode-local-variables-hook 'mdw-fix-up-quote t t))
4346
4347 ;;;--------------------------------------------------------------------------
4348 ;;; Shell scripts.
4349
4350 (defun mdw-setup-sh-script-mode ()
4351
4352   ;; Fetch the shell interpreter's name.
4353   (let ((shell-name sh-shell-file))
4354
4355     ;; Try reading the hash-bang line.
4356     (save-excursion
4357       (goto-char (point-min))
4358       (if (looking-at "#![ \t]*\\([^ \t\n]*\\)")
4359           (setq shell-name (match-string 1))))
4360
4361     ;; Now try to set the shell.
4362     ;;
4363     ;; Don't let `sh-set-shell' bugger up my script.
4364     (let ((executable-set-magic #'(lambda (s &rest r) s)))
4365       (sh-set-shell shell-name)))
4366
4367   ;; Don't insert here-document scaffolding automatically.
4368   (local-set-key "<" 'self-insert-command)
4369
4370   ;; Now enable my keys and the fontification.
4371   (mdw-misc-mode-config)
4372
4373   ;; Set the indentation level correctly.
4374   (setq sh-indentation 2)
4375   (setq sh-basic-offset 2))
4376
4377 (setq sh-shell-file "/bin/sh")
4378
4379 ;; Awful hacking to override the shell detection for particular scripts.
4380 (defmacro define-custom-shell-mode (name shell)
4381   `(defun ,name ()
4382      (interactive)
4383      (set (make-local-variable 'sh-shell-file) ,shell)
4384      (sh-mode)))
4385 (define-custom-shell-mode bash-mode "/bin/bash")
4386 (define-custom-shell-mode rc-mode "/usr/bin/rc")
4387 (put 'sh-shell-file 'permanent-local t)
4388
4389 ;; Hack the rc syntax table.  Backquotes aren't paired in rc.
4390 (eval-after-load "sh-script"
4391   '(or (assq 'rc sh-mode-syntax-table-input)
4392        (let ((frag '(nil
4393                      ?# "<"
4394                      ?\n ">#"
4395                      ?\" "\"\""
4396                      ?\' "\"\'"
4397                      ?$ "'"
4398                      ?\` "."
4399                      ?! "_"
4400                      ?% "_"
4401                      ?. "_"
4402                      ?^ "_"
4403                      ?~ "_"
4404                      ?, "_"
4405                      ?= "."
4406                      ?< "."
4407                      ?> "."))
4408              (assoc (assq 'rc sh-mode-syntax-table-input)))
4409          (if assoc
4410              (rplacd assoc frag)
4411            (setq sh-mode-syntax-table-input
4412                    (cons (cons 'rc frag)
4413                          sh-mode-syntax-table-input))))))
4414
4415 (progn
4416   (add-hook 'sh-mode-hook 'mdw-misc-mode-config t)
4417   (add-hook 'sh-mode-hook 'mdw-setup-sh-script-mode t))
4418
4419 ;;;--------------------------------------------------------------------------
4420 ;;; Emacs shell mode.
4421
4422 (defun mdw-eshell-prompt ()
4423   (let ((left "[") (right "]"))
4424     (when (= (user-uid) 0)
4425       (setq left "«" right "»"))
4426     (concat left
4427             (save-match-data
4428               (replace-regexp-in-string "\\..*$" "" (system-name)))
4429             " "
4430             (let* ((pwd (eshell/pwd)) (npwd (length pwd))
4431                    (home (expand-file-name "~")) (nhome (length home)))
4432               (if (and (>= npwd nhome)
4433                        (or (= nhome npwd)
4434                            (= (elt pwd nhome) ?/))
4435                        (string= (substring pwd 0 nhome) home))
4436                   (concat "~" (substring pwd (length home)))
4437                 pwd))
4438             right)))
4439 (setq-default eshell-prompt-function 'mdw-eshell-prompt)
4440 (setq-default eshell-prompt-regexp "^\\[[^]>]+\\(\\]\\|>>?\\)")
4441
4442 (defun eshell/e (file) (find-file file) nil)
4443 (defun eshell/ee (file) (find-file-other-window file) nil)
4444 (defun eshell/w3m (url) (w3m-goto-url url) nil)
4445
4446 (mdw-define-face eshell-prompt (t :weight bold))
4447 (mdw-define-face eshell-ls-archive (t :weight bold :foreground "red"))
4448 (mdw-define-face eshell-ls-backup (t :foreground "lightgrey" :slant italic))
4449 (mdw-define-face eshell-ls-product (t :foreground "lightgrey" :slant italic))
4450 (mdw-define-face eshell-ls-clutter (t :foreground "lightgrey" :slant italic))
4451 (mdw-define-face eshell-ls-executable (t :weight bold))
4452 (mdw-define-face eshell-ls-directory (t :foreground "cyan" :weight bold))
4453 (mdw-define-face eshell-ls-readonly (t nil))
4454 (mdw-define-face eshell-ls-symlink (t :foreground "cyan"))
4455
4456 (defun mdw-eshell-hack () (setenv "LD_PRELOAD" nil))
4457 (add-hook 'eshell-mode-hook 'mdw-eshell-hack)
4458
4459 ;;;--------------------------------------------------------------------------
4460 ;;; Messages-file mode.
4461
4462 (defun messages-mode-guts ()
4463   (setq messages-mode-syntax-table (make-syntax-table))
4464   (set-syntax-table messages-mode-syntax-table)
4465   (modify-syntax-entry ?0 "w" messages-mode-syntax-table)
4466   (modify-syntax-entry ?1 "w" messages-mode-syntax-table)
4467   (modify-syntax-entry ?2 "w" messages-mode-syntax-table)
4468   (modify-syntax-entry ?3 "w" messages-mode-syntax-table)
4469   (modify-syntax-entry ?4 "w" messages-mode-syntax-table)
4470   (modify-syntax-entry ?5 "w" messages-mode-syntax-table)
4471   (modify-syntax-entry ?6 "w" messages-mode-syntax-table)
4472   (modify-syntax-entry ?7 "w" messages-mode-syntax-table)
4473   (modify-syntax-entry ?8 "w" messages-mode-syntax-table)
4474   (modify-syntax-entry ?9 "w" messages-mode-syntax-table)
4475   (make-local-variable 'comment-start)
4476   (make-local-variable 'comment-end)
4477   (make-local-variable 'indent-line-function)
4478   (setq indent-line-function 'indent-relative)
4479   (mdw-standard-fill-prefix "\\([ \t]*\\(;\\|/?\\*\\)+[ \t]*\\)")
4480   (make-local-variable 'font-lock-defaults)
4481   (make-local-variable 'messages-mode-keywords)
4482   (let ((keywords
4483          (mdw-regexps "array" "bitmap" "callback" "docs[ \t]+enum"
4484                       "export" "enum" "fixed-octetstring" "flags"
4485                       "harmless" "map" "nested" "optional"
4486                       "optional-tagged" "package" "primitive"
4487                       "primitive-nullfree" "relaxed[ \t]+enum"
4488                       "set" "table" "tagged-optional"   "union"
4489                       "variadic" "vector" "version" "version-tag")))
4490     (setq messages-mode-keywords
4491             (list
4492              (list (concat "\\<\\(" keywords "\\)\\>:")
4493                    '(0 font-lock-keyword-face))
4494              '("\\([-a-zA-Z0-9]+:\\)" (0 font-lock-warning-face))
4495              '("\\(\\<[a-z][-_a-zA-Z0-9]*\\)"
4496                (0 font-lock-variable-name-face))
4497              '("\\<\\([0-9]+\\)\\>" (0 mdw-number-face))
4498              '("\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
4499                (0 mdw-punct-face)))))
4500   (setq font-lock-defaults
4501           '(messages-mode-keywords nil nil nil nil))
4502   (run-hooks 'messages-file-hook))
4503
4504 (defun messages-mode ()
4505   (interactive)
4506   (fundamental-mode)
4507   (setq major-mode 'messages-mode)
4508   (setq mode-name "Messages")
4509   (messages-mode-guts)
4510   (modify-syntax-entry ?# "<" messages-mode-syntax-table)
4511   (modify-syntax-entry ?\n ">" messages-mode-syntax-table)
4512   (setq comment-start "# ")
4513   (setq comment-end "")
4514   (run-hooks 'messages-mode-hook))
4515
4516 (defun cpp-messages-mode ()
4517   (interactive)
4518   (fundamental-mode)
4519   (setq major-mode 'cpp-messages-mode)
4520   (setq mode-name "CPP Messages")
4521   (messages-mode-guts)
4522   (modify-syntax-entry ?* ". 23" messages-mode-syntax-table)
4523   (modify-syntax-entry ?/ ". 14" messages-mode-syntax-table)
4524   (setq comment-start "/* ")
4525   (setq comment-end " */")
4526   (let ((preprocessor-keywords
4527          (mdw-regexps "assert" "define" "elif" "else" "endif" "error"
4528                       "ident" "if" "ifdef" "ifndef" "import" "include"
4529                       "line" "pragma" "unassert" "undef" "warning")))
4530     (setq messages-mode-keywords
4531             (append (list (list (concat "^[ \t]*\\#[ \t]*"
4532                                         "\\(include\\|import\\)"
4533                                         "[ \t]*\\(<[^>]+\\(>\\)?\\)")
4534                                 '(2 font-lock-string-face))
4535                           (list (concat "^\\([ \t]*#[ \t]*\\(\\("
4536                                         preprocessor-keywords
4537                                         "\\)\\>\\|[0-9]+\\|$\\)\\)")
4538                                 '(1 font-lock-keyword-face)))
4539                     messages-mode-keywords)))
4540   (run-hooks 'cpp-messages-mode-hook))
4541
4542 (progn
4543   (add-hook 'messages-mode-hook 'mdw-misc-mode-config t)
4544   (add-hook 'cpp-messages-mode-hook 'mdw-misc-mode-config t)
4545   ;; (add-hook 'messages-file-hook 'mdw-fontify-messages t)
4546   )
4547
4548 ;;;--------------------------------------------------------------------------
4549 ;;; Messages-file mode.
4550
4551 (defvar mallow-driver-substitution-face 'mallow-driver-substitution-face
4552   "Face to use for subsittution directives.")
4553 (make-face 'mallow-driver-substitution-face)
4554 (defvar mallow-driver-text-face 'mallow-driver-text-face
4555   "Face to use for body text.")
4556 (make-face 'mallow-driver-text-face)
4557
4558 (defun mallow-driver-mode ()
4559   (interactive)
4560   (fundamental-mode)
4561   (setq major-mode 'mallow-driver-mode)
4562   (setq mode-name "Mallow driver")
4563   (setq mallow-driver-mode-syntax-table (make-syntax-table))
4564   (set-syntax-table mallow-driver-mode-syntax-table)
4565   (make-local-variable 'comment-start)
4566   (make-local-variable 'comment-end)
4567   (make-local-variable 'indent-line-function)
4568   (setq indent-line-function 'indent-relative)
4569   (mdw-standard-fill-prefix "\\([ \t]*\\(;\\|/?\\*\\)+[ \t]*\\)")
4570   (make-local-variable 'font-lock-defaults)
4571   (make-local-variable 'mallow-driver-mode-keywords)
4572   (let ((keywords
4573          (mdw-regexps "each" "divert" "file" "if"
4574                       "perl" "set" "string" "type" "write")))
4575     (setq mallow-driver-mode-keywords
4576             (list
4577              (list (concat "^%\\s *\\(}\\|\\(" keywords "\\)\\>\\).*$")
4578                    '(0 font-lock-keyword-face))
4579              (list "^%\\s *\\(#.*\\)?$"
4580                    '(0 font-lock-comment-face))
4581              (list "^%"
4582                    '(0 font-lock-keyword-face))
4583              (list "^|?\\(.+\\)$" '(1 mallow-driver-text-face))
4584              (list "\\${[^}]*}"
4585                    '(0 mallow-driver-substitution-face t)))))
4586   (setq font-lock-defaults
4587         '(mallow-driver-mode-keywords nil nil nil nil))
4588   (modify-syntax-entry ?\" "_" mallow-driver-mode-syntax-table)
4589   (modify-syntax-entry ?\n ">" mallow-driver-mode-syntax-table)
4590   (setq comment-start "%# ")
4591   (setq comment-end "")
4592   (run-hooks 'mallow-driver-mode-hook))
4593
4594 (progn
4595   (add-hook 'mallow-driver-hook 'mdw-misc-mode-config t))
4596
4597 ;;;--------------------------------------------------------------------------
4598 ;;; NFast debugs.
4599
4600 (defun nfast-debug-mode ()
4601   (interactive)
4602   (fundamental-mode)
4603   (setq major-mode 'nfast-debug-mode)
4604   (setq mode-name "NFast debug")
4605   (setq messages-mode-syntax-table (make-syntax-table))
4606   (set-syntax-table messages-mode-syntax-table)
4607   (make-local-variable 'font-lock-defaults)
4608   (make-local-variable 'nfast-debug-mode-keywords)
4609   (setq truncate-lines t)
4610   (setq nfast-debug-mode-keywords
4611           (list
4612            '("^\\(NFast_\\(Connect\\|Disconnect\\|Submit\\|Wait\\)\\)"
4613              (0 font-lock-keyword-face))
4614            (list (concat "^[ \t]+\\(\\("
4615                          "[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]"
4616                          "[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]"
4617                          "[ \t]+\\)*"
4618                          "[0-9a-fA-F]+\\)[ \t]*$")
4619                  '(0 mdw-number-face))
4620            '("^[ \t]+\.status=[ \t]+\\<\\(OK\\)\\>"
4621              (1 font-lock-keyword-face))
4622            '("^[ \t]+\.status=[ \t]+\\<\\([a-zA-Z][0-9a-zA-Z]*\\)\\>"
4623              (1 font-lock-warning-face))
4624            '("^[ \t]+\.status[ \t]+\\<\\(zero\\)\\>"
4625              (1 nil))
4626            (list (concat "^[ \t]+\\.cmd=[ \t]+"
4627                          "\\<\\([a-zA-Z][0-9a-zA-Z]*\\)\\>")
4628                  '(1 font-lock-keyword-face))
4629            '("-?\\<\\([0-9]+\\|0x[0-9a-fA-F]+\\)\\>" (0 mdw-number-face))
4630            '("^\\([ \t]+[a-z0-9.]+\\)" (0 font-lock-variable-name-face))
4631            '("\\<\\([a-z][a-z0-9.]+\\)\\>=" (1 font-lock-variable-name-face))
4632            '("\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)" (0 mdw-punct-face))))
4633   (setq font-lock-defaults
4634           '(nfast-debug-mode-keywords nil nil nil nil))
4635   (run-hooks 'nfast-debug-mode-hook))
4636
4637 ;;;--------------------------------------------------------------------------
4638 ;;; Lispy languages.
4639
4640 ;; Unpleasant bodge.
4641 (unless (boundp 'slime-repl-mode-map)
4642   (setq slime-repl-mode-map (make-sparse-keymap)))
4643
4644 (defun mdw-indent-newline-and-indent ()
4645   (interactive)
4646   (indent-for-tab-command)
4647   (newline-and-indent))
4648
4649 (eval-after-load "cl-indent"
4650   '(progn
4651      (mapc #'(lambda (pair)
4652                (put (car pair)
4653                     'common-lisp-indent-function
4654                     (cdr pair)))
4655       '((destructuring-bind . ((&whole 4 &rest 1) 4 &body))
4656         (multiple-value-bind . ((&whole 4 &rest 1) 4 &body))))))
4657
4658 (defun mdw-common-lisp-indent ()
4659   (make-local-variable 'lisp-indent-function)
4660   (setq lisp-indent-function 'common-lisp-indent-function))
4661
4662 (defmacro mdw-advise-hyperspec-lookup (func args)
4663   `(defadvice ,func (around mdw-browse-w3m ,args activate compile)
4664      (if (fboundp 'w3m)
4665          (let ((browse-url-browser-function #'mdw-w3m-browse-url))
4666            ad-do-it)
4667        ad-do-it)))
4668 (mdw-advise-hyperspec-lookup common-lisp-hyperspec (symbol))
4669 (mdw-advise-hyperspec-lookup common-lisp-hyperspec-format (char))
4670 (mdw-advise-hyperspec-lookup common-lisp-hyperspec-lookup-reader-macro (char))
4671
4672 (defun mdw-fontify-lispy ()
4673
4674   ;; Set fill prefix.
4675   (mdw-standard-fill-prefix "\\([ \t]*;+[ \t]*\\)")
4676
4677   ;; Not much fontification needed.
4678   (make-local-variable 'font-lock-keywords)
4679     (setq font-lock-keywords
4680           (list (list (concat "\\("
4681                               "\\_<[-+]?"
4682                               "\\(" "[0-9]+/[0-9]+"
4683                               "\\|" "\\(" "[0-9]+" "\\(\\.[0-9]*\\)?" "\\|"
4684                                           "\\.[0-9]+" "\\)"
4685                                     "\\([dDeEfFlLsS][-+]?[0-9]+\\)?"
4686                               "\\)"
4687                               "\\|"
4688                               "#"
4689                               "\\(" "x" "[-+]?"
4690                                     "[0-9A-Fa-f]+" "\\(/[0-9A-Fa-f]+\\)?"
4691                               "\\|" "o" "[-+]?" "[0-7]+" "\\(/[0-7]+\\)?"
4692                               "\\|" "b" "[-+]?" "[01]+" "\\(/[01]+\\)?"
4693                               "\\|" "[0-9]+" "r" "[-+]?"
4694                                     "[0-9a-zA-Z]+" "\\(/[0-9a-zA-Z]+\\)?"
4695                               "\\)"
4696                               "\\)\\_>")
4697                       '(0 mdw-number-face))
4698                 (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
4699                       '(0 mdw-punct-face)))))
4700
4701 ;; Special indentation.
4702
4703 (defcustom mdw-lisp-loop-default-indent 2
4704   "Default indent for simple `loop' body."
4705   :type 'integer
4706   :safe 'integerp)
4707 (defcustom mdw-lisp-setf-value-indent 2
4708   "Default extra indent for `setf' values."
4709   :type 'integer :safe 'integerp)
4710
4711 (setq lisp-simple-loop-indentation 0
4712       lisp-loop-keyword-indentation 0
4713       lisp-loop-forms-indentation 2
4714       lisp-lambda-list-keyword-parameter-alignment t)
4715
4716 (defun mdw-indent-funcall
4717     (path state &optional indent-point sexp-column normal-indent)
4718   "Indent `funcall' more usefully.
4719 Essentially, treat `funcall foo' as a function name, and align the arguments
4720 to `foo'."
4721   (and (or (not (consp path)) (null (cadr path)))
4722        (save-excursion
4723          (goto-char (cadr state))
4724          (forward-char 1)
4725          (let ((start-line (line-number-at-pos)))
4726            (and (condition-case nil (progn (forward-sexp 3) t)
4727                   (scan-error nil))
4728                 (progn
4729                   (forward-sexp -1)
4730                   (and (= start-line (line-number-at-pos))
4731                        (current-column))))))))
4732 (progn
4733   (put 'funcall 'common-lisp-indent-function 'mdw-indent-funcall)
4734   (put 'funcall 'lisp-indent-function 'mdw-indent-funcall))
4735
4736 (defun mdw-indent-setf
4737     (path state &optional indent-point sexp-column normal-indent)
4738   "Indent `setf' more usefully.
4739 If the values aren't on the same lines as their variables then indent them
4740 by `mdw-lisp-setf-value-indent' spaces."
4741   (and (or (not (consp path)) (null (cadr path)))
4742        (let ((basic-indent (save-excursion
4743                              (goto-char (cadr state))
4744                              (forward-char 1)
4745                              (and (condition-case nil
4746                                       (progn (forward-sexp 2) t)
4747                                     (scan-error nil))
4748                                   (progn
4749                                     (forward-sexp -1)
4750                                     (current-column)))))
4751              (offset (if (consp path) (car path)
4752                        (catch 'done
4753                          (save-excursion
4754                            (let ((start path)
4755                                  (count 0))
4756                              (goto-char (cadr state))
4757                              (forward-char 1)
4758                              (while (< (point) start)
4759                                (condition-case nil (forward-sexp 1)
4760                                  (scan-error (throw 'done nil)))
4761                                (incf count))
4762                              (1- count)))))))
4763          (and basic-indent offset
4764               (list (+ basic-indent
4765                        (if (oddp offset) 0
4766                          mdw-lisp-setf-value-indent))
4767                     basic-indent)))))
4768 (progn
4769   (put 'setf 'common-lisp-indent-functopion 'mdw-indent-setf)
4770   (put 'psetf 'common-lisp-indent-function 'mdw-indent-setf)
4771   (put 'setq 'common-lisp-indent-function 'mdw-indent-setf)
4772   (put 'setf 'lisp-indent-function 'mdw-indent-setf)
4773   (put 'setq 'lisp-indent-function 'mdw-indent-setf)
4774   (put 'setq-local 'lisp-indent-function 'mdw-indent-setf)
4775   (put 'setq-default 'lisp-indent-function 'mdw-indent-setf))
4776
4777 (defadvice common-lisp-loop-part-indentation
4778     (around mdw-fix-loop-indentation (indent-point state) activate compile)
4779   "Improve `loop' indentation.
4780 If the first subform is on the same line as the `loop' keyword, then
4781 align the other subforms beneath it.  Otherwise, indent them
4782 `mdw-lisp-loop-default-indent' columns in from the opening parenthesis."
4783
4784   (let* ((loop-indentation (save-excursion
4785                              (goto-char (elt state 1))
4786                              (current-column))))
4787
4788     ;; Don't really care about this.
4789     (when (and (boundp 'lisp-indent-backquote-substitution-mode)
4790                (eq lisp-indent-backquote-substitution-mode 'corrected))
4791       (save-excursion
4792         (goto-char (elt state 1))
4793         (cl-incf loop-indentation
4794                  (cond ((eq (char-before) ?,) -1)
4795                        ((and (eq (char-before) ?@)
4796                              (progn (backward-char)
4797                                     (eq (char-before) ?,)))
4798                         -2)
4799                        (t 0)))))
4800
4801     ;; If the first loop item is on the same line as the `loop' itself then
4802     ;; use that as the baseline.  Otherwise advance by the default indent.
4803     (goto-char (cadr state))
4804     (forward-char 1)
4805     (let ((baseline-indent
4806            (if (= (line-number-at-pos)
4807                   (if (condition-case nil (progn (forward-sexp 2) t)
4808                         (scan-error nil))
4809                       (progn (forward-sexp -1) (line-number-at-pos))
4810                     -1))
4811                (current-column)
4812              (+ loop-indentation mdw-lisp-loop-default-indent))))
4813
4814       (goto-char indent-point)
4815       (beginning-of-line)
4816
4817       (setq ad-return-value
4818               (list
4819                (cond ((condition-case ()
4820                           (save-excursion
4821                             (goto-char (elt state 1))
4822                             (forward-char 1)
4823                             (forward-sexp 2)
4824                             (backward-sexp 1)
4825                             (not (looking-at "\\(:\\|\\sw\\)")))
4826                         (error nil))
4827                       (+ baseline-indent lisp-simple-loop-indentation))
4828                      ((looking-at "^\\s-*\\(:?\\sw+\\|;\\)")
4829                       (+ baseline-indent lisp-loop-keyword-indentation))
4830                      (t
4831                       (+ baseline-indent lisp-loop-forms-indentation)))
4832
4833                ;; Tell the caller that the next line needs recomputation,
4834                ;; even though it doesn't start a sexp.
4835                loop-indentation)))))
4836
4837 ;; SLIME setup.
4838
4839 (defcustom mdw-friendly-name "[mdw]"
4840   "How I want to be addressed."
4841   :type 'string
4842   :safe 'stringp)
4843 (defadvice slime-user-first-name
4844     (around mdw-use-friendly-name compile activate)
4845   (if mdw-friendly-name (setq ad-return-value mdw-friendly-name)
4846     ad-do-it))
4847
4848 (eval-and-compile
4849   (trap
4850     (if (not mdw-fast-startup)
4851         (progn
4852           (require 'slime-autoloads)
4853           (slime-setup '(slime-autodoc slime-c-p-c))))))
4854
4855 (let ((stuff '((cmucl ("cmucl"))
4856                (sbcl ("sbcl") :coding-system utf-8-unix)
4857                (clisp ("clisp") :coding-system utf-8-unix))))
4858   (or (boundp 'slime-lisp-implementations)
4859       (setq slime-lisp-implementations nil))
4860   (while stuff
4861     (let* ((head (car stuff))
4862            (found (assq (car head) slime-lisp-implementations)))
4863       (setq stuff (cdr stuff))
4864       (if found
4865           (rplacd found (cdr head))
4866         (setq slime-lisp-implementations
4867                 (cons head slime-lisp-implementations))))))
4868 (setq slime-default-lisp 'sbcl)
4869
4870 ;; Hooks.
4871
4872 (progn
4873   (dolist (hook '(emacs-lisp-mode-hook
4874                   scheme-mode-hook
4875                   lisp-mode-hook
4876                   inferior-lisp-mode-hook
4877                   lisp-interaction-mode-hook
4878                   ielm-mode-hook
4879                   slime-repl-mode-hook))
4880     (add-hook hook 'mdw-misc-mode-config t)
4881     (add-hook hook 'mdw-fontify-lispy t))
4882   (add-hook 'lisp-mode-hook 'mdw-common-lisp-indent t)
4883   (add-hook 'inferior-lisp-mode-hook
4884             #'(lambda () (local-set-key "\C-m" 'comint-send-and-indent)) t))
4885
4886 ;;;--------------------------------------------------------------------------
4887 ;;; Other languages.
4888
4889 ;; Smalltalk.
4890
4891 (defun mdw-setup-smalltalk ()
4892   (and mdw-auto-indent
4893        (local-set-key "\C-m" 'smalltalk-newline-and-indent))
4894   (make-local-variable 'mdw-auto-indent)
4895   (setq mdw-auto-indent nil)
4896   (local-set-key "\C-i" 'smalltalk-reindent))
4897
4898 (defun mdw-fontify-smalltalk ()
4899   (make-local-variable 'font-lock-keywords)
4900   (setq font-lock-keywords
4901           (list
4902            (list "\\<[A-Z][a-zA-Z0-9]*\\>"
4903                  '(0 font-lock-keyword-face))
4904            (list (concat "\\<0\\([xX][0-9a-fA-F_]+\\|[0-7_]+\\)\\|"
4905                          "[0-9][0-9_]*\\(\\.[0-9_]*\\)?"
4906                          "\\([eE][-+]?[0-9_]+\\)?")
4907                  '(0 mdw-number-face))
4908            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
4909                  '(0 mdw-punct-face)))))
4910
4911 (progn
4912   (add-hook 'smalltalk-mode 'mdw-misc-mode-config t)
4913   (add-hook 'smalltalk-mode 'mdw-fontify-smalltalk t))
4914
4915 ;; m4.
4916
4917 (defun mdw-setup-m4 ()
4918
4919   ;; Inexplicably, Emacs doesn't match braces in m4 mode.  This is very
4920   ;; annoying: fix it.
4921   (modify-syntax-entry ?{ "(")
4922   (modify-syntax-entry ?} ")")
4923
4924   ;; Fill prefix.
4925   (mdw-standard-fill-prefix "\\([ \t]*\\(?:#+\\|\\<dnl\\>\\)[ \t]*\\)"))
4926
4927 (dolist (hook '(m4-mode-hook autoconf-mode-hook autotest-mode-hook))
4928   (add-hook hook #'mdw-misc-mode-config t)
4929   (add-hook hook #'mdw-setup-m4 t))
4930
4931 ;; Make.
4932
4933 (progn
4934   (add-hook 'makefile-mode-hook 'mdw-misc-mode-config t))
4935
4936 ;;;--------------------------------------------------------------------------
4937 ;;; Text mode.
4938
4939 (defun mdw-text-mode ()
4940   (setq fill-column 72)
4941   (flyspell-mode t)
4942   (mdw-standard-fill-prefix
4943    "\\([ \t]*\\([>#|:] ?\\)*[ \t]*\\)" 3)
4944   (auto-fill-mode 1))
4945
4946 (eval-after-load "flyspell"
4947   '(define-key flyspell-mode-map "\C-\M-i" nil))
4948
4949 (progn
4950   (add-hook 'text-mode-hook 'mdw-text-mode t))
4951
4952 ;;;--------------------------------------------------------------------------
4953 ;;; Outline and hide/show modes.
4954
4955 (defun mdw-outline-collapse-all ()
4956   "Completely collapse everything in the entire buffer."
4957   (interactive)
4958   (save-excursion
4959     (goto-char (point-min))
4960     (while (< (point) (point-max))
4961       (hide-subtree)
4962       (forward-line))))
4963
4964 (setq hs-hide-comments-when-hiding-all nil)
4965
4966 (defadvice hs-hide-all (after hide-first-comment activate)
4967   (save-excursion (hs-hide-initial-comment-block)))
4968
4969 ;;;--------------------------------------------------------------------------
4970 ;;; Shell mode.
4971
4972 (defun mdw-sh-mode-setup ()
4973   (local-set-key [?\C-a] 'comint-bol)
4974   (add-hook 'comint-output-filter-functions
4975             'comint-watch-for-password-prompt))
4976
4977 (defun mdw-term-mode-setup ()
4978   (setq term-prompt-regexp shell-prompt-pattern)
4979   (make-local-variable 'mouse-yank-at-point)
4980   (make-local-variable 'transient-mark-mode)
4981   (setq mouse-yank-at-point t)
4982   (auto-fill-mode -1)
4983   (setq tab-width 8))
4984
4985 (defun comint-send-and-indent ()
4986   (interactive)
4987   (comint-send-input)
4988   (and mdw-auto-indent
4989        (indent-for-tab-command)))
4990
4991 (defadvice comint-line-beginning-position
4992     (around mdw-calculate-it-properly () activate compile)
4993   "Calculate the actual line start for multi-line input."
4994   (if (or comint-use-prompt-regexp
4995           (eq (field-at-pos (point)) 'output))
4996       ad-do-it
4997     (setq ad-return-value
4998             (constrain-to-field (line-beginning-position) (point)))))
4999
5000 (defun term-send-meta-right () (interactive) (term-send-raw-string "\e\e[C"))
5001 (defun term-send-meta-left  () (interactive) (term-send-raw-string "\e\e[D"))
5002 (defun term-send-ctrl-uscore () (interactive) (term-send-raw-string "\C-_"))
5003 (defun term-send-meta-meta-something ()
5004   (interactive)
5005   (term-send-raw-string "\e\e")
5006   (term-send-raw))
5007 (eval-after-load 'term
5008   '(progn
5009      (define-key term-raw-map [?\e ?\e] nil)
5010      (define-key term-raw-map [?\e ?\e t] 'term-send-meta-meta-something)
5011      (define-key term-raw-map [?\C-/] 'term-send-ctrl-uscore)
5012      (define-key term-raw-map [M-right] 'term-send-meta-right)
5013      (define-key term-raw-map [?\e ?\M-O ?C] 'term-send-meta-right)
5014      (define-key term-raw-map [M-left] 'term-send-meta-left)
5015      (define-key term-raw-map [?\e ?\M-O ?D] 'term-send-meta-left)))
5016
5017 (defadvice term-exec (before program-args-list compile activate)
5018   "If the PROGRAM argument is a list, interpret it as (PROGRAM . SWITCHES).
5019 This allows you to pass a list of arguments through `ansi-term'."
5020   (let ((program (ad-get-arg 2)))
5021     (if (listp program)
5022         (progn
5023           (ad-set-arg 2 (car program))
5024           (ad-set-arg 4 (cdr program))))))
5025
5026 (defadvice term-exec-1 (around hack-environment compile activate)
5027   "Hack the environment inherited by inferiors in the terminal."
5028   (let ((process-environment (copy-tree process-environment)))
5029     (setenv "LD_PRELOAD" nil)
5030     ad-do-it))
5031
5032 (defadvice shell (around hack-environment compile activate)
5033   "Hack the environment inherited by inferiors in the shell."
5034   (let ((process-environment (copy-tree process-environment)))
5035     (setenv "LD_PRELOAD" nil)
5036     ad-do-it))
5037
5038 (defun ssh (host)
5039   "Open a terminal containing an ssh session to the HOST."
5040   (interactive "sHost: ")
5041   (ansi-term (list "ssh" host) (format "ssh@%s" host)))
5042
5043 (defcustom git-grep-command
5044   "env GIT_PAGER=cat git grep --no-color -nH -e "
5045   "The default command for \\[git-grep]."
5046   :type 'string)
5047
5048 (defvar git-grep-history nil)
5049
5050 (defun git-grep (command-args)
5051   "Run `git grep' with user-specified args and collect output in a buffer."
5052   (interactive
5053    (list (read-shell-command "Run git grep (like this): "
5054                              git-grep-command 'git-grep-history)))
5055   (let ((grep-use-null-device nil))
5056     (grep command-args)))
5057
5058 ;;;--------------------------------------------------------------------------
5059 ;;; Magit configuration.
5060
5061 (setq magit-diff-refine-hunk 't
5062       magit-view-git-manual-method 'man
5063       magit-log-margin '(nil age magit-log-margin-width t 18)
5064       magit-wip-after-save-local-mode-lighter ""
5065       magit-wip-after-apply-mode-lighter ""
5066       magit-wip-before-change-mode-lighter "")
5067 (eval-after-load "magit"
5068   '(progn (global-magit-file-mode 1)
5069           (magit-wip-after-save-mode 1)
5070           (magit-wip-after-apply-mode 1)
5071           (magit-wip-before-change-mode 1)
5072           (add-to-list 'magit-no-confirm 'safe-with-wip)
5073           (add-to-list 'magit-no-confirm 'trash)
5074           (push '(:eval (if (or magit-wip-after-save-local-mode
5075                                 magit-wip-after-apply-mode
5076                                 magit-wip-before-change-mode)
5077                             (format " wip:%s%s%s"
5078                                     (if magit-wip-after-apply-mode "A" "")
5079                                     (if magit-wip-before-change-mode "C" "")
5080                                     (if magit-wip-after-save-local-mode "S" ""))))
5081                 minor-mode-alist)
5082           (dolist (popup '(magit-diff-popup
5083                            magit-diff-refresh-popup
5084                            magit-diff-mode-refresh-popup
5085                            magit-revision-mode-refresh-popup))
5086             (magit-define-popup-switch popup ?R "Reverse diff" "-R"))
5087           (magit-define-popup-switch 'magit-rebase-popup ?r
5088                                      "Rebase merges" "--rebase-merges")))
5089
5090 (defadvice magit-wip-commit-buffer-file
5091     (around mdw-just-this-buffer activate compile)
5092   (let ((magit-save-repository-buffers nil)) ad-do-it))
5093
5094 (defadvice magit-discard
5095     (around mdw-delete-if-prefix-argument activate compile)
5096   (let ((magit-delete-by-moving-to-trash
5097          (and (null current-prefix-arg)
5098               magit-delete-by-moving-to-trash)))
5099     ad-do-it))
5100
5101 (setq magit-repolist-columns
5102         '(("Name" 16 magit-repolist-column-ident nil)
5103           ("Version" 18 magit-repolist-column-version nil)
5104           ("St" 2 magit-repolist-column-dirty nil)
5105           ("L<U" 3 mdw-repolist-column-unpulled-from-upstream nil)
5106           ("L>U" 3 mdw-repolist-column-unpushed-to-upstream nil)
5107           ("Path" 32 magit-repolist-column-path nil)))
5108
5109 (setq magit-repository-directories '(("~/etc/profile" . 0)
5110                                      ("~/src/" . 1)))
5111
5112 (defadvice magit-list-repos (around mdw-dirname () activate compile)
5113   "Make sure the returned names are directory names.
5114 Otherwise child processes get started in the wrong directory and
5115 there is sadness."
5116   (setq ad-return-value (mapcar #'file-name-as-directory ad-do-it)))
5117
5118 (defun mdw-repolist-column-unpulled-from-upstream (_id)
5119   "Insert number of upstream commits not in the current branch."
5120   (let ((upstream (magit-get-upstream-branch (magit-get-current-branch) t)))
5121     (and upstream
5122          (let ((n (cadr (magit-rev-diff-count "HEAD" upstream))))
5123            (propertize (number-to-string n) 'face
5124                        (if (> n 0) 'bold 'shadow))))))
5125
5126 (defun mdw-repolist-column-unpushed-to-upstream (_id)
5127   "Insert number of commits in the current branch but not its upstream."
5128   (let ((upstream (magit-get-upstream-branch (magit-get-current-branch) t)))
5129     (and upstream
5130          (let ((n (car (magit-rev-diff-count "HEAD" upstream))))
5131            (propertize (number-to-string n) 'face
5132                        (if (> n 0) 'bold 'shadow))))))
5133
5134 (defun mdw-try-smerge ()
5135   (save-excursion
5136     (goto-char (point-min))
5137     (when (re-search-forward "^<<<<<<< " nil t)
5138       (smerge-mode 1))))
5139 (add-hook 'find-file-hook 'mdw-try-smerge t)
5140
5141 ;;;--------------------------------------------------------------------------
5142 ;;; GUD, and especially GDB.
5143
5144 ;; Inhibit window dedication.  I mean, seriously, wtf?
5145 (defadvice gdb-display-buffer (after mdw-undedicated (buf) compile activate)
5146   "Don't make windows dedicated.  Seriously."
5147   (set-window-dedicated-p ad-return-value nil))
5148 (defadvice gdb-set-window-buffer
5149     (after mdw-undedicated (name &optional ignore-dedicated window)
5150      compile activate)
5151   "Don't make windows dedicated.  Seriously."
5152   (set-window-dedicated-p (or window (selected-window)) nil))
5153
5154 ;;;--------------------------------------------------------------------------
5155 ;;; SQL stuff.
5156
5157 (setq sql-postgres-options '("-n" "-P" "pager=off")
5158       sql-postgres-login-params
5159         '((user :default "mdw")
5160           (database :default "mdw")
5161           (server :default "db.distorted.org.uk")))
5162
5163 ;;;--------------------------------------------------------------------------
5164 ;;; Man pages.
5165
5166 ;; Turn off `noip' when running `man': it interferes with `man-db''s own
5167 ;; seccomp(2)-based sandboxing, which is (in this case, at least) strictly
5168 ;; better.
5169 (defadvice Man-getpage-in-background
5170     (around mdw-inhibit-noip (topic) compile activate)
5171   "Inhibit the `noip' preload hack when invoking `man'."
5172   (let* ((old-preload (getenv "LD_PRELOAD"))
5173          (preloads (and old-preload
5174                         (save-match-data (split-string old-preload ":"))))
5175          (any nil)
5176          (filtered nil))
5177     (save-match-data
5178       (while preloads
5179         (let ((item (pop preloads)))
5180           (if (string-match  "\\(/\\|^\\)noip\.so\\(:\\|$\\)" item)
5181               (setq any t)
5182             (push item filtered)))))
5183     (if any
5184         (unwind-protect
5185             (progn
5186               (setenv "LD_PRELOAD"
5187                       (and filtered
5188                            (with-output-to-string
5189                              (setq filtered (nreverse filtered))
5190                              (let ((first t))
5191                                (while filtered
5192                                  (if first (setq first nil)
5193                                    (write-char ?:))
5194                                  (write-string (pop filtered)))))))
5195               ad-do-it)
5196           (setenv "LD_PRELOAD" old-preload))
5197       ad-do-it)))
5198
5199 ;;;--------------------------------------------------------------------------
5200 ;;; MPC configuration.
5201
5202 (eval-when-compile (trap (require 'mpc)))
5203
5204 (setq mpc-browser-tags '(Artist|Composer|Performer Album|Playlist))
5205
5206 (defun mdw-mpc-now-playing ()
5207   (interactive)
5208   (require 'mpc)
5209   (save-excursion
5210     (set-buffer (mpc-proc-cmd (mpc-proc-cmd-list '("status" "currentsong"))))
5211     (mpc--status-callback))
5212   (let ((state (cdr (assq 'state mpc-status))))
5213     (cond ((member state '("stop"))
5214            (message "mpd stopped."))
5215           ((member state '("play" "pause"))
5216            (let* ((artist (cdr (assq 'Artist mpc-status)))
5217                   (album (cdr (assq 'Album mpc-status)))
5218                   (title (cdr (assq 'Title mpc-status)))
5219                   (file (cdr (assq 'file mpc-status)))
5220                   (duration-string (cdr (assq 'Time mpc-status)))
5221                   (time-string (cdr (assq 'time mpc-status)))
5222                   (time (and time-string
5223                              (string-to-number
5224                               (if (string-match ":" time-string)
5225                                   (substring time-string
5226                                              0 (match-beginning 0))
5227                                 (time-string)))))
5228                   (duration (and duration-string
5229                                  (string-to-number duration-string)))
5230                   (pos (and time duration
5231                             (format " [%d:%02d/%d:%02d]"
5232                                     (/ time 60) (mod time 60)
5233                                     (/ duration 60) (mod duration 60))))
5234                   (fmt (cond ((and artist title)
5235                               (format "`%s' by %s%s" title artist
5236                                       (if album (format ", from `%s'" album)
5237                                         "")))
5238                              (file
5239                               (format "`%s' (no tags)" file))
5240                              (t
5241                               "(no idea what's playing!)"))))
5242              (if (string= state "play")
5243                  (message "mpd playing %s%s" fmt (or pos ""))
5244                (message "mpd paused in %s%s" fmt (or pos "")))))
5245           (t
5246            (message "mpd in unknown state `%s'" state)))))
5247
5248 (defmacro mdw-define-mpc-wrapper (func bvl interactive &rest body)
5249   `(defun ,func ,bvl
5250      (interactive ,@interactive)
5251      (require 'mpc)
5252      ,@body
5253      (mdw-mpc-now-playing)))
5254
5255 (mdw-define-mpc-wrapper mdw-mpc-play-or-pause () nil
5256   (if (member (cdr (assq 'state (mpc-cmd-status))) '("play"))
5257       (mpc-pause)
5258     (mpc-play)))
5259
5260 (mdw-define-mpc-wrapper mdw-mpc-next () nil (mpc-next))
5261 (mdw-define-mpc-wrapper mdw-mpc-prev () nil (mpc-prev))
5262 (mdw-define-mpc-wrapper mdw-mpc-stop () nil (mpc-stop))
5263
5264 (defun mdw-mpc-louder (step)
5265   (interactive (list (if current-prefix-arg
5266                          (prefix-numeric-value current-prefix-arg)
5267                        +10)))
5268   (mpc-proc-cmd (format "volume %+d" step)))
5269
5270 (defun mdw-mpc-quieter (step)
5271   (interactive (list (if current-prefix-arg
5272                          (prefix-numeric-value current-prefix-arg)
5273                        +10)))
5274   (mpc-proc-cmd (format "volume %+d" (- step))))
5275
5276 (defun mdw-mpc-hack-lines (arg interactivep func)
5277   (if (and interactivep (use-region-p))
5278       (let ((from (region-beginning)) (to (region-end)))
5279         (goto-char from)
5280         (beginning-of-line)
5281         (funcall func)
5282         (forward-line)
5283         (while (< (point) to)
5284           (funcall func)
5285           (forward-line)))
5286     (let ((n (prefix-numeric-value arg)))
5287       (cond ((minusp n)
5288              (unless (bolp)
5289                (beginning-of-line)
5290                (funcall func)
5291                (incf n))
5292              (while (minusp n)
5293                (forward-line -1)
5294                (funcall func)
5295                (incf n)))
5296             (t
5297              (beginning-of-line)
5298              (while (plusp n)
5299                (funcall func)
5300                (forward-line)
5301                (decf n)))))))
5302
5303 (defun mdw-mpc-select-one ()
5304   (when (and (get-char-property (point) 'mpc-file)
5305              (not (get-char-property (point) 'mpc-select)))
5306     (mpc-select-toggle)))
5307
5308 (defun mdw-mpc-unselect-one ()
5309   (when (get-char-property (point) 'mpc-select)
5310     (mpc-select-toggle)))
5311
5312 (defun mdw-mpc-select (&optional arg interactivep)
5313   (interactive (list current-prefix-arg t))
5314   (mdw-mpc-hack-lines arg interactivep 'mdw-mpc-select-one))
5315
5316 (defun mdw-mpc-unselect (&optional arg interactivep)
5317   (interactive (list current-prefix-arg t))
5318   (mdw-mpc-hack-lines arg interactivep 'mdw-mpc-unselect-one))
5319
5320 (defun mdw-mpc-unselect-backwards (arg)
5321   (interactive "p")
5322   (mdw-mpc-hack-lines (- arg) t 'mdw-mpc-unselect-one))
5323
5324 (defun mdw-mpc-unselect-all ()
5325   (interactive)
5326   (setq mpc-select nil)
5327   (mpc-selection-refresh))
5328
5329 (defun mdw-mpc-next-line (arg)
5330   (interactive "p")
5331   (beginning-of-line)
5332   (forward-line arg))
5333
5334 (defun mdw-mpc-previous-line (arg)
5335   (interactive "p")
5336   (beginning-of-line)
5337   (forward-line (- arg)))
5338
5339 (defun mdw-mpc-playlist-add (&optional arg interactivep)
5340   (interactive (list current-prefix-arg t))
5341   (let ((mpc-select mpc-select))
5342     (when (or arg (and interactivep (use-region-p)))
5343       (setq mpc-select nil)
5344       (mdw-mpc-hack-lines arg interactivep 'mdw-mpc-select-one))
5345     (setq mpc-select (reverse mpc-select))
5346     (mpc-playlist-add)))
5347
5348 (defun mdw-mpc-playlist-delete (&optional arg interactivep)
5349   (interactive (list current-prefix-arg t))
5350   (setq mpc-select (nreverse mpc-select))
5351   (mpc-select-save
5352     (when (or arg (and interactivep (use-region-p)))
5353       (setq mpc-select nil)
5354       (mpc-selection-refresh)
5355       (mdw-mpc-hack-lines arg interactivep 'mdw-mpc-select-one))
5356       (mpc-playlist-delete)))
5357
5358 (defun mdw-mpc-hack-tagbrowsers ()
5359   (setq-local mode-line-format
5360                 '("%e"
5361                   mode-line-frame-identification
5362                   mode-line-buffer-identification)))
5363 (add-hook 'mpc-tagbrowser-mode-hook 'mdw-mpc-hack-tagbrowsers)
5364
5365 (defun mdw-mpc-hack-songs ()
5366   (setq-local header-line-format
5367               ;; '("MPC " mpc-volume " " mpc-current-song)
5368               (list (propertize " " 'display '(space :align-to 0))
5369                     ;; 'mpc-songs-format-description
5370                     '(:eval
5371                       (let ((deactivate-mark) (hscroll (window-hscroll)))
5372                         (with-temp-buffer
5373                           (mpc-format mpc-songs-format 'self hscroll)
5374                           ;; That would be simpler than the hscroll handling in
5375                           ;; mpc-format, but currently move-to-column does not
5376                           ;; recognize :space display properties.
5377                           ;; (move-to-column hscroll)
5378                           ;; (delete-region (point-min) (point))
5379                           (buffer-string)))))))
5380 (add-hook 'mpc-songs-mode-hook 'mdw-mpc-hack-songs)
5381
5382 (eval-after-load "mpc"
5383   '(progn
5384      (define-key mpc-mode-map "m" 'mdw-mpc-select)
5385      (define-key mpc-mode-map "u" 'mdw-mpc-unselect)
5386      (define-key mpc-mode-map "\177" 'mdw-mpc-unselect-backwards)
5387      (define-key mpc-mode-map "\e\177" 'mdw-mpc-unselect-all)
5388      (define-key mpc-mode-map "n" 'mdw-mpc-next-line)
5389      (define-key mpc-mode-map "p" 'mdw-mpc-previous-line)
5390      (define-key mpc-mode-map "/" 'mpc-songs-search)
5391      (setq mpc-songs-mode-map (make-sparse-keymap))
5392      (set-keymap-parent mpc-songs-mode-map mpc-mode-map)
5393      (define-key mpc-songs-mode-map "l" 'mpc-playlist)
5394      (define-key mpc-songs-mode-map "+" 'mdw-mpc-playlist-add)
5395      (define-key mpc-songs-mode-map "-" 'mdw-mpc-playlist-delete)
5396      (define-key mpc-songs-mode-map "\r" 'mpc-songs-jump-to)))
5397
5398 ;;;--------------------------------------------------------------------------
5399 ;;; Inferior Emacs Lisp.
5400
5401 (setq comint-prompt-read-only t)
5402
5403 (eval-after-load "comint"
5404   '(progn
5405      (define-key comint-mode-map "\C-w" 'comint-kill-region)
5406      (define-key comint-mode-map [C-S-backspace] 'comint-kill-whole-line)))
5407
5408 (eval-after-load "ielm"
5409   '(progn
5410      (define-key ielm-map "\C-w" 'comint-kill-region)
5411      (define-key ielm-map [C-S-backspace] 'comint-kill-whole-line)))
5412
5413 ;;;----- That's all, folks --------------------------------------------------
5414
5415 (provide 'dot-emacs)