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