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