chiark / gitweb /
Merge remote-tracking branch 'origin'
[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 (defvar mdw-fast-startup nil
28   "Whether .emacs should optimize for rapid startup.
29 This may be at the expense of cool features.")
30 (let ((probe nil) (next command-line-args))
31   (while next
32     (cond ((string= (car next) "--mdw-fast-startup")
33            (setq mdw-fast-startup t)
34            (if probe
35                (rplacd probe (cdr next))
36              (setq command-line-args (cdr next))))
37           (t
38            (setq probe next)))
39     (setq next (cdr next))))
40
41 ;;;--------------------------------------------------------------------------
42 ;;; Some general utilities.
43
44 (eval-when-compile
45   (unless (fboundp 'make-regexp)
46     (load "make-regexp"))
47   (require 'cl))
48
49 (defmacro mdw-regexps (&rest list)
50   "Turn a LIST of strings into a single regular expression at compile-time."
51   (declare (indent nil)
52            (debug 0))
53   `',(make-regexp list))
54
55 (defun mdw-wrong ()
56   "This is not the key sequence you're looking for."
57   (interactive)
58   (error "wrong button"))
59
60 (defun mdw-emacs-version-p (major &optional minor)
61   "Return non-nil if the running Emacs is at least version MAJOR.MINOR."
62   (or (> emacs-major-version major)
63       (and (= emacs-major-version major)
64            (>= emacs-minor-version (or minor 0)))))
65
66 ;; Some error trapping.
67 ;;
68 ;; If individual bits of this file go tits-up, we don't particularly want
69 ;; the whole lot to stop right there and then, because it's bloody annoying.
70
71 (defmacro trap (&rest forms)
72   "Execute FORMS without allowing errors to propagate outside."
73   (declare (indent 0)
74            (debug t))
75   `(condition-case err
76        ,(if (cdr forms) (cons 'progn forms) (car forms))
77      (error (message "Error (trapped): %s in %s"
78                      (error-message-string err)
79                      ',forms))))
80
81 ;; Configuration reading.
82
83 (defvar mdw-config nil)
84 (defun mdw-config (sym)
85   "Read the configuration variable named SYM."
86   (unless mdw-config
87     (setq mdw-config
88           (flet ((replace (what with)
89                    (goto-char (point-min))
90                    (while (re-search-forward what nil t)
91                      (replace-match with t))))
92             (with-temp-buffer
93               (insert-file-contents "~/.mdw.conf")
94               (replace  "^[ \t]*\\(#.*\\|\\)\n" "")
95               (replace (concat "^[ \t]*"
96                                "\\([-a-zA-Z0-9_.]*\\)"
97                                "[ \t]*=[ \t]*"
98                                "\\(.*[^ \t\n]\\|\\)"
99                                "[ \t]**\\(\n\\|$\\)")
100                        "(\\1 . \"\\2\")\n")
101               (car (read-from-string
102                     (concat "(" (buffer-string) ")")))))))
103   (cdr (assq sym mdw-config)))
104
105 ;; Local variables hacking.
106
107 (defun run-local-vars-mode-hook ()
108   "Run a hook for the major-mode after local variables have been processed."
109   (run-hooks (intern (concat (symbol-name major-mode)
110                              "-local-variables-hook"))))
111 (add-hook 'hack-local-variables-hook 'run-local-vars-mode-hook)
112
113 ;; Set up the load path convincingly.
114
115 (dolist (dir (append (and (boundp 'debian-emacs-flavor)
116                           (list (concat "/usr/share/"
117                                         (symbol-name debian-emacs-flavor)
118                                         "/site-lisp")))))
119   (dolist (sub (directory-files dir t))
120     (when (and (file-accessible-directory-p sub)
121                (not (member sub load-path)))
122       (setq load-path (nconc load-path (list sub))))))
123
124 ;; Is an Emacs library available?
125
126 (defun library-exists-p (name)
127   "Return non-nil if NAME is an available library.
128 Return non-nil if NAME.el (or NAME.elc) somewhere on the Emacs
129 load path.  The non-nil value is the filename we found for the
130 library."
131   (let ((path load-path) elt (foundp nil))
132     (while (and path (not foundp))
133       (setq elt (car path))
134       (setq path (cdr path))
135       (setq foundp (or (let ((file (concat elt "/" name ".elc")))
136                          (and (file-exists-p file) file))
137                        (let ((file (concat elt "/" name ".el")))
138                          (and (file-exists-p file) file)))))
139     foundp))
140
141 (defun maybe-autoload (symbol file &optional docstring interactivep type)
142   "Set an autoload if the file actually exists."
143   (and (library-exists-p file)
144        (autoload symbol file docstring interactivep type)))
145
146 (defun mdw-kick-menu-bar (&optional frame)
147   "Regenerate FRAME's menu bar so it doesn't have empty menus."
148   (interactive)
149   (unless frame (setq frame (selected-frame)))
150   (let ((old (frame-parameter frame 'menu-bar-lines)))
151     (set-frame-parameter frame 'menu-bar-lines 0)
152     (set-frame-parameter frame 'menu-bar-lines old)))
153
154 ;; Splitting windows.
155
156 (unless (fboundp 'scroll-bar-columns)
157   (defun scroll-bar-columns (side)
158     (cond ((eq side 'left) 0)
159           (window-system 3)
160           (t 1))))
161 (unless (fboundp 'fringe-columns)
162   (defun fringe-columns (side)
163     (cond ((not window-system) 0)
164           ((eq side 'left) 1)
165           (t 2))))
166
167 (defun mdw-horizontal-window-overhead ()
168   "Computes the horizontal window overhead.
169 This is the number of columns used by fringes, scroll bars and other such
170 cruft."
171   (if (not window-system)
172       1
173     (let ((tot 0))
174       (dolist (what '(scroll-bar fringe))
175         (dolist (side '(left right))
176           (incf tot (funcall (intern (concat (symbol-name what) "-columns"))
177                              side))))
178       tot)))
179
180 (defun mdw-split-window-horizontally (&optional width)
181   "Split a window horizontally.
182 Without a numeric argument, split the window approximately in
183 half.  With a numeric argument WIDTH, allocate WIDTH columns to
184 the left-hand window (if positive) or -WIDTH columns to the
185 right-hand window (if negative).  Space for scroll bars and
186 fringes is not taken out of the allowance for WIDTH, unlike
187 \\[split-window-horizontally]."
188   (interactive "P")
189   (split-window-horizontally
190    (cond ((null width) nil)
191          ((>= width 0) (+ width (mdw-horizontal-window-overhead)))
192          ((< width 0) width))))
193
194 (defun mdw-divvy-window (&optional width)
195   "Split a wide window into appropriate widths."
196   (interactive "P")
197   (setq width (cond (width (prefix-numeric-value width))
198                     ((and window-system (mdw-emacs-version-p 22))
199                      77)
200                     (t 78)))
201   (let* ((win (selected-window))
202          (sb-width (mdw-horizontal-window-overhead))
203          (c (/ (+ (window-width) sb-width)
204                (+ width sb-width))))
205     (while (> c 1)
206       (setq c (1- c))
207       (split-window-horizontally (+ width sb-width))
208       (other-window 1))
209     (select-window win)))
210
211 ;; Don't raise windows unless I say so.
212
213 (defvar mdw-inhibit-raise-frame nil
214   "*Whether `raise-frame' should do nothing when the frame is mapped.")
215
216 (defadvice raise-frame
217     (around mdw-inhibit (&optional frame) activate compile)
218   "Don't actually do anything if `mdw-inhibit-raise-frame' is true, and the
219 frame is actually mapped on the screen."
220   (if mdw-inhibit-raise-frame
221       (make-frame-visible frame)
222     ad-do-it))
223
224 (defmacro mdw-advise-to-inhibit-raise-frame (function)
225   "Advise the FUNCTION not to raise frames, even if it wants to."
226   `(defadvice ,function
227        (around mdw-inhibit-raise (&rest hunoz) activate compile)
228      "Don't raise the window unless you have to."
229      (let ((mdw-inhibit-raise-frame t))
230        ad-do-it)))
231
232 (mdw-advise-to-inhibit-raise-frame select-frame-set-input-focus)
233
234 ;; Bug fix for markdown-mode, which breaks point positioning during
235 ;; `query-replace'.
236 (defadvice markdown-check-change-for-wiki-link
237     (around mdw-save-match activate compile)
238   "Save match data around the `markdown-mode' `after-change-functions' hook."
239   (save-match-data ad-do-it))
240
241 ;; Bug fix for `bbdb-canonicalize-address': on Emacs 24, `run-hook-with-args'
242 ;; always returns nil, with the result that all email addresses are lost.
243 ;; Replace the function entirely.
244 (defadvice bbdb-canonicalize-address
245     (around mdw-bug-fix activate compile)
246   "Don't use `run-hook-with-args', because that doesn't work."
247   (let ((net (ad-get-arg 0)))
248
249     ;; Make sure this is a proper hook list.
250     (if (functionp bbdb-canonicalize-net-hook)
251         (setq bbdb-canonicalize-net-hook (list bbdb-canonicalize-net-hook)))
252
253     ;; Iterate over the hooks until things converge.
254     (let ((donep nil))
255       (while (not donep)
256         (let (next (changep nil)
257               hook (hooks bbdb-canonicalize-net-hook))
258           (while hooks
259             (setq hook (pop hooks))
260             (setq next (funcall hook net))
261             (if (not (equal next net))
262                 (setq changep t
263                       net next)))
264           (setq donep (not changep)))))
265     (setq ad-return-value net)))
266
267 ;; Transient mark mode hacks.
268
269 (defadvice exchange-point-and-mark
270     (around mdw-highlight (&optional arg) activate compile)
271   "Maybe don't actually exchange point and mark.
272 If `transient-mark-mode' is on and the mark is inactive, then
273 just activate it.  A non-trivial prefix argument will force the
274 usual behaviour.  A trivial prefix argument (i.e., just C-u) will
275 activate the mark and temporarily enable `transient-mark-mode' if
276 it's currently off."
277   (cond ((or mark-active
278              (and (not transient-mark-mode) (not arg))
279              (and arg (or (not (consp arg))
280                           (not (= (car arg) 4)))))
281          ad-do-it)
282         (t
283          (or transient-mark-mode (setq transient-mark-mode 'only))
284          (set-mark (mark t)))))
285
286 ;; Functions for sexp diary entries.
287
288 (defun mdw-not-org-mode (form)
289   "As FORM, but not in Org mode agenda."
290   (and (not mdw-diary-for-org-mode-p)
291        (eval form)))
292
293 (defun mdw-weekday (l)
294   "Return non-nil if `date' falls on one of the days of the week in L.
295 L is a list of day numbers (from 0 to 6 for Sunday through to
296 Saturday) or symbols `sunday', `monday', etc. (or a mixture).  If
297 the date stored in `date' falls on a listed day, then the
298 function returns non-nil."
299   (let ((d (calendar-day-of-week date)))
300     (or (memq d l)
301         (memq (nth d '(sunday monday tuesday wednesday
302                               thursday friday saturday)) l))))
303
304 (defun mdw-discordian-date (date)
305   "Return the Discordian calendar date corresponding to DATE.
306
307 The return value is (YOLD . st-tibs-day) or (YOLD SEASON DAYNUM DOW).
308
309 The original is by David Pearson.  I modified it to produce date components
310 as output rather than a string."
311   (let* ((days ["Sweetmorn" "Boomtime" "Pungenday"
312                 "Prickle-Prickle" "Setting Orange"])
313          (months ["Chaos" "Discord" "Confusion"
314                   "Bureaucracy" "Aftermath"])
315          (day-count [0 31 59 90 120 151 181 212 243 273 304 334])
316          (year (- (extract-calendar-year date) 1900))
317          (month (1- (extract-calendar-month date)))
318          (day (1- (extract-calendar-day date)))
319          (julian (+ (aref day-count month) day))
320          (dyear (+ year 3066)))
321     (if (and (= month 1) (= day 28))
322         (cons dyear 'st-tibs-day)
323       (list dyear
324             (aref months (floor (/ julian 73)))
325             (1+ (mod julian 73))
326             (aref days (mod julian 5))))))
327
328 (defun mdw-diary-discordian-date ()
329   "Convert the date in `date' to a string giving the Discordian date."
330   (let* ((ddate (mdw-discordian-date date))
331          (tail (format "in the YOLD %d" (car ddate))))
332     (if (eq (cdr ddate) 'st-tibs-day)
333         (format "St Tib's Day %s" tail)
334       (let ((season (cadr ddate))
335             (daynum (caddr ddate))
336             (dayname (cadddr ddate)))
337       (format "%s, the %d%s day of %s %s"
338               dayname
339               daynum
340               (let ((ldig (mod daynum 10)))
341                 (cond ((= ldig 1) "st")
342                       ((= ldig 2) "nd")
343                       ((= ldig 3) "rd")
344                       (t "th")))
345               season
346               tail)))))
347
348 (defun mdw-todo (&optional when)
349   "Return non-nil today, or on WHEN, whichever is later."
350   (let ((w (calendar-absolute-from-gregorian (calendar-current-date)))
351         (d (calendar-absolute-from-gregorian date)))
352     (if when
353         (setq w (max w (calendar-absolute-from-gregorian
354                         (cond
355                          ((not european-calendar-style)
356                           when)
357                          ((> (car when) 100)
358                           (list (nth 1 when)
359                                 (nth 2 when)
360                                 (nth 0 when)))
361                          (t
362                           (list (nth 1 when)
363                                 (nth 0 when)
364                                 (nth 2 when))))))))
365     (eq w d)))
366
367 (defvar mdw-diary-for-org-mode-p nil)
368
369 (defadvice org-agenda-list (around mdw-preserve-links activate)
370   (let ((mdw-diary-for-org-mode-p t))
371     ad-do-it))
372
373 (defadvice diary-add-to-list (before mdw-trim-leading-space compile activate)
374   "Trim leading space from the diary entry string."
375   (save-match-data
376     (let ((str (ad-get-arg 1))
377           (done nil) old)
378       (while (not done)
379         (setq old str)
380         (setq str (cond ((null str) nil)
381                         ((string-match "\\(^\\|\n\\)[ \t]+" str)
382                          (replace-match "\\1" nil nil str))
383                         ((and mdw-diary-for-org-mode-p
384                               (string-match (concat
385                                              "\\(^\\|\n\\)"
386                                              "\\(" diary-time-regexp
387                                              "\\(-" diary-time-regexp "\\)?"
388                                              "\\)"
389                                              "\\(\t[ \t]*\\| [ \t]+\\)")
390                                             str))
391                          (replace-match "\\1\\2 " nil nil str))
392                         ((and (not mdw-diary-for-org-mode-p)
393                               (string-match "\\[\\[[^][]*]\\[\\([^][]*\\)]]"
394                                             str))
395                          (replace-match "\\1" nil nil str))
396                         (t str)))
397         (if (equal str old) (setq done t)))
398       (ad-set-arg 1 str))))
399
400 (defadvice org-bbdb-anniversaries (after mdw-fixup-list compile activate)
401   "Return a string rather than a list."
402   (with-temp-buffer
403     (let ((anyp nil))
404       (dolist (e (let ((ee ad-return-value))
405                    (if (atom ee) (list ee) ee)))
406         (when e
407           (when anyp (insert ?\n))
408           (insert e)
409           (setq anyp t)))
410       (setq ad-return-value
411             (and anyp (buffer-string))))))
412
413 ;; Fighting with Org-mode's evil key maps.
414
415 (defvar mdw-evil-keymap-keys
416   '(([S-up] . [?\C-c up])
417     ([S-down] . [?\C-c down])
418     ([S-left] . [?\C-c left])
419     ([S-right] . [?\C-c right])
420     (([M-up] [?\e up]) . [C-up])
421     (([M-down] [?\e down]) . [C-down])
422     (([M-left] [?\e left]) . [C-left])
423     (([M-right] [?\e right]) . [C-right]))
424   "Defines evil keybindings to clobber in `mdw-clobber-evil-keymap'.
425 The value is an alist mapping evil keys (as a list, or singleton)
426 to good keys (in the same form).")
427
428 (defun mdw-clobber-evil-keymap (keymap)
429   "Replace evil key bindings in the KEYMAP.
430 Evil key bindings are defined in `mdw-evil-keymap-keys'."
431   (dolist (entry mdw-evil-keymap-keys)
432     (let ((binding nil)
433           (keys (if (listp (car entry))
434                     (car entry)
435                   (list (car entry))))
436           (replacements (if (listp (cdr entry))
437                             (cdr entry)
438                           (list (cdr entry)))))
439       (catch 'found
440         (dolist (key keys)
441           (setq binding (lookup-key keymap key))
442           (when binding
443             (throw 'found nil))))
444       (when binding
445         (dolist (key keys)
446           (define-key keymap key nil))
447         (dolist (key replacements)
448           (define-key keymap key binding))))))
449
450 (eval-after-load "org-latex"
451   '(progn
452      (push '("strayman"
453              "\\documentclass{strayman}
454 \\usepackage[utf8]{inputenc}
455 \\usepackage[palatino, helvetica, courier, maths=cmr]{mdwfonts}
456 \\usepackage[T1]{fontenc}
457 \\usepackage{graphicx, tikz, mdwtab, mdwmath, crypto, longtable}"
458              ("\\section{%s}" . "\\section*{%s}")
459              ("\\subsection{%s}" . "\\subsection*{%s}")
460              ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
461              ("\\paragraph{%s}" . "\\paragraph*{%s}")
462              ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))
463            org-export-latex-classes)))
464
465 (setq org-export-docbook-xslt-proc-command "xsltproc --output %o %s %i"
466       org-export-docbook-xsl-fo-proc-command "fop %i.safe %o"
467       org-export-docbook-xslt-stylesheet
468       "/usr/share/xml/docbook/stylesheet/docbook-xsl/fo/docbook.xsl")
469
470 ;; Some hacks to do with window placement.
471
472 (defun mdw-clobber-other-windows-showing-buffer (buffer-or-name)
473   "Arrange that no windows on other frames are showing BUFFER-OR-NAME."
474   (interactive "bBuffer: ")
475   (let ((home-frame (selected-frame))
476         (buffer (get-buffer buffer-or-name))
477         (safe-buffer (get-buffer "*scratch*")))
478     (mapc (lambda (frame)
479             (or (eq frame home-frame)
480                 (mapc (lambda (window)
481                         (and (eq (window-buffer window) buffer)
482                              (set-window-buffer window safe-buffer)))
483                       (window-list frame))))
484           (frame-list))))
485
486 (defvar mdw-inhibit-walk-windows nil
487   "If non-nil, then `walk-windows' does nothing.
488 This is used by advice on `switch-to-buffer-other-frame' to inhibit finding
489 buffers in random frames.")
490
491 (defadvice walk-windows (around mdw-inhibit activate)
492   "If `mdw-inhibit-walk-windows' is non-nil, then do nothing."
493   (and (not mdw-inhibit-walk-windows)
494        ad-do-it))
495
496 (defadvice switch-to-buffer-other-frame
497     (around mdw-always-new-frame activate)
498   "Always make a new frame.
499 Even if an existing window in some random frame looks tempting."
500   (let ((mdw-inhibit-walk-windows t)) ad-do-it))
501
502 (defadvice display-buffer (before mdw-inhibit-other-frames activate)
503   "Don't try to do anything fancy with other frames.
504 Pretend they don't exist.  They might be on other display devices."
505   (ad-set-arg 2 nil))
506
507 ;;;--------------------------------------------------------------------------
508 ;;; Mail and news hacking.
509
510 (define-derived-mode  mdwmail-mode mail-mode "[mdw] mail"
511   "Major mode for editing news and mail messages from external programs.
512 Not much right now.  Just support for doing MailCrypt stuff."
513   :syntax-table nil
514   :abbrev-table nil
515   (run-hooks 'mail-setup-hook))
516
517 (define-key mdwmail-mode-map [?\C-c ?\C-c] 'disabled-operation)
518
519 (add-hook 'mdwail-mode-hook
520           (lambda ()
521             (set-buffer-file-coding-system 'utf-8)
522             (make-local-variable 'paragraph-separate)
523             (make-local-variable 'paragraph-start)
524             (setq paragraph-start
525                   (concat "[ \t]*[-_][-_][-_]+$\\|^-- \\|-----\\|"
526                           paragraph-start))
527             (setq paragraph-separate
528                   (concat "[ \t]*[-_][-_][-_]+$\\|^-- \\|-----\\|"
529                           paragraph-separate))))
530
531 ;; How to encrypt in mdwmail.
532
533 (defun mdwmail-mc-encrypt (&optional recip scm start end from sign)
534   (or start
535       (setq start (save-excursion
536                     (goto-char (point-min))
537                     (or (search-forward "\n\n" nil t) (point-min)))))
538   (or end
539       (setq end (point-max)))
540   (mc-encrypt-generic recip scm start end from sign))
541
542 ;; How to sign in mdwmail.
543
544 (defun mdwmail-mc-sign (key scm start end uclr)
545   (or start
546       (setq start (save-excursion
547                     (goto-char (point-min))
548                     (or (search-forward "\n\n" nil t) (point-min)))))
549   (or end
550       (setq end (point-max)))
551   (mc-sign-generic key scm start end uclr))
552
553 ;; Some signature mangling.
554
555 (defun mdwmail-mangle-signature ()
556   (save-excursion
557     (goto-char (point-min))
558     (perform-replace "\n-- \n" "\n-- " nil nil nil)))
559 (add-hook 'mail-setup-hook 'mdwmail-mangle-signature)
560 (add-hook 'message-setup-hook 'mdwmail-mangle-signature)
561
562 ;; Insert my login name into message-ids, so I can score replies.
563
564 (defadvice message-unique-id (after mdw-user-name last activate compile)
565   "Ensure that the user's name appears at the end of the message-id string,
566 so that it can be used for convenient filtering."
567   (setq ad-return-value (concat ad-return-value "." (user-login-name))))
568
569 ;; Tell my movemail hack where movemail is.
570 ;;
571 ;; This is needed to shup up warnings about LD_PRELOAD.
572
573 (let ((path exec-path))
574   (while path
575     (let ((try (expand-file-name "movemail" (car path))))
576       (if (file-executable-p try)
577           (setenv "REAL_MOVEMAIL" try))
578       (setq path (cdr path)))))
579
580 ;; AUTHINFO GENERIC kludge.
581
582 (defvar nntp-authinfo-generic nil
583   "Set to the `NNTPAUTH' string to pass on to `authinfo-kludge'.
584
585 Use this to arrange for per-server settings.")
586
587 (defun nntp-open-authinfo-kludge (buffer)
588   "Open a connection to SERVER using `authinfo-kludge'."
589   (let ((proc (start-process "nntpd" buffer
590                              "env" (concat "NNTPAUTH="
591                                            (or nntp-authinfo-generic
592                                                (getenv "NNTPAUTH")
593                                                (error "NNTPAUTH unset")))
594                              "authinfo-kludge" nntp-address)))
595     (set-buffer buffer)
596     (nntp-wait-for-string "^\r*200")
597     (beginning-of-line)
598     (delete-region (point-min) (point))
599     proc))
600
601 (eval-after-load "erc"
602     '(load "~/.ercrc.el"))
603
604 ;;;--------------------------------------------------------------------------
605 ;;; Utility functions.
606
607 (or (fboundp 'line-number-at-pos)
608     (defun line-number-at-pos (&optional pos)
609       (let ((opoint (or pos (point))) start)
610         (save-excursion
611           (save-restriction
612             (goto-char (point-min))
613             (widen)
614             (forward-line 0)
615             (setq start (point))
616             (goto-char opoint)
617             (forward-line 0)
618             (1+ (count-lines 1 (point))))))))
619
620 (defun mdw-uniquify-alist (&rest alists)
621   "Return the concatenation of the ALISTS with duplicate elements removed.
622 The first association with a given key prevails; others are
623 ignored.  The input lists are not modified, although they'll
624 probably become garbage."
625   (and alists
626        (let ((start-list (cons nil nil)))
627          (mdw-do-uniquify start-list
628                           start-list
629                           (car alists)
630                           (cdr alists)))))
631
632 (defun mdw-do-uniquify (done end l rest)
633   "A helper function for mdw-uniquify-alist.
634 The DONE argument is a list whose first element is `nil'.  It
635 contains the uniquified alist built so far.  The leading `nil' is
636 stripped off at the end of the operation; it's only there so that
637 DONE always references a cons cell.  END refers to the final cons
638 cell in the DONE list; it is modified in place each time to avoid
639 the overheads of `append'ing all the time.  The L argument is the
640 alist we're currently processing; the remaining alists are given
641 in REST."
642
643   ;; There are several different cases to deal with here.
644   (cond
645
646    ;; Current list isn't empty.  Add the first item to the DONE list if
647    ;; there's not an item with the same KEY already there.
648    (l (or (assoc (car (car l)) done)
649           (progn
650             (setcdr end (cons (car l) nil))
651             (setq end (cdr end))))
652       (mdw-do-uniquify done end (cdr l) rest))
653
654    ;; The list we were working on is empty.  Shunt the next list into the
655    ;; current list position and go round again.
656    (rest (mdw-do-uniquify done end (car rest) (cdr rest)))
657
658    ;; Everything's done.  Remove the leading `nil' from the DONE list and
659    ;; return it.  Finished!
660    (t (cdr done))))
661
662 (defun date ()
663   "Insert the current date in a pleasing way."
664   (interactive)
665   (insert (save-excursion
666             (let ((buffer (get-buffer-create "*tmp*")))
667               (unwind-protect (progn (set-buffer buffer)
668                                      (erase-buffer)
669                                      (shell-command "date +%Y-%m-%d" t)
670                                      (goto-char (mark))
671                                      (delete-backward-char 1)
672                                      (buffer-string))
673                 (kill-buffer buffer))))))
674
675 (defun uuencode (file &optional name)
676   "UUencodes a file, maybe calling it NAME, into the current buffer."
677   (interactive "fInput file name: ")
678
679   ;; If NAME isn't specified, then guess from the filename.
680   (if (not name)
681       (setq name
682             (substring file
683                        (or (string-match "[^/]*$" file) 0))))
684   (print (format "uuencode `%s' `%s'" file name))
685
686   ;; Now actually do the thing.
687   (call-process "uuencode" file t nil name))
688
689 (defvar np-file "~/.np"
690   "*Where the `now-playing' file is.")
691
692 (defun np (&optional arg)
693   "Grabs a `now-playing' string."
694   (interactive)
695   (save-excursion
696     (or arg (progn
697               (goto-char (point-max))
698               (insert "\nNP: ")
699               (insert-file-contents np-file)))))
700
701 (defun mdw-version-< (ver-a ver-b)
702   "Answer whether VER-A is strictly earlier than VER-B.
703 VER-A and VER-B are version numbers, which are strings containing digit
704 sequences separated by `.'."
705   (let* ((la (mapcar (lambda (x) (car (read-from-string x)))
706                      (split-string ver-a "\\.")))
707          (lb (mapcar (lambda (x) (car (read-from-string x)))
708                      (split-string ver-b "\\."))))
709     (catch 'done
710       (while t
711         (cond ((null la) (throw 'done lb))
712               ((null lb) (throw 'done nil))
713               ((< (car la) (car lb)) (throw 'done t))
714               ((= (car la) (car lb)) (setq la (cdr la) lb (cdr lb))))))))
715
716 (defun mdw-check-autorevert ()
717   "Sets global-auto-revert-ignore-buffer appropriately for this buffer.
718 This takes into consideration whether it's been found using
719 tramp, which seems to get itself into a twist."
720   (cond ((not (boundp 'global-auto-revert-ignore-buffer))
721          nil)
722         ((and (buffer-file-name)
723               (fboundp 'tramp-tramp-file-p)
724               (tramp-tramp-file-p (buffer-file-name)))
725          (unless global-auto-revert-ignore-buffer
726            (setq global-auto-revert-ignore-buffer 'tramp)))
727         ((eq global-auto-revert-ignore-buffer 'tramp)
728          (setq global-auto-revert-ignore-buffer nil))))
729
730 (defadvice find-file (after mdw-autorevert activate)
731   (mdw-check-autorevert))
732 (defadvice write-file (after mdw-autorevert activate)
733   (mdw-check-autorevert))
734
735 ;;;--------------------------------------------------------------------------
736 ;;; Dired hacking.
737
738 (defadvice dired-maybe-insert-subdir
739     (around mdw-marked-insertion first activate)
740   "The DIRNAME may be a list of directory names to insert.
741 Interactively, if files are marked, then insert all of them.
742 With a numeric prefix argument, select that many entries near
743 point; with a non-numeric prefix argument, prompt for listing
744 options."
745   (interactive
746    (list (dired-get-marked-files nil
747                                  (and (integerp current-prefix-arg)
748                                       current-prefix-arg)
749                                  #'file-directory-p)
750          (and current-prefix-arg
751               (not (integerp current-prefix-arg))
752               (read-string "Switches for listing: "
753                            (or dired-subdir-switches
754                                dired-actual-switches)))))
755   (let ((dirs (ad-get-arg 0)))
756     (dolist (dir (if (listp dirs) dirs (list dirs)))
757       (ad-set-arg 0 dir)
758       ad-do-it)))
759
760 ;;;--------------------------------------------------------------------------
761 ;;; URL viewing.
762
763 (defun mdw-w3m-browse-url (url &optional new-session-p)
764   "Invoke w3m on the URL in its current window, or at least a different one.
765 If NEW-SESSION-P, start a new session."
766   (interactive "sURL: \nP")
767   (save-excursion
768     (let ((window (selected-window)))
769       (unwind-protect
770           (progn
771             (select-window (or (and (not new-session-p)
772                                     (get-buffer-window "*w3m*"))
773                                (progn
774                                  (if (one-window-p t) (split-window))
775                                  (get-lru-window))))
776             (w3m-browse-url url new-session-p))
777         (select-window window)))))
778
779 (defvar mdw-good-url-browsers
780   '(browse-url-mozilla
781     browse-url-generic
782     (w3m . mdw-w3m-browse-url)
783     browse-url-w3)
784   "List of good browsers for mdw-good-url-browsers.
785 Each item is a browser function name, or a cons (CHECK . FUNC).
786 A symbol FOO stands for (FOO . FOO).")
787
788 (defun mdw-good-url-browser ()
789   "Return a good URL browser.
790 Trundle the list of such things, finding the first item for which
791 CHECK is fboundp, and returning the correponding FUNC."
792   (let ((bs mdw-good-url-browsers) b check func answer)
793     (while (and bs (not answer))
794       (setq b (car bs)
795             bs (cdr bs))
796       (if (consp b)
797           (setq check (car b) func (cdr b))
798         (setq check b func b))
799       (if (fboundp check)
800           (setq answer func)))
801     answer))
802
803 (eval-after-load "w3m-search"
804   '(progn
805      (dolist
806          (item
807           '(("g" "Google" "http://www.google.co.uk/search?q=%s")
808             ("gd" "Google Directory"
809              "http://www.google.com/search?cat=gwd/Top&q=%s")
810             ("gg" "Google Groups" "http://groups.google.com/groups?q=%s")
811             ("ward" "Ward's wiki" "http://c2.com/cgi/wiki?%s")
812             ("gi" "Images" "http://images.google.com/images?q=%s")
813             ("rfc" "RFC"
814              "http://metalzone.distorted.org.uk/ftp/pub/mirrors/rfc/rfc%s.txt.gz")
815             ("wp" "Wikipedia"
816              "http://en.wikipedia.org/wiki/Special:Search?go=Go&search=%s")
817             ("imdb" "IMDb" "http://www.imdb.com/Find?%s")
818             ("nc-wiki" "nCipher wiki"
819              "http://wiki.ncipher.com/wiki/bin/view/Devel/?topic=%s")
820             ("map" "Google maps" "http://maps.google.co.uk/maps?q=%s&hl=en")
821             ("lp" "Launchpad bug by number"
822              "https://bugs.launchpad.net/bugs/%s")
823             ("lppkg" "Launchpad bugs by package"
824              "https://bugs.launchpad.net/%s")
825             ("msdn" "MSDN"
826              "http://social.msdn.microsoft.com/Search/en-GB/?query=%s&ac=8")
827             ("debbug" "Debian bug by number"
828              "http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=%s")
829             ("debbugpkg" "Debian bugs by package"
830              "http://bugs.debian.org/cgi-bin/pkgreport.cgi?pkg=%s")
831             ("ljlogin" "LJ login" "http://www.livejournal.com/login.bml")))
832        (add-to-list 'w3m-search-engine-alist
833                     (list (cadr item) (caddr item) nil))
834        (add-to-list 'w3m-uri-replace-alist
835                     (list (concat "\\`" (car item) ":")
836                           'w3m-search-uri-replace
837                           (cadr item))))))
838
839 ;;;--------------------------------------------------------------------------
840 ;;; Paragraph filling.
841
842 ;; Useful variables.
843
844 (defvar mdw-fill-prefix nil
845   "*Used by `mdw-line-prefix' and `mdw-fill-paragraph'.
846 If there's no fill prefix currently set (by the `fill-prefix'
847 variable) and there's a match from one of the regexps here, it
848 gets used to set the fill-prefix for the current operation.
849
850 The variable is a list of items of the form `REGEXP . PREFIX'; if
851 the REGEXP matches, the PREFIX is used to set the fill prefix.
852 It in turn is a list of things:
853
854   STRING -- insert a literal string
855   (match . N) -- insert the thing matched by bracketed subexpression N
856   (pad . N) -- a string of whitespace the same width as subexpression N
857   (expr . FORM) -- the result of evaluating FORM")
858
859 (make-variable-buffer-local 'mdw-fill-prefix)
860
861 (defvar mdw-hanging-indents
862   (concat "\\(\\("
863             "\\([*o+]\\|-[-#]?\\|[0-9]+\\.\\|\\[[0-9]+\\]\\|([a-zA-Z])\\)"
864             "[ \t]+"
865           "\\)?\\)")
866   "*Standard regexp matching parts of a hanging indent.
867 This is mainly useful in `auto-fill-mode'.")
868
869 ;; Setting things up.
870
871 (fset 'mdw-do-auto-fill (symbol-function 'do-auto-fill))
872
873 ;; Utility functions.
874
875 (defun mdw-maybe-tabify (s)
876   "Tabify or untabify the string S, according to `indent-tabs-mode'."
877   (let ((tabfun (if indent-tabs-mode #'tabify #'untabify)))
878     (with-temp-buffer
879       (save-match-data
880         (insert s "\n")
881         (let ((start (point-min)) (end (point-max)))
882           (funcall tabfun (point-min) (point-max))
883           (setq s (buffer-substring (point-min) (1- (point-max)))))))))
884
885 (defun mdw-examine-fill-prefixes (l)
886   "Given a list of dynamic fill prefixes, pick one which matches
887 context and return the static fill prefix to use.  Point must be
888 at the start of a line, and match data must be saved."
889   (cond ((not l) nil)
890                ((looking-at (car (car l)))
891                 (mdw-maybe-tabify (apply #'concat
892                                          (mapcar #'mdw-do-prefix-match
893                                                  (cdr (car l))))))
894                (t (mdw-examine-fill-prefixes (cdr l)))))
895
896 (defun mdw-maybe-car (p)
897   "If P is a pair, return (car P), otherwise just return P."
898   (if (consp p) (car p) p))
899
900 (defun mdw-padding (s)
901   "Return a string the same width as S but made entirely from whitespace."
902   (let* ((l (length s)) (i 0) (n (make-string l ? )))
903     (while (< i l)
904       (if (= 9 (aref s i))
905           (aset n i 9))
906       (setq i (1+ i)))
907     n))
908
909 (defun mdw-do-prefix-match (m)
910   "Expand a dynamic prefix match element.
911 See `mdw-fill-prefix' for details."
912   (cond ((not (consp m)) (format "%s" m))
913            ((eq (car m) 'match) (match-string (mdw-maybe-car (cdr m))))
914            ((eq (car m) 'pad) (mdw-padding (match-string
915                                             (mdw-maybe-car (cdr m)))))
916            ((eq (car m) 'eval) (eval (cdr m)))
917            (t "")))
918
919 (defun mdw-choose-dynamic-fill-prefix ()
920   "Work out the dynamic fill prefix based on the variable `mdw-fill-prefix'."
921   (cond ((and fill-prefix (not (string= fill-prefix ""))) fill-prefix)
922            ((not mdw-fill-prefix) fill-prefix)
923            (t (save-excursion
924                 (beginning-of-line)
925                 (save-match-data
926                   (mdw-examine-fill-prefixes mdw-fill-prefix))))))
927
928 (defun do-auto-fill ()
929   "Handle auto-filling, working out a dynamic fill prefix in the
930 case where there isn't a sensible static one."
931   (let ((fill-prefix (mdw-choose-dynamic-fill-prefix)))
932     (mdw-do-auto-fill)))
933
934 (defun mdw-fill-paragraph ()
935   "Fill paragraph, getting a dynamic fill prefix."
936   (interactive)
937   (let ((fill-prefix (mdw-choose-dynamic-fill-prefix)))
938     (fill-paragraph nil)))
939
940 (defun mdw-standard-fill-prefix (rx &optional mat)
941   "Set the dynamic fill prefix, handling standard hanging indents and stuff.
942 This is just a short-cut for setting the thing by hand, and by
943 design it doesn't cope with anything approximating a complicated
944 case."
945   (setq mdw-fill-prefix
946            `((,(concat rx mdw-hanging-indents)
947               (match . 1)
948               (pad . ,(or mat 2))))))
949
950 ;;;--------------------------------------------------------------------------
951 ;;; Other common declarations.
952
953 ;; Common mode settings.
954
955 (defvar mdw-auto-indent t
956   "Whether to indent automatically after a newline.")
957
958 (defun mdw-whitespace-mode (&optional arg)
959   "Turn on/off whitespace mode, but don't highlight trailing space."
960   (interactive "P")
961   (when (and (boundp 'whitespace-style)
962              (fboundp 'whitespace-mode))
963     (let ((whitespace-style (remove 'trailing whitespace-style)))
964       (whitespace-mode arg))
965     (setq show-trailing-whitespace whitespace-mode)))
966
967 (defvar mdw-do-misc-mode-hacking nil)
968
969 (defun mdw-misc-mode-config ()
970   (and mdw-auto-indent
971        (cond ((eq major-mode 'lisp-mode)
972               (local-set-key "\C-m" 'mdw-indent-newline-and-indent))
973              ((or (eq major-mode 'slime-repl-mode)
974                   (eq major-mode 'asm-mode))
975               nil)
976              (t
977               (local-set-key "\C-m" 'newline-and-indent))))
978   (set (make-local-variable 'mdw-do-misc-mode-hacking) t)
979   (local-set-key [C-return] 'newline)
980   (make-local-variable 'page-delimiter)
981   (setq page-delimiter "\f\\|^.*-\\{6\\}.*$")
982   (setq comment-column 40)
983   (auto-fill-mode 1)
984   (setq fill-column 77)
985   (and (fboundp 'gtags-mode)
986        (gtags-mode))
987   (if (fboundp 'hs-minor-mode)
988       (trap (hs-minor-mode t))
989     (outline-minor-mode t))
990   (reveal-mode t)
991   (trap (turn-on-font-lock)))
992
993 (defun mdw-post-local-vars-misc-mode-config ()
994   (when (and mdw-do-misc-mode-hacking
995              (not buffer-read-only))
996     (setq show-trailing-whitespace t)
997     (mdw-whitespace-mode 1)))
998 (add-hook 'hack-local-variables-hook 'mdw-post-local-vars-misc-mode-config)
999
1000 (defmacro mdw-advise-update-angry-fruit-salad (&rest funcs)
1001   `(progn ,@(mapcar (lambda (func)
1002                       `(defadvice ,func
1003                            (after mdw-angry-fruit-salad activate)
1004                          (when mdw-do-misc-mode-hacking
1005                            (setq show-trailing-whitespace
1006                                  (not buffer-read-only))
1007                            (mdw-whitespace-mode (if buffer-read-only 0 1)))))
1008                     funcs)))
1009 (mdw-advise-update-angry-fruit-salad toggle-read-only
1010                                      read-only-mode
1011                                      view-mode
1012                                      view-mode-enable
1013                                      view-mode-disable)
1014
1015 (eval-after-load 'gtags
1016   '(progn
1017      (dolist (key '([mouse-2] [mouse-3]))
1018        (define-key gtags-mode-map key nil))
1019      (define-key gtags-mode-map [C-S-mouse-2] 'gtags-find-tag-by-event)
1020      (define-key gtags-select-mode-map [C-S-mouse-2]
1021        'gtags-select-tag-by-event)
1022      (dolist (map (list gtags-mode-map gtags-select-mode-map))
1023        (define-key map [C-S-mouse-3] 'gtags-pop-stack))))
1024
1025 ;; Backup file handling.
1026
1027 (defvar mdw-backup-disable-regexps nil
1028   "*List of regular expressions: if a file name matches any of
1029 these then the file is not backed up.")
1030
1031 (defun mdw-backup-enable-predicate (name)
1032   "[mdw]'s default backup predicate.
1033 Allows a backup if the standard predicate would allow it, and it
1034 doesn't match any of the regular expressions in
1035 `mdw-backup-disable-regexps'."
1036   (and (normal-backup-enable-predicate name)
1037        (let ((answer t) (list mdw-backup-disable-regexps))
1038          (save-match-data
1039            (while list
1040              (if (string-match (car list) name)
1041                  (setq answer nil))
1042              (setq list (cdr list)))
1043            answer))))
1044 (setq backup-enable-predicate 'mdw-backup-enable-predicate)
1045
1046 ;; Frame cleanup.
1047
1048 (defun mdw-last-one-out-turn-off-the-lights (frame)
1049   "Disconnect from an X display if this was the last frame on that display."
1050   (let ((frame-display (frame-parameter frame 'display)))
1051     (when (and frame-display
1052                (eq window-system 'x)
1053                (not (some (lambda (fr)
1054                             (and (not (eq fr frame))
1055                                  (string= (frame-parameter fr 'display)
1056                                           frame-display)))
1057                           (frame-list))))
1058       (run-with-idle-timer 0 nil #'x-close-connection frame-display))))
1059 (add-hook 'delete-frame-functions 'mdw-last-one-out-turn-off-the-lights)
1060
1061 ;;;--------------------------------------------------------------------------
1062 ;;; Where is point?
1063
1064 (defvar mdw-point-overlay
1065   (let ((ov (make-overlay 0 0))
1066         (s "."))
1067     (overlay-put ov 'priority 2)
1068     (put-text-property 0 1 'display '(left-fringe vertical-bar) s)
1069     (overlay-put ov 'before-string s)
1070     (delete-overlay ov)
1071     ov)
1072   "An overlay used for showing where point is in the selected window.")
1073
1074 (defun mdw-remove-point-overlay ()
1075   "Remove the current-point overlay."
1076   (delete-overlay mdw-point-overlay))
1077
1078 (defun mdw-update-point-overlay ()
1079   "Mark the current point position with an overlay."
1080   (if (not mdw-point-overlay-mode)
1081       (mdw-remove-point-overlay)
1082     (overlay-put mdw-point-overlay 'window (selected-window))
1083     (if (bolp)
1084         (move-overlay mdw-point-overlay
1085                       (point) (1+ (point)) (current-buffer))
1086       (move-overlay mdw-point-overlay
1087                     (1- (point)) (point) (current-buffer)))))
1088
1089 (defvar mdw-point-overlay-buffers nil
1090   "List of buffers using `mdw-point-overlay-mode'.")
1091
1092 (define-minor-mode mdw-point-overlay-mode
1093   "Indicate current line with an overlay."
1094   :global nil
1095   (let ((buffer (current-buffer)))
1096     (setq mdw-point-overlay-buffers
1097           (mapcan (lambda (buf)
1098                     (if (and (buffer-live-p buf)
1099                              (not (eq buf buffer)))
1100                         (list buf)))
1101                   mdw-point-overlay-buffers))
1102     (if mdw-point-overlay-mode
1103         (setq mdw-point-overlay-buffers
1104               (cons buffer mdw-point-overlay-buffers))))
1105   (cond (mdw-point-overlay-buffers
1106          (add-hook 'pre-command-hook 'mdw-remove-point-overlay)
1107          (add-hook 'post-command-hook 'mdw-update-point-overlay))
1108         (t
1109          (mdw-remove-point-overlay)
1110          (remove-hook 'pre-command-hook 'mdw-remove-point-overlay)
1111          (remove-hook 'post-command-hook 'mdw-update-point-overlay))))
1112
1113 (define-globalized-minor-mode mdw-global-point-overlay-mode
1114   mdw-point-overlay-mode
1115   (lambda () (if (not (minibufferp)) (mdw-point-overlay-mode t))))
1116
1117 ;;;--------------------------------------------------------------------------
1118 ;;; Fullscreen-ness.
1119
1120 (defvar mdw-full-screen-parameters
1121   '((menu-bar-lines . 0)
1122     ;(vertical-scroll-bars . nil)
1123     )
1124   "Frame parameters to set when making a frame fullscreen.")
1125
1126 (defvar mdw-full-screen-save
1127   '(width height)
1128   "Extra frame parameters to save when setting fullscreen.")
1129
1130 (defun mdw-toggle-full-screen (&optional frame)
1131   "Show the FRAME fullscreen."
1132   (interactive)
1133   (when window-system
1134     (cond ((frame-parameter frame 'fullscreen)
1135            (set-frame-parameter frame 'fullscreen nil)
1136            (modify-frame-parameters
1137             nil
1138             (or (frame-parameter frame 'mdw-full-screen-saved)
1139                 (mapcar (lambda (assoc)
1140                           (assq (car assoc) default-frame-alist))
1141                         mdw-full-screen-parameters))))
1142           (t
1143            (let ((saved (mapcar (lambda (param)
1144                                   (cons param (frame-parameter frame param)))
1145                                 (append (mapcar #'car
1146                                                 mdw-full-screen-parameters)
1147                                         mdw-full-screen-save))))
1148              (set-frame-parameter frame 'mdw-full-screen-saved saved))
1149            (modify-frame-parameters frame mdw-full-screen-parameters)
1150            (set-frame-parameter frame 'fullscreen 'fullboth)))))
1151
1152 ;;;--------------------------------------------------------------------------
1153 ;;; General fontification.
1154
1155 (make-face 'mdw-virgin-face)
1156
1157 (defmacro mdw-define-face (name &rest body)
1158   "Define a face, and make sure it's actually set as the definition."
1159   (declare (indent 1)
1160            (debug 0))
1161   `(progn
1162      (copy-face 'mdw-virgin-face ',name)
1163      (defvar ,name ',name)
1164      (put ',name 'face-defface-spec ',body)
1165      (face-spec-set ',name ',body nil)))
1166
1167 (mdw-define-face default
1168   (((type w32)) :family "courier new" :height 85)
1169   (((type x)) :family "6x13" :foundry "trad" :height 130)
1170   (((type color)) :foreground "white" :background "black")
1171   (t nil))
1172 (mdw-define-face fixed-pitch
1173   (((type w32)) :family "courier new" :height 85)
1174   (((type x)) :family "6x13" :foundry "trad" :height 130)
1175   (t :foreground "white" :background "black"))
1176 (if (mdw-emacs-version-p 23)
1177     (mdw-define-face variable-pitch
1178       (((type x)) :family "sans" :height 100))
1179   (mdw-define-face variable-pitch
1180     (((type x)) :family "helvetica" :height 90)))
1181 (mdw-define-face region
1182   (((type tty) (class color)) :background "blue")
1183   (((type tty) (class mono)) :inverse-video t)
1184   (t :background "grey30"))
1185 (mdw-define-face match
1186   (((type tty) (class color)) :background "blue")
1187   (((type tty) (class mono)) :inverse-video t)
1188   (t :background "blue"))
1189 (mdw-define-face mc/cursor-face
1190   (((type tty) (class mono)) :inverse-video t)
1191   (t :background "red"))
1192 (mdw-define-face minibuffer-prompt
1193   (t :weight bold))
1194 (mdw-define-face mode-line
1195   (((class color)) :foreground "blue" :background "yellow"
1196                    :box (:line-width 1 :style released-button))
1197   (t :inverse-video t))
1198 (mdw-define-face mode-line-inactive
1199   (((class color)) :foreground "yellow" :background "blue"
1200                    :box (:line-width 1 :style released-button))
1201   (t :inverse-video t))
1202 (mdw-define-face nobreak-space
1203   (((type tty)))
1204   (t :inherit escape-glyph :underline t))
1205 (mdw-define-face scroll-bar
1206   (t :foreground "black" :background "lightgrey"))
1207 (mdw-define-face fringe
1208   (t :foreground "yellow"))
1209 (mdw-define-face show-paren-match
1210   (((class color)) :background "darkgreen")
1211   (t :underline t))
1212 (mdw-define-face show-paren-mismatch
1213   (((class color)) :background "red")
1214   (t :inverse-video t))
1215 (mdw-define-face highlight
1216   (((type x) (class color)) :background "DarkSeaGreen4")
1217   (((type tty) (class color)) :background "cyan")
1218   (t :inverse-video t))
1219
1220 (mdw-define-face holiday-face
1221   (t :background "red"))
1222 (mdw-define-face calendar-today-face
1223   (t :foreground "yellow" :weight bold))
1224
1225 (mdw-define-face comint-highlight-prompt
1226   (t :weight bold))
1227 (mdw-define-face comint-highlight-input
1228   (t nil))
1229
1230 (mdw-define-face dired-directory
1231   (t :foreground "cyan" :weight bold))
1232 (mdw-define-face dired-symlink
1233   (t :foreground "cyan"))
1234 (mdw-define-face dired-perm-write
1235   (t nil))
1236
1237 (mdw-define-face trailing-whitespace
1238   (((class color)) :background "red")
1239   (t :inverse-video t))
1240 (mdw-define-face whitespace-line
1241   (((class color)) :background "darkred")
1242   (t :inverse-video :t))
1243 (mdw-define-face mdw-punct-face
1244   (((type tty)) :foreground "yellow") (t :foreground "burlywood2"))
1245 (mdw-define-face mdw-number-face
1246   (t :foreground "yellow"))
1247 (mdw-define-face mdw-trivial-face)
1248 (mdw-define-face font-lock-function-name-face
1249   (t :slant italic))
1250 (mdw-define-face font-lock-keyword-face
1251   (t :weight bold))
1252 (mdw-define-face font-lock-constant-face
1253   (t :slant italic))
1254 (mdw-define-face font-lock-builtin-face
1255   (t :weight bold))
1256 (mdw-define-face font-lock-type-face
1257   (t :weight bold :slant italic))
1258 (mdw-define-face font-lock-reference-face
1259   (t :weight bold))
1260 (mdw-define-face font-lock-variable-name-face
1261   (t :slant italic))
1262 (mdw-define-face font-lock-comment-delimiter-face
1263   (((class mono)) :weight bold)
1264   (((type tty) (class color)) :foreground "green")
1265   (t :slant italic :foreground "SeaGreen1"))
1266 (mdw-define-face font-lock-comment-face
1267   (((class mono)) :weight bold)
1268   (((type tty) (class color)) :foreground "green")
1269   (t :slant italic :foreground "SeaGreen1"))
1270 (mdw-define-face font-lock-string-face
1271   (((class mono)) :weight bold)
1272   (((class color)) :foreground "SkyBlue1"))
1273
1274 (mdw-define-face message-separator
1275   (t :background "red" :foreground "white" :weight bold))
1276 (mdw-define-face message-cited-text
1277   (default :slant italic)
1278   (((type tty)) :foreground "cyan") (t :foreground "SkyBlue1"))
1279 (mdw-define-face message-header-cc
1280   (default :slant italic)
1281   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
1282 (mdw-define-face message-header-newsgroups
1283   (default :slant italic)
1284   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
1285 (mdw-define-face message-header-subject
1286   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
1287 (mdw-define-face message-header-to
1288   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
1289 (mdw-define-face message-header-xheader
1290   (default :slant italic)
1291   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
1292 (mdw-define-face message-header-other
1293   (default :slant italic)
1294   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
1295 (mdw-define-face message-header-name
1296   (default :weight bold)
1297   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
1298
1299 (mdw-define-face which-func
1300   (t nil))
1301
1302 (mdw-define-face gnus-header-name
1303   (default :weight bold)
1304   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
1305 (mdw-define-face gnus-header-subject
1306   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
1307 (mdw-define-face gnus-header-from
1308   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
1309 (mdw-define-face gnus-header-to
1310   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
1311 (mdw-define-face gnus-header-content
1312   (default :slant italic)
1313   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
1314
1315 (mdw-define-face gnus-cite-1
1316   (((type tty)) :foreground "cyan") (t :foreground "SkyBlue1"))
1317 (mdw-define-face gnus-cite-2
1318   (((type tty)) :foreground "blue") (t :foreground "RoyalBlue2"))
1319 (mdw-define-face gnus-cite-3
1320   (((type tty)) :foreground "magenta") (t :foreground "MediumOrchid"))
1321 (mdw-define-face gnus-cite-4
1322   (((type tty)) :foreground "red") (t :foreground "firebrick2"))
1323 (mdw-define-face gnus-cite-5
1324   (((type tty)) :foreground "yellow") (t :foreground "burlywood2"))
1325 (mdw-define-face gnus-cite-6
1326   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
1327 (mdw-define-face gnus-cite-7
1328   (((type tty)) :foreground "cyan") (t :foreground "SlateBlue1"))
1329 (mdw-define-face gnus-cite-8
1330   (((type tty)) :foreground "blue") (t :foreground "RoyalBlue2"))
1331 (mdw-define-face gnus-cite-9
1332   (((type tty)) :foreground "magenta") (t :foreground "purple2"))
1333 (mdw-define-face gnus-cite-10
1334   (((type tty)) :foreground "red") (t :foreground "DarkOrange2"))
1335 (mdw-define-face gnus-cite-11
1336   (t :foreground "grey"))
1337
1338 (mdw-define-face diff-header
1339   (t nil))
1340 (mdw-define-face diff-index
1341   (t :weight bold))
1342 (mdw-define-face diff-file-header
1343   (t :weight bold))
1344 (mdw-define-face diff-hunk-header
1345   (t :foreground "SkyBlue1"))
1346 (mdw-define-face diff-function
1347   (t :foreground "SkyBlue1" :weight bold))
1348 (mdw-define-face diff-header
1349   (t :background "grey10"))
1350 (mdw-define-face diff-added
1351   (t :foreground "green"))
1352 (mdw-define-face diff-removed
1353   (t :foreground "red"))
1354 (mdw-define-face diff-context
1355   (t nil))
1356 (mdw-define-face diff-refine-change
1357   (((class color) (type x)) :background "RoyalBlue4")
1358   (t :underline t))
1359 (mdw-define-face diff-refine-removed
1360   (((class color) (type x)) :background "#500")
1361   (t :underline t))
1362 (mdw-define-face diff-refine-added
1363   (((class color) (type x)) :background "#050")
1364   (t :underline t))
1365
1366 (mdw-define-face dylan-header-background
1367   (((class color) (type x)) :background "NavyBlue")
1368   (t :background "blue"))
1369
1370 (mdw-define-face magit-diff-add
1371   (t :foreground "green"))
1372 (mdw-define-face magit-diff-del
1373   (t :foreground "red"))
1374 (mdw-define-face magit-diff-file-header
1375   (t :weight bold))
1376 (mdw-define-face magit-diff-hunk-header
1377   (t :foreground "SkyBlue1"))
1378 (mdw-define-face magit-item-highlight
1379   (((type tty)) :background "blue")
1380   (t :background "grey11"))
1381 (mdw-define-face magit-log-head-label-remote
1382   (((type tty)) :background "cyan" :foreground "green")
1383   (t :background "grey11" :foreground "DarkSeaGreen2" :box t))
1384 (mdw-define-face magit-log-head-label-local
1385   (((type tty)) :background "cyan" :foreground "yellow")
1386   (t :background "grey11" :foreground "LightSkyBlue1" :box t))
1387 (mdw-define-face magit-log-head-label-tags
1388   (((type tty)) :background "red" :foreground "yellow")
1389   (t :background "LemonChiffon1" :foreground "goldenrod4" :box t))
1390 (mdw-define-face magit-log-graph
1391   (((type tty)) :foreground "magenta")
1392   (t :foreground "grey80"))
1393
1394 (mdw-define-face erc-input-face
1395   (t :foreground "red"))
1396
1397 (mdw-define-face woman-bold
1398   (t :weight bold))
1399 (mdw-define-face woman-italic
1400   (t :slant italic))
1401
1402 (eval-after-load "rst"
1403   '(progn
1404      (mdw-define-face rst-level-1-face
1405        (t :foreground "SkyBlue1" :weight bold))
1406      (mdw-define-face rst-level-2-face
1407        (t :foreground "SeaGreen1" :weight bold))
1408      (mdw-define-face rst-level-3-face
1409        (t :weight bold))
1410      (mdw-define-face rst-level-4-face
1411        (t :slant italic))
1412      (mdw-define-face rst-level-5-face
1413        (t :underline t))
1414      (mdw-define-face rst-level-6-face
1415        ())))
1416
1417 (mdw-define-face p4-depot-added-face
1418   (t :foreground "green"))
1419 (mdw-define-face p4-depot-branch-op-face
1420   (t :foreground "yellow"))
1421 (mdw-define-face p4-depot-deleted-face
1422   (t :foreground "red"))
1423 (mdw-define-face p4-depot-unmapped-face
1424   (t :foreground "SkyBlue1"))
1425 (mdw-define-face p4-diff-change-face
1426   (t :foreground "yellow"))
1427 (mdw-define-face p4-diff-del-face
1428   (t :foreground "red"))
1429 (mdw-define-face p4-diff-file-face
1430   (t :foreground "SkyBlue1"))
1431 (mdw-define-face p4-diff-head-face
1432   (t :background "grey10"))
1433 (mdw-define-face p4-diff-ins-face
1434   (t :foreground "green"))
1435
1436 (mdw-define-face w3m-anchor-face
1437   (t :foreground "SkyBlue1" :underline t))
1438 (mdw-define-face w3m-arrived-anchor-face
1439   (t :foreground "SkyBlue1" :underline t))
1440
1441 (mdw-define-face whizzy-slice-face
1442   (t :background "grey10"))
1443 (mdw-define-face whizzy-error-face
1444   (t :background "darkred"))
1445
1446 ;; Ellipses used to indicate hidden text (and similar).
1447 (mdw-define-face mdw-ellipsis-face
1448   (((type tty)) :foreground "blue") (t :foreground "grey60"))
1449 (let ((dollar (make-glyph-code ?$ 'mdw-ellipsis-face))
1450       (backslash (make-glyph-code ?\\ 'mdw-ellipsis-face))
1451       (dot (make-glyph-code ?. 'mdw-ellipsis-face))
1452       (bar (make-glyph-code ?| mdw-ellipsis-face)))
1453   (set-display-table-slot standard-display-table 0 dollar)
1454   (set-display-table-slot standard-display-table 1 backslash)
1455   (set-display-table-slot standard-display-table 4
1456                           (vector dot dot dot))
1457   (set-display-table-slot standard-display-table 5 bar))
1458
1459 ;;;--------------------------------------------------------------------------
1460 ;;; C programming configuration.
1461
1462 ;; Make C indentation nice.
1463
1464 (defun mdw-c-lineup-arglist (langelem)
1465   "Hack for DWIMmery in c-lineup-arglist."
1466   (if (save-excursion
1467         (c-block-in-arglist-dwim (c-langelem-2nd-pos c-syntactic-element)))
1468       0
1469     (c-lineup-arglist langelem)))
1470
1471 (defun mdw-c-indent-extern-mumble (langelem)
1472   "Indent `extern \"...\" {' lines."
1473   (save-excursion
1474     (back-to-indentation)
1475     (if (looking-at
1476          "\\s-*\\<extern\\>\\s-*\"\\([^\\\\\"]+\\|\\.\\)*\"\\s-*{")
1477         c-basic-offset
1478       nil)))
1479
1480 (defun mdw-c-indent-arglist-nested (langelem)
1481   "Indent continued argument lists.
1482 If we've nested more than one argument list, then only introduce a single
1483 indentation anyway."
1484   (let ((context c-syntactic-context)
1485         (pos (c-langelem-2nd-pos c-syntactic-element))
1486         (should-indent-p t))
1487     (while (and context
1488                 (eq (caar context) 'arglist-cont-nonempty))
1489       (when (and (= (caddr (pop context)) pos)
1490                  context
1491                  (memq (caar context) '(arglist-intro
1492                                         arglist-cont-nonempty)))
1493         (setq should-indent-p nil)))
1494     (if should-indent-p '+ 0)))
1495
1496 (defvar mdw-define-c-styles-hook nil
1497   "Hook run when `cc-mode' starts up to define styles.")
1498
1499 (defmacro mdw-define-c-style (name &rest assocs)
1500   "Define a C style, called NAME (a symbol), setting ASSOCs.
1501 A function, named `mdw-define-c-style/NAME', is defined to actually install
1502 the style using `c-add-style', and added to the hook
1503 `mdw-define-c-styles-hook'.  If CC Mode is already loaded, then the style is
1504 set."
1505   (declare (indent defun))
1506   (let* ((name-string (symbol-name name))
1507          (func (intern (concat "mdw-define-c-style/" name-string))))
1508     `(progn
1509        (defun ,func () (c-add-style ,name-string ',assocs))
1510        (and (featurep 'cc-mode) (,func))
1511        (add-hook 'mdw-define-c-styles-hook ',func))))
1512
1513 (eval-after-load "cc-mode"
1514   '(run-hooks 'mdw-define-c-styles-hook))
1515
1516 (mdw-define-c-style mdw-trustonic-c
1517   (c-basic-offset . 4)
1518   (comment-column . 0)
1519   (c-indent-comment-alist (anchored-comment . (column . 0))
1520                           (end-block . (space . 1))
1521                           (cpp-end-block . (space . 1))
1522                           (other . (space . 1)))
1523   (c-class-key . "class")
1524   (c-backslash-column . 0)
1525   (c-auto-align-backslashes . nil)
1526   (c-label-minimum-indentation . 0)
1527   (c-offsets-alist (substatement-open . (add 0 c-indent-one-line-block))
1528                    (defun-open . (add 0 c-indent-one-line-block))
1529                    (arglist-cont-nonempty . mdw-c-indent-arglist-nested)
1530                    (topmost-intro . mdw-c-indent-extern-mumble)
1531                    (cpp-define-intro . 0)
1532                    (knr-argdecl . 0)
1533                    (inextern-lang . [0])
1534                    (label . 0)
1535                    (case-label . +)
1536                    (access-label . -)
1537                    (inclass . +)
1538                    (inline-open . ++)
1539                    (statement-cont . +)
1540                    (statement-case-intro . +)))
1541
1542 (mdw-define-c-style mdw-c
1543   (c-basic-offset . 2)
1544   (comment-column . 40)
1545   (c-class-key . "class")
1546   (c-backslash-column . 72)
1547   (c-label-minimum-indentation . 0)
1548   (c-offsets-alist (substatement-open . (add 0 c-indent-one-line-block))
1549                    (defun-open . (add 0 c-indent-one-line-block))
1550                    (arglist-cont-nonempty . mdw-c-lineup-arglist)
1551                    (topmost-intro . mdw-c-indent-extern-mumble)
1552                    (cpp-define-intro . 0)
1553                    (knr-argdecl . 0)
1554                    (inextern-lang . [0])
1555                    (label . 0)
1556                    (case-label . +)
1557                    (access-label . -)
1558                    (inclass . +)
1559                    (inline-open . ++)
1560                    (statement-cont . +)
1561                    (statement-case-intro . +)))
1562
1563 (defun mdw-set-default-c-style (modes style)
1564   "Update the default CC Mode style for MODES to be STYLE.
1565
1566 MODES may be a list of major mode names or a singleton.  STYLE is a style
1567 name, as a symbol."
1568   (let ((modes (if (listp modes) modes (list modes)))
1569         (style (symbol-name style)))
1570     (setq c-default-style
1571           (append (mapcar (lambda (mode)
1572                             (cons mode style))
1573                           modes)
1574                   (remove-if (lambda (assoc)
1575                                (memq (car assoc) modes))
1576                              (if (listp c-default-style)
1577                                  c-default-style
1578                                (list (cons 'other c-default-style))))))))
1579 (setq c-default-style "mdw-c")
1580
1581 (mdw-set-default-c-style '(c-mode c++-mode) 'mdw-c)
1582
1583 (defvar mdw-c-comment-fill-prefix
1584   `((,(concat "\\([ \t]*/?\\)"
1585               "\\(\*\\|//]\\)"
1586               "\\([ \t]*\\)"
1587               "\\([A-Za-z]+:[ \t]*\\)?"
1588               mdw-hanging-indents)
1589      (pad . 1) (match . 2) (pad . 3) (pad . 4) (pad . 5)))
1590   "Fill prefix matching C comments (both kinds).")
1591
1592 (defun mdw-fontify-c-and-c++ ()
1593
1594   ;; Fiddle with some syntax codes.
1595   (modify-syntax-entry ?* ". 23")
1596   (modify-syntax-entry ?/ ". 124b")
1597   (modify-syntax-entry ?\n "> b")
1598
1599   ;; Other stuff.
1600   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
1601
1602   ;; Now define things to be fontified.
1603   (make-local-variable 'font-lock-keywords)
1604   (let ((c-keywords
1605          (mdw-regexps "alignas"          ;C11 macro, C++11
1606                       "alignof"          ;C++11
1607                       "and"              ;C++, C95 macro
1608                       "and_eq"           ;C++, C95 macro
1609                       "asm"              ;K&R, C++, GCC
1610                       "atomic"           ;C11 macro, C++11 template type
1611                       "auto"             ;K&R, C89
1612                       "bitand"           ;C++, C95 macro
1613                       "bitor"            ;C++, C95 macro
1614                       "bool"             ;C++, C99 macro
1615                       "break"            ;K&R, C89
1616                       "case"             ;K&R, C89
1617                       "catch"            ;C++
1618                       "char"             ;K&R, C89
1619                       "char16_t"         ;C++11, C11 library type
1620                       "char32_t"         ;C++11, C11 library type
1621                       "class"            ;C++
1622                       "complex"          ;C99 macro, C++ template type
1623                       "compl"            ;C++, C95 macro
1624                       "const"            ;C89
1625                       "constexpr"        ;C++11
1626                       "const_cast"       ;C++
1627                       "continue"         ;K&R, C89
1628                       "decltype"         ;C++11
1629                       "defined"          ;C89 preprocessor
1630                       "default"          ;K&R, C89
1631                       "delete"           ;C++
1632                       "do"               ;K&R, C89
1633                       "double"           ;K&R, C89
1634                       "dynamic_cast"     ;C++
1635                       "else"             ;K&R, C89
1636                       ;; "entry"         ;K&R -- never used
1637                       "enum"             ;C89
1638                       "explicit"         ;C++
1639                       "export"           ;C++
1640                       "extern"           ;K&R, C89
1641                       "float"            ;K&R, C89
1642                       "for"              ;K&R, C89
1643                       ;; "fortran"       ;K&R
1644                       "friend"           ;C++
1645                       "goto"             ;K&R, C89
1646                       "if"               ;K&R, C89
1647                       "imaginary"        ;C99 macro
1648                       "inline"           ;C++, C99, GCC
1649                       "int"              ;K&R, C89
1650                       "long"             ;K&R, C89
1651                       "mutable"          ;C++
1652                       "namespace"        ;C++
1653                       "new"              ;C++
1654                       "noexcept"         ;C++11
1655                       "noreturn"         ;C11 macro
1656                       "not"              ;C++, C95 macro
1657                       "not_eq"           ;C++, C95 macro
1658                       "nullptr"          ;C++11
1659                       "operator"         ;C++
1660                       "or"               ;C++, C95 macro
1661                       "or_eq"            ;C++, C95 macro
1662                       "private"          ;C++
1663                       "protected"        ;C++
1664                       "public"           ;C++
1665                       "register"         ;K&R, C89
1666                       "reinterpret_cast" ;C++
1667                       "restrict"         ;C99
1668                       "return"           ;K&R, C89
1669                       "short"            ;K&R, C89
1670                       "signed"           ;C89
1671                       "sizeof"           ;K&R, C89
1672                       "static"           ;K&R, C89
1673                       "static_assert"    ;C11 macro, C++11
1674                       "static_cast"      ;C++
1675                       "struct"           ;K&R, C89
1676                       "switch"           ;K&R, C89
1677                       "template"         ;C++
1678                       "throw"            ;C++
1679                       "try"              ;C++
1680                       "thread_local"     ;C11 macro, C++11
1681                       "typedef"          ;C89
1682                       "typeid"           ;C++
1683                       "typeof"           ;GCC
1684                       "typename"         ;C++
1685                       "union"            ;K&R, C89
1686                       "unsigned"         ;K&R, C89
1687                       "using"            ;C++
1688                       "virtual"          ;C++
1689                       "void"             ;C89
1690                       "volatile"         ;C89
1691                       "wchar_t"          ;C++, C89 library type
1692                       "while"            ;K&R, C89
1693                       "xor"              ;C++, C95 macro
1694                       "xor_eq"           ;C++, C95 macro
1695                       "_Alignas"         ;C11
1696                       "_Alignof"         ;C11
1697                       "_Atomic"          ;C11
1698                       "_Bool"            ;C99
1699                       "_Complex"         ;C99
1700                       "_Generic"         ;C11
1701                       "_Imaginary"       ;C99
1702                       "_Noreturn"        ;C11
1703                       "_Pragma"          ;C99 preprocessor
1704                       "_Static_assert"   ;C11
1705                       "_Thread_local"    ;C11
1706                       "__alignof__"      ;GCC
1707                       "__asm__"          ;GCC
1708                       "__attribute__"    ;GCC
1709                       "__complex__"      ;GCC
1710                       "__const__"        ;GCC
1711                       "__extension__"    ;GCC
1712                       "__imag__"         ;GCC
1713                       "__inline__"       ;GCC
1714                       "__label__"        ;GCC
1715                       "__real__"         ;GCC
1716                       "__signed__"       ;GCC
1717                       "__typeof__"       ;GCC
1718                       "__volatile__"     ;GCC
1719                       ))
1720         (c-constants
1721          (mdw-regexps "false"            ;C++, C99 macro
1722                       "this"             ;C++
1723                       "true"             ;C++, C99 macro
1724                       ))
1725         (preprocessor-keywords
1726          (mdw-regexps "assert" "define" "elif" "else" "endif" "error"
1727                       "ident" "if" "ifdef" "ifndef" "import" "include"
1728                       "line" "pragma" "unassert" "undef" "warning"))
1729         (objc-keywords
1730          (mdw-regexps "class" "defs" "encode" "end" "implementation"
1731                       "interface" "private" "protected" "protocol" "public"
1732                       "selector")))
1733
1734     (setq font-lock-keywords
1735           (list
1736
1737            ;; Fontify include files as strings.
1738            (list (concat "^[ \t]*\\#[ \t]*"
1739                          "\\(include\\|import\\)"
1740                          "[ \t]*\\(<[^>]+\\(>\\|\\)\\)")
1741                  '(2 font-lock-string-face))
1742
1743            ;; Preprocessor directives are `references'?.
1744            (list (concat "^\\([ \t]*#[ \t]*\\(\\("
1745                          preprocessor-keywords
1746                          "\\)\\>\\|[0-9]+\\|$\\)\\)")
1747                  '(1 font-lock-keyword-face))
1748
1749            ;; Handle the keywords defined above.
1750            (list (concat "@\\<\\(" objc-keywords "\\)\\>")
1751                  '(0 font-lock-keyword-face))
1752
1753            (list (concat "\\<\\(" c-keywords "\\)\\>")
1754                  '(0 font-lock-keyword-face))
1755
1756            (list (concat "\\<\\(" c-constants "\\)\\>")
1757                  '(0 font-lock-variable-name-face))
1758
1759            ;; Handle numbers too.
1760            ;;
1761            ;; This looks strange, I know.  It corresponds to the
1762            ;; preprocessor's idea of what a number looks like, rather than
1763            ;; anything sensible.
1764            (list (concat "\\(\\<[0-9]\\|\\.[0-9]\\)"
1765                          "\\([Ee][+-]\\|[0-9A-Za-z_.]\\)*")
1766                  '(0 mdw-number-face))
1767
1768            ;; And anything else is punctuation.
1769            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1770                  '(0 mdw-punct-face))))))
1771
1772 ;;;--------------------------------------------------------------------------
1773 ;;; AP calc mode.
1774
1775 (define-derived-mode apcalc-mode c-mode "AP Calc"
1776   "Major mode for editing Calc code.")
1777
1778 (defun mdw-fontify-apcalc ()
1779
1780   ;; Fiddle with some syntax codes.
1781   (modify-syntax-entry ?* ". 23")
1782   (modify-syntax-entry ?/ ". 14")
1783
1784   ;; Other stuff.
1785   (setq comment-start "/* ")
1786   (setq comment-end " */")
1787   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
1788
1789   ;; Now define things to be fontified.
1790   (make-local-variable 'font-lock-keywords)
1791   (let ((c-keywords
1792          (mdw-regexps "break" "case" "cd" "continue" "define" "default"
1793                       "do" "else" "exit" "for" "global" "goto" "help" "if"
1794                       "local" "mat" "obj" "print" "quit" "read" "return"
1795                       "show" "static" "switch" "while" "write")))
1796
1797     (setq font-lock-keywords
1798           (list
1799
1800            ;; Handle the keywords defined above.
1801            (list (concat "\\<\\(" c-keywords "\\)\\>")
1802                  '(0 font-lock-keyword-face))
1803
1804            ;; Handle numbers too.
1805            ;;
1806            ;; This looks strange, I know.  It corresponds to the
1807            ;; preprocessor's idea of what a number looks like, rather than
1808            ;; anything sensible.
1809            (list (concat "\\(\\<[0-9]\\|\\.[0-9]\\)"
1810                          "\\([Ee][+-]\\|[0-9A-Za-z_.]\\)*")
1811                  '(0 mdw-number-face))
1812
1813            ;; And anything else is punctuation.
1814            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1815                  '(0 mdw-punct-face))))))
1816
1817 ;;;--------------------------------------------------------------------------
1818 ;;; Java programming configuration.
1819
1820 ;; Make indentation nice.
1821
1822 (mdw-define-c-style mdw-java
1823   (c-basic-offset . 2)
1824   (c-backslash-column . 72)
1825   (c-offsets-alist (substatement-open . 0)
1826                    (label . +)
1827                    (case-label . +)
1828                    (access-label . 0)
1829                    (inclass . +)
1830                    (statement-case-intro . +)))
1831 (mdw-set-default-c-style 'java-mode 'mdw-java)
1832
1833 ;; Declare Java fontification style.
1834
1835 (defun mdw-fontify-java ()
1836
1837   ;; Other stuff.
1838   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
1839
1840   ;; Now define things to be fontified.
1841   (make-local-variable 'font-lock-keywords)
1842   (let ((java-keywords
1843          (mdw-regexps "abstract" "boolean" "break" "byte" "case" "catch"
1844                       "char" "class" "const" "continue" "default" "do"
1845                       "double" "else" "extends" "final" "finally" "float"
1846                       "for" "goto" "if" "implements" "import" "instanceof"
1847                       "int" "interface" "long" "native" "new" "package"
1848                       "private" "protected" "public" "return" "short"
1849                       "static" "switch" "synchronized" "throw" "throws"
1850                       "transient" "try" "void" "volatile" "while"))
1851
1852         (java-constants
1853          (mdw-regexps "false" "null" "super" "this" "true")))
1854
1855     (setq font-lock-keywords
1856           (list
1857
1858            ;; Handle the keywords defined above.
1859            (list (concat "\\<\\(" java-keywords "\\)\\>")
1860                  '(0 font-lock-keyword-face))
1861
1862            ;; Handle the magic constants defined above.
1863            (list (concat "\\<\\(" java-constants "\\)\\>")
1864                  '(0 font-lock-variable-name-face))
1865
1866            ;; Handle numbers too.
1867            ;;
1868            ;; The following isn't quite right, but it's close enough.
1869            (list (concat "\\<\\("
1870                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
1871                          "[0-9]+\\(\\.[0-9]*\\|\\)"
1872                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)"
1873                          "[lLfFdD]?")
1874                  '(0 mdw-number-face))
1875
1876            ;; And anything else is punctuation.
1877            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1878                  '(0 mdw-punct-face))))))
1879
1880 ;;;--------------------------------------------------------------------------
1881 ;;; Javascript programming configuration.
1882
1883 (defun mdw-javascript-style ()
1884   (setq js-indent-level 2)
1885   (setq js-expr-indent-offset 0))
1886
1887 (defun mdw-fontify-javascript ()
1888
1889   ;; Other stuff.
1890   (mdw-javascript-style)
1891   (setq js-auto-indent-flag t)
1892
1893   ;; Now define things to be fontified.
1894   (make-local-variable 'font-lock-keywords)
1895   (let ((javascript-keywords
1896          (mdw-regexps "abstract" "boolean" "break" "byte" "case" "catch"
1897                       "char" "class" "const" "continue" "debugger" "default"
1898                       "delete" "do" "double" "else" "enum" "export" "extends"
1899                       "final" "finally" "float" "for" "function" "goto" "if"
1900                       "implements" "import" "in" "instanceof" "int"
1901                       "interface" "let" "long" "native" "new" "package"
1902                       "private" "protected" "public" "return" "short"
1903                       "static" "super" "switch" "synchronized" "throw"
1904                       "throws" "transient" "try" "typeof" "var" "void"
1905                       "volatile" "while" "with" "yield"
1906
1907                       "boolean" "byte" "char" "double" "float" "int" "long"
1908                       "short" "void"))
1909         (javascript-constants
1910          (mdw-regexps "false" "null" "undefined" "Infinity" "NaN" "true"
1911                       "arguments" "this")))
1912
1913     (setq font-lock-keywords
1914           (list
1915
1916            ;; Handle the keywords defined above.
1917            (list (concat "\\_<\\(" javascript-keywords "\\)\\_>")
1918                  '(0 font-lock-keyword-face))
1919
1920            ;; Handle the predefined constants defined above.
1921            (list (concat "\\_<\\(" javascript-constants "\\)\\_>")
1922                  '(0 font-lock-variable-name-face))
1923
1924            ;; Handle numbers too.
1925            ;;
1926            ;; The following isn't quite right, but it's close enough.
1927            (list (concat "\\_<\\("
1928                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
1929                          "[0-9]+\\(\\.[0-9]*\\|\\)"
1930                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)"
1931                          "[lLfFdD]?")
1932                  '(0 mdw-number-face))
1933
1934            ;; And anything else is punctuation.
1935            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1936                  '(0 mdw-punct-face))))))
1937
1938 ;;;--------------------------------------------------------------------------
1939 ;;; Scala programming configuration.
1940
1941 (defun mdw-fontify-scala ()
1942
1943   ;; Comment filling.
1944   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
1945
1946   ;; Define things to be fontified.
1947   (make-local-variable 'font-lock-keywords)
1948   (let ((scala-keywords
1949          (mdw-regexps "abstract" "case" "catch" "class" "def" "do" "else"
1950                       "extends" "final" "finally" "for" "forSome" "if"
1951                       "implicit" "import" "lazy" "match" "new" "object"
1952                       "override" "package" "private" "protected" "return"
1953                       "sealed" "throw" "trait" "try" "type" "val"
1954                       "var" "while" "with" "yield"))
1955         (scala-constants
1956          (mdw-regexps "false" "null" "super" "this" "true"))
1957         (punctuation "[-!%^&*=+:@#~/?\\|`]"))
1958
1959     (setq font-lock-keywords
1960           (list
1961
1962            ;; Magical identifiers between backticks.
1963            (list (concat "`\\([^`]+\\)`")
1964                  '(1 font-lock-variable-name-face))
1965
1966            ;; Handle the keywords defined above.
1967            (list (concat "\\_<\\(" scala-keywords "\\)\\_>")
1968                  '(0 font-lock-keyword-face))
1969
1970            ;; Handle the constants defined above.
1971            (list (concat "\\_<\\(" scala-constants "\\)\\_>")
1972                  '(0 font-lock-variable-name-face))
1973
1974            ;; Magical identifiers between backticks.
1975            (list (concat "`\\([^`]+\\)`")
1976                  '(1 font-lock-variable-name-face))
1977
1978            ;; Handle numbers too.
1979            ;;
1980            ;; As usual, not quite right.
1981            (list (concat "\\_<\\("
1982                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
1983                          "[0-9]+\\(\\.[0-9]*\\|\\)"
1984                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)"
1985                          "[lLfFdD]?")
1986                  '(0 mdw-number-face))
1987
1988            ;; Identifiers with trailing operators.
1989            (list (concat "_\\(" punctuation "\\)+")
1990                  '(0 mdw-trivial-face))
1991
1992            ;; And everything else is punctuation.
1993            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1994                  '(0 mdw-punct-face)))
1995
1996           font-lock-syntactic-keywords
1997           (list
1998
1999            ;; Single quotes around characters.  But not when used to quote
2000            ;; symbol names.  Ugh.
2001            (list (concat "\\('\\)"
2002                          "\\(" "."
2003                          "\\|" "\\\\" "\\(" "\\\\\\\\" "\\)*"
2004                                "u+" "[0-9a-fA-F]\\{4\\}"
2005                          "\\|" "\\\\" "[0-7]\\{1,3\\}"
2006                          "\\|" "\\\\" "." "\\)"
2007                          "\\('\\)")
2008                  '(1 "\"")
2009                  '(4 "\""))))))
2010
2011 ;;;--------------------------------------------------------------------------
2012 ;;; C# programming configuration.
2013
2014 ;; Make indentation nice.
2015
2016 (mdw-define-c-style mdw-csharp
2017   (c-basic-offset . 2)
2018   (c-backslash-column . 72)
2019   (c-offsets-alist (substatement-open . 0)
2020                    (label . 0)
2021                    (case-label . +)
2022                    (access-label . 0)
2023                    (inclass . +)
2024                    (statement-case-intro . +)))
2025 (mdw-set-default-c-style 'csharp-mode 'mdw-csharp)
2026
2027 ;; Declare C# fontification style.
2028
2029 (defun mdw-fontify-csharp ()
2030
2031   ;; Other stuff.
2032   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
2033
2034   ;; Now define things to be fontified.
2035   (make-local-variable 'font-lock-keywords)
2036   (let ((csharp-keywords
2037          (mdw-regexps "abstract" "as" "bool" "break" "byte" "case" "catch"
2038                       "char" "checked" "class" "const" "continue" "decimal"
2039                       "default" "delegate" "do" "double" "else" "enum"
2040                       "event" "explicit" "extern" "finally" "fixed" "float"
2041                       "for" "foreach" "goto" "if" "implicit" "in" "int"
2042                       "interface" "internal" "is" "lock" "long" "namespace"
2043                       "new" "object" "operator" "out" "override" "params"
2044                       "private" "protected" "public" "readonly" "ref"
2045                       "return" "sbyte" "sealed" "short" "sizeof"
2046                       "stackalloc" "static" "string" "struct" "switch"
2047                       "throw" "try" "typeof" "uint" "ulong" "unchecked"
2048                       "unsafe" "ushort" "using" "virtual" "void" "volatile"
2049                       "while" "yield"))
2050
2051         (csharp-constants
2052          (mdw-regexps "base" "false" "null" "this" "true")))
2053
2054     (setq font-lock-keywords
2055           (list
2056
2057            ;; Handle the keywords defined above.
2058            (list (concat "\\<\\(" csharp-keywords "\\)\\>")
2059                  '(0 font-lock-keyword-face))
2060
2061            ;; Handle the magic constants defined above.
2062            (list (concat "\\<\\(" csharp-constants "\\)\\>")
2063                  '(0 font-lock-variable-name-face))
2064
2065            ;; Handle numbers too.
2066            ;;
2067            ;; The following isn't quite right, but it's close enough.
2068            (list (concat "\\<\\("
2069                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
2070                          "[0-9]+\\(\\.[0-9]*\\|\\)"
2071                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)"
2072                          "[lLfFdD]?")
2073                  '(0 mdw-number-face))
2074
2075            ;; And anything else is punctuation.
2076            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2077                  '(0 mdw-punct-face))))))
2078
2079 (define-derived-mode csharp-mode java-mode "C#"
2080   "Major mode for editing C# code.")
2081
2082 ;;;--------------------------------------------------------------------------
2083 ;;; F# programming configuration.
2084
2085 (setq fsharp-indent-offset 2)
2086
2087 (defun mdw-fontify-fsharp ()
2088
2089   (let ((punct "=<>+-*/|&%!@?"))
2090     (do ((i 0 (1+ i)))
2091         ((>= i (length punct)))
2092       (modify-syntax-entry (aref punct i) ".")))
2093
2094   (modify-syntax-entry ?_ "_")
2095   (modify-syntax-entry ?( "(")
2096   (modify-syntax-entry ?) ")")
2097
2098   (setq indent-tabs-mode nil)
2099
2100   (let ((fsharp-keywords
2101          (mdw-regexps "abstract" "and" "as" "assert" "atomic"
2102                       "begin" "break"
2103                       "checked" "class" "component" "const" "constraint"
2104                       "constructor" "continue"
2105                       "default" "delegate" "do" "done" "downcast" "downto"
2106                       "eager" "elif" "else" "end" "exception" "extern"
2107                       "finally" "fixed" "for" "fori" "fun" "function"
2108                       "functor"
2109                       "global"
2110                       "if" "in" "include" "inherit" "inline" "interface"
2111                       "internal"
2112                       "lazy" "let"
2113                       "match" "measure" "member" "method" "mixin" "module"
2114                       "mutable"
2115                       "namespace" "new"
2116                       "object" "of" "open" "or" "override"
2117                       "parallel" "params" "private" "process" "protected"
2118                       "public" "pure"
2119                       "rec" "recursive" "return"
2120                       "sealed" "sig" "static" "struct"
2121                       "tailcall" "then" "to" "trait" "try" "type"
2122                       "upcast" "use"
2123                       "val" "virtual" "void" "volatile"
2124                       "when" "while" "with"
2125                       "yield"))
2126
2127         (fsharp-builtins
2128          (mdw-regexps "asr" "land" "lor" "lsl" "lsr" "lxor" "mod"
2129                       "base" "false" "null" "true"))
2130
2131         (bang-keywords
2132          (mdw-regexps "do" "let" "return" "use" "yield"))
2133
2134         (preprocessor-keywords
2135          (mdw-regexps "if" "indent" "else" "endif")))
2136
2137     (setq font-lock-keywords
2138           (list (list (concat "\\(^\\|[^\"]\\)"
2139                               "\\(" "(\\*"
2140                                     "[^*]*\\*+"
2141                                     "\\(" "[^)*]" "[^*]*" "\\*+" "\\)*"
2142                                     ")"
2143                               "\\|"
2144                                     "//.*"
2145                               "\\)")
2146                       '(2 font-lock-comment-face))
2147
2148                 (list (concat "'" "\\("
2149                                     "\\\\"
2150                                     "\\(" "[ntbr'\\]"
2151                                     "\\|" "[0-9][0-9][0-9]"
2152                                     "\\|" "u" "[0-9a-fA-F]\\{4\\}"
2153                                     "\\|" "U" "[0-9a-fA-F]\\{8\\}"
2154                                     "\\)"
2155                                   "\\|"
2156                                   "." "\\)" "'"
2157                               "\\|"
2158                               "\"" "[^\"\\]*"
2159                                     "\\(" "\\\\" "\\(.\\|\n\\)"
2160                                           "[^\"\\]*" "\\)*"
2161                               "\\(\"\\|\\'\\)")
2162                       '(0 font-lock-string-face))
2163
2164                 (list (concat "\\_<\\(" bang-keywords "\\)!" "\\|"
2165                               "^#[ \t]*\\(" preprocessor-keywords "\\)\\_>"
2166                               "\\|"
2167                               "\\_<\\(" fsharp-keywords "\\)\\_>")
2168                       '(0 font-lock-keyword-face))
2169                 (list (concat "\\<\\(" fsharp-builtins "\\)\\_>")
2170                       '(0 font-lock-variable-name-face))
2171
2172                 (list (concat "\\_<"
2173                               "\\(" "0[bB][01]+" "\\|"
2174                                     "0[oO][0-7]+" "\\|"
2175                                     "0[xX][0-9a-fA-F]+" "\\)"
2176                               "\\(" "lf\\|LF" "\\|"
2177                                     "[uU]?[ysnlL]?" "\\)"
2178                               "\\|"
2179                               "\\_<"
2180                               "[0-9]+" "\\("
2181                                 "[mMQRZING]"
2182                                 "\\|"
2183                                 "\\(\\.[0-9]*\\)?"
2184                                 "\\([eE][-+]?[0-9]+\\)?"
2185                                 "[fFmM]?"
2186                                 "\\|"
2187                                 "[uU]?[ysnlL]?"
2188                               "\\)")
2189                       '(0 mdw-number-face))
2190
2191                 (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2192                       '(0 mdw-punct-face))))))
2193
2194 (defun mdw-fontify-inferior-fsharp ()
2195   (mdw-fontify-fsharp)
2196   (setq font-lock-keywords
2197         (append (list (list "^[#-]" '(0 font-lock-comment-face))
2198                       (list "^>" '(0 font-lock-keyword-face)))
2199                 font-lock-keywords)))
2200
2201 ;;;--------------------------------------------------------------------------
2202 ;;; Go programming configuration.
2203
2204 (defun mdw-fontify-go ()
2205
2206   (make-local-variable 'font-lock-keywords)
2207   (let ((go-keywords
2208          (mdw-regexps "break" "case" "chan" "const" "continue"
2209                       "default" "defer" "else" "fallthrough" "for"
2210                       "func" "go" "goto" "if" "import"
2211                       "interface" "map" "package" "range" "return"
2212                       "select" "struct" "switch" "type" "var"))
2213         (go-intrinsics
2214          (mdw-regexps "bool" "byte" "complex64" "complex128" "error"
2215                       "float32" "float64" "int" "uint8" "int16" "int32"
2216                       "int64" "rune" "string" "uint" "uint8" "uint16"
2217                       "uint32" "uint64" "uintptr" "void"
2218                       "false" "iota" "nil" "true"
2219                       "init" "main"
2220                       "append" "cap" "copy" "delete" "imag" "len" "make"
2221                       "new" "panic" "real" "recover")))
2222
2223     (setq font-lock-keywords
2224           (list
2225
2226            ;; Handle the keywords defined above.
2227            (list (concat "\\<\\(" go-keywords "\\)\\>")
2228                  '(0 font-lock-keyword-face))
2229            (list (concat "\\<\\(" go-intrinsics "\\)\\>")
2230                  '(0 font-lock-variable-name-face))
2231
2232            ;; Strings and characters.
2233            (list (concat "'"
2234                          "\\(" "[^\\']" "\\|"
2235                                "\\\\"
2236                                "\\(" "[abfnrtv\\'\"]" "\\|"
2237                                      "[0-7]\\{3\\}" "\\|"
2238                                      "x" "[0-9A-Fa-f]\\{2\\}" "\\|"
2239                                      "u" "[0-9A-Fa-f]\\{4\\}" "\\|"
2240                                      "U" "[0-9A-Fa-f]\\{8\\}" "\\)" "\\)"
2241                          "'"
2242                          "\\|"
2243                          "\""
2244                          "\\(" "[^\n\\\"]+" "\\|" "\\\\." "\\)*"
2245                          "\\(\"\\|$\\)"
2246                          "\\|"
2247                          "`" "[^`]+" "`")
2248                  '(0 font-lock-string-face))
2249
2250            ;; Handle numbers too.
2251            ;;
2252            ;; The following isn't quite right, but it's close enough.
2253            (list (concat "\\<\\("
2254                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
2255                          "[0-9]+\\(\\.[0-9]*\\|\\)"
2256                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)")
2257                  '(0 mdw-number-face))
2258
2259            ;; And anything else is punctuation.
2260            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2261                  '(0 mdw-punct-face))))))
2262
2263 ;;;--------------------------------------------------------------------------
2264 ;;; Rust programming configuration.
2265
2266 (setq-default rust-indent-offset 2)
2267
2268 (defun mdw-self-insert-and-indent (count)
2269   (interactive "p")
2270   (self-insert-command count)
2271   (indent-according-to-mode))
2272
2273 (defun mdw-fontify-rust ()
2274
2275   ;; Hack syntax categories.
2276   (modify-syntax-entry ?= ".")
2277
2278   ;; Fontify keywords and things.
2279   (make-local-variable 'font-lock-keywords)
2280   (let ((rust-keywords
2281          (mdw-regexps "abstract" "alignof" "as"
2282                       "become" "box" "break"
2283                       "const" "continue" "create"
2284                       "do"
2285                       "else" "enum" "extern"
2286                       "false" "final" "fn" "for"
2287                       "if" "impl" "in"
2288                       "let" "loop"
2289                       "macro" "match" "mod" "move" "mut"
2290                       "offsetof" "override"
2291                       "priv" "pub" "pure"
2292                       "ref" "return"
2293                       "self" "sizeof" "static" "struct" "super"
2294                       "true" "trait" "type" "typeof"
2295                       "unsafe" "unsized" "use"
2296                       "virtual"
2297                       "where" "while"
2298                       "yield"))
2299         (rust-builtins
2300          (mdw-regexps "array" "pointer" "slice" "tuple"
2301                       "bool" "true" "false"
2302                       "f32" "f64"
2303                       "i8" "i16" "i32" "i64" "isize"
2304                       "u8" "u16" "u32" "u64" "usize"
2305                       "char" "str")))
2306     (setq font-lock-keywords
2307           (list
2308
2309            ;; Handle the keywords defined above.
2310            (list (concat "\\<\\(" rust-keywords "\\)\\>")
2311                  '(0 font-lock-keyword-face))
2312            (list (concat "\\<\\(" rust-builtins "\\)\\>")
2313                  '(0 font-lock-variable-name-face))
2314
2315            ;; Handle numbers too.
2316            (list (concat "\\<\\("
2317                                "[0-9][0-9_]*"
2318                                "\\(" "\\(\\.[0-9_]+\\)?[eE][-+]?[0-9_]+"
2319                                "\\|" "\\.[0-9_]+"
2320                                "\\)"
2321                                "\\(f32\\|f64\\)?"
2322                          "\\|" "\\(" "[0-9][0-9_]*"
2323                                "\\|" "0x[0-9a-fA-F_]+"
2324                                "\\|" "0o[0-7_]+"
2325                                "\\|" "0b[01_]+"
2326                                "\\)"
2327                                "\\([ui]\\(8\\|16\\|32\\|64\\|s\\|size\\)\\)?"
2328                          "\\)\\>")
2329                  '(0 mdw-number-face))
2330
2331            ;; And anything else is punctuation.
2332            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2333                  '(0 mdw-punct-face)))))
2334
2335   ;; Hack key bindings.
2336   (local-set-key [?{] 'mdw-self-insert-and-indent)
2337   (local-set-key [?}] 'mdw-self-insert-and-indent))
2338
2339 ;;;--------------------------------------------------------------------------
2340 ;;; Awk programming configuration.
2341
2342 ;; Make Awk indentation nice.
2343
2344 (mdw-define-c-style mdw-awk
2345   (c-basic-offset . 2)
2346   (c-offsets-alist (substatement-open . 0)
2347                    (c-backslash-column . 72)
2348                    (statement-cont . 0)
2349                    (statement-case-intro . +)))
2350 (mdw-set-default-c-style 'awk-mode 'mdw-awk)
2351
2352 ;; Declare Awk fontification style.
2353
2354 (defun mdw-fontify-awk ()
2355
2356   ;; Miscellaneous fiddling.
2357   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
2358
2359   ;; Now define things to be fontified.
2360   (make-local-variable 'font-lock-keywords)
2361   (let ((c-keywords
2362          (mdw-regexps "BEGIN" "END" "ARGC" "ARGIND" "ARGV" "CONVFMT"
2363                       "ENVIRON" "ERRNO" "FIELDWIDTHS" "FILENAME" "FNR"
2364                       "FS" "IGNORECASE" "NF" "NR" "OFMT" "OFS" "ORS" "RS"
2365                       "RSTART" "RLENGTH" "RT"   "SUBSEP"
2366                       "atan2" "break" "close" "continue" "cos" "delete"
2367                       "do" "else" "exit" "exp" "fflush" "file" "for" "func"
2368                       "function" "gensub" "getline" "gsub" "if" "in"
2369                       "index" "int" "length" "log" "match" "next" "rand"
2370                       "return" "print" "printf" "sin" "split" "sprintf"
2371                       "sqrt" "srand" "strftime" "sub" "substr" "system"
2372                       "systime" "tolower" "toupper" "while")))
2373
2374     (setq font-lock-keywords
2375           (list
2376
2377            ;; Handle the keywords defined above.
2378            (list (concat "\\<\\(" c-keywords "\\)\\>")
2379                  '(0 font-lock-keyword-face))
2380
2381            ;; Handle numbers too.
2382            ;;
2383            ;; The following isn't quite right, but it's close enough.
2384            (list (concat "\\<\\("
2385                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
2386                          "[0-9]+\\(\\.[0-9]*\\|\\)"
2387                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)"
2388                          "[uUlL]*")
2389                  '(0 mdw-number-face))
2390
2391            ;; And anything else is punctuation.
2392            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2393                  '(0 mdw-punct-face))))))
2394
2395 ;;;--------------------------------------------------------------------------
2396 ;;; Perl programming style.
2397
2398 ;; Perl indentation style.
2399
2400 (setq perl-indent-level 2)
2401
2402 (setq cperl-indent-level 2)
2403 (setq cperl-continued-statement-offset 2)
2404 (setq cperl-continued-brace-offset 0)
2405 (setq cperl-brace-offset -2)
2406 (setq cperl-brace-imaginary-offset 0)
2407 (setq cperl-label-offset 0)
2408
2409 ;; Define perl fontification style.
2410
2411 (defun mdw-fontify-perl ()
2412
2413   ;; Miscellaneous fiddling.
2414   (modify-syntax-entry ?$ "\\")
2415   (modify-syntax-entry ?$ "\\" font-lock-syntax-table)
2416   (modify-syntax-entry ?: "." font-lock-syntax-table)
2417   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
2418
2419   ;; Now define fontification things.
2420   (make-local-variable 'font-lock-keywords)
2421   (let ((perl-keywords
2422          (mdw-regexps "and"
2423                       "break"
2424                       "cmp" "continue"
2425                       "default" "do"
2426                       "else" "elsif" "eq"
2427                       "for" "foreach"
2428                       "ge" "given" "gt" "goto"
2429                       "if"
2430                       "last" "le" "local" "lt"
2431                       "my"
2432                       "ne" "next"
2433                       "or" "our"
2434                       "package"
2435                       "redo" "require" "return"
2436                       "sub"
2437                       "undef" "unless" "until" "use"
2438                       "when" "while")))
2439
2440     (setq font-lock-keywords
2441           (list
2442
2443            ;; Set up the keywords defined above.
2444            (list (concat "\\<\\(" perl-keywords "\\)\\>")
2445                  '(0 font-lock-keyword-face))
2446
2447            ;; At least numbers are simpler than C.
2448            (list (concat "\\<0\\([xX][0-9a-fA-F_]+\\|[0-7_]+\\)\\|"
2449                          "\\<[0-9][0-9_]*\\(\\.[0-9_]*\\|\\)"
2450                          "\\([eE]\\([-+]\\|\\)[0-9_]+\\|\\)")
2451                  '(0 mdw-number-face))
2452
2453            ;; And anything else is punctuation.
2454            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2455                  '(0 mdw-punct-face))))))
2456
2457 (defun perl-number-tests (&optional arg)
2458   "Assign consecutive numbers to lines containing `#t'.  With ARG,
2459 strip numbers instead."
2460   (interactive "P")
2461   (save-excursion
2462     (goto-char (point-min))
2463     (let ((i 0) (fmt (if arg "" " %4d")))
2464       (while (search-forward "#t" nil t)
2465         (delete-region (point) (line-end-position))
2466         (setq i (1+ i))
2467         (insert (format fmt i)))
2468       (goto-char (point-min))
2469       (if (re-search-forward "\\(tests\\s-*=>\\s-*\\)\\w*" nil t)
2470           (replace-match (format "\\1%d" i))))))
2471
2472 ;;;--------------------------------------------------------------------------
2473 ;;; Python programming style.
2474
2475 (defun mdw-fontify-pythonic (keywords)
2476
2477   ;; Miscellaneous fiddling.
2478   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
2479   (setq indent-tabs-mode nil)
2480
2481   ;; Now define fontification things.
2482   (make-local-variable 'font-lock-keywords)
2483   (setq font-lock-keywords
2484         (list
2485
2486          ;; Set up the keywords defined above.
2487          (list (concat "\\_<\\(" keywords "\\)\\_>")
2488                '(0 font-lock-keyword-face))
2489
2490          ;; At least numbers are simpler than C.
2491          (list (concat "\\_<0\\([xX][0-9a-fA-F_]+\\|[0-7_]+\\)\\|"
2492                        "\\_<[0-9][0-9_]*\\(\\.[0-9_]*\\|\\)"
2493                        "\\([eE]\\([-+]\\|\\)[0-9_]+\\|[lL]\\|\\)")
2494                '(0 mdw-number-face))
2495
2496          ;; And anything else is punctuation.
2497          (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2498                '(0 mdw-punct-face)))))
2499
2500 ;; Define Python fontification styles.
2501
2502 (defun mdw-fontify-python ()
2503   (mdw-fontify-pythonic
2504    (mdw-regexps "and" "as" "assert" "break" "class" "continue" "def"
2505                 "del" "elif" "else" "except" "exec" "finally" "for"
2506                 "from" "global" "if" "import" "in" "is" "lambda"
2507                 "not" "or" "pass" "print" "raise" "return" "try"
2508                 "while" "with" "yield")))
2509
2510 (defun mdw-fontify-pyrex ()
2511   (mdw-fontify-pythonic
2512    (mdw-regexps "and" "as" "assert" "break" "cdef" "class" "continue"
2513                 "ctypedef" "def" "del" "elif" "else" "except" "exec"
2514                 "extern" "finally" "for" "from" "global" "if"
2515                 "import" "in" "is" "lambda" "not" "or" "pass" "print"
2516                 "raise" "return" "struct" "try" "while" "with"
2517                 "yield")))
2518
2519 ;;;--------------------------------------------------------------------------
2520 ;;; Icon programming style.
2521
2522 ;; Icon indentation style.
2523
2524 (setq icon-brace-offset 0
2525       icon-continued-brace-offset 0
2526       icon-continued-statement-offset 2
2527       icon-indent-level 2)
2528
2529 ;; Define Icon fontification style.
2530
2531 (defun mdw-fontify-icon ()
2532
2533   ;; Miscellaneous fiddling.
2534   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
2535
2536   ;; Now define fontification things.
2537   (make-local-variable 'font-lock-keywords)
2538   (let ((icon-keywords
2539          (mdw-regexps "break" "by" "case" "create" "default" "do" "else"
2540                       "end" "every" "fail" "global" "if" "initial"
2541                       "invocable" "link" "local" "next" "not" "of"
2542                       "procedure" "record" "repeat" "return" "static"
2543                       "suspend" "then" "to" "until" "while"))
2544         (preprocessor-keywords
2545          (mdw-regexps "define" "else" "endif" "error" "ifdef" "ifndef"
2546                       "include" "line" "undef")))
2547     (setq font-lock-keywords
2548           (list
2549
2550            ;; Set up the keywords defined above.
2551            (list (concat "\\<\\(" icon-keywords "\\)\\>")
2552                  '(0 font-lock-keyword-face))
2553
2554            ;; The things that Icon calls keywords.
2555            (list "&\\sw+\\>" '(0 font-lock-variable-name-face))
2556
2557            ;; At least numbers are simpler than C.
2558            (list (concat "\\<[0-9]+"
2559                          "\\([rR][0-9a-zA-Z]+\\|"
2560                          "\\.[0-9]+\\([eE][+-]?[0-9]+\\)?\\)\\>\\|"
2561                          "\\.[0-9]+\\([eE][+-]?[0-9]+\\)?\\>")
2562                  '(0 mdw-number-face))
2563
2564            ;; Preprocessor.
2565            (list (concat "^[ \t]*$[ \t]*\\<\\("
2566                          preprocessor-keywords
2567                          "\\)\\>")
2568                  '(0 font-lock-keyword-face))
2569
2570            ;; And anything else is punctuation.
2571            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2572                  '(0 mdw-punct-face))))))
2573
2574 ;;;--------------------------------------------------------------------------
2575 ;;; Assembler mode.
2576
2577 (defun mdw-fontify-asm ()
2578   (modify-syntax-entry ?' "\"")
2579   (modify-syntax-entry ?. "w")
2580   (modify-syntax-entry ?\n ">")
2581   (setf fill-prefix nil)
2582   (mdw-standard-fill-prefix "\\([ \t]*;+[ \t]*\\)"))
2583
2584 (defun mdw-asm-set-comment ()
2585   (modify-syntax-entry ?; "."
2586                        )
2587   (modify-syntax-entry asm-comment-char "<b")
2588   (setq comment-start (string asm-comment-char ? )))
2589 (add-hook 'asm-mode-local-variables-hook 'mdw-asm-set-comment)
2590 (put 'asm-comment-char 'safe-local-variable 'characterp)
2591
2592 ;;;--------------------------------------------------------------------------
2593 ;;; TCL configuration.
2594
2595 (defun mdw-fontify-tcl ()
2596   (mapcar #'(lambda (ch) (modify-syntax-entry ch ".")) '(?$))
2597   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
2598   (make-local-variable 'font-lock-keywords)
2599   (setq font-lock-keywords
2600         (list
2601          (list (concat "\\<0\\([xX][0-9a-fA-F_]+\\|[0-7_]+\\)\\|"
2602                        "\\<[0-9][0-9_]*\\(\\.[0-9_]*\\|\\)"
2603                        "\\([eE]\\([-+]\\|\\)[0-9_]+\\|\\)")
2604                '(0 mdw-number-face))
2605          (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2606                '(0 mdw-punct-face)))))
2607
2608 ;;;--------------------------------------------------------------------------
2609 ;;; Dylan programming configuration.
2610
2611 (defun mdw-fontify-dylan ()
2612
2613   (make-local-variable 'font-lock-keywords)
2614
2615   ;; Horrors.  `dylan-mode' sets the `major-mode' name after calling this
2616   ;; hook, which undoes all of our configuration.
2617   (setq major-mode 'dylan-mode)
2618   (font-lock-set-defaults)
2619
2620   (let* ((word "[-_a-zA-Z!*@<>$%]+")
2621          (dylan-keywords (mdw-regexps
2622
2623                           "C-address" "C-callable-wrapper" "C-function"
2624                           "C-mapped-subtype" "C-pointer-type" "C-struct"
2625                           "C-subtype" "C-union" "C-variable"
2626
2627                           "above" "abstract" "afterwards" "all"
2628                           "begin" "below" "block" "by"
2629                           "case" "class" "cleanup" "constant" "create"
2630                           "define" "domain"
2631                           "else" "elseif" "end" "exception" "export"
2632                           "finally" "for" "from" "function"
2633                           "generic"
2634                           "handler"
2635                           "if" "in" "instance" "interface" "iterate"
2636                           "keyed-by"
2637                           "let" "library" "local"
2638                           "macro" "method" "module"
2639                           "otherwise"
2640                           "profiling"
2641                           "select" "slot" "subclass"
2642                           "table" "then" "to"
2643                           "unless" "until" "use"
2644                           "variable" "virtual"
2645                           "when" "while"))
2646          (sharp-keywords (mdw-regexps
2647                           "all-keys" "key" "next" "rest" "include"
2648                           "t" "f")))
2649     (setq font-lock-keywords
2650           (list (list (concat "\\<\\(" dylan-keywords
2651                               "\\|" "with\\(out\\)?-" word
2652                               "\\)\\>")
2653                       '(0 font-lock-keyword-face))
2654                 (list (concat "\\<" word ":" "\\|"
2655                               "#\\(" sharp-keywords "\\)\\>")
2656                       '(0 font-lock-variable-name-face))
2657                 (list (concat "\\("
2658                               "\\([-+]\\|\\<\\)[0-9]+" "\\("
2659                                 "\\(\\.[0-9]+\\)?" "\\([eE][-+][0-9]+\\)?"
2660                                 "\\|" "/[0-9]+"
2661                               "\\)"
2662                               "\\|" "\\.[0-9]+" "\\([eE][-+][0-9]+\\)?"
2663                               "\\|" "#b[01]+"
2664                               "\\|" "#o[0-7]+"
2665                               "\\|" "#x[0-9a-zA-Z]+"
2666                               "\\)\\>")
2667                       '(0 mdw-number-face))
2668                 (list (concat "\\("
2669                               "\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\|"
2670                               "\\_<[-+*/=<>:&|]+\\_>"
2671                               "\\)")
2672                       '(0 mdw-punct-face))))))
2673
2674 ;;;--------------------------------------------------------------------------
2675 ;;; Algol 68 configuration.
2676
2677 (setq a68-indent-step 2)
2678
2679 (defun mdw-fontify-algol-68 ()
2680
2681   ;; Fix up the syntax table.
2682   (modify-syntax-entry ?# "!" a68-mode-syntax-table)
2683   (dolist (ch '(?- ?+ ?= ?< ?> ?* ?/ ?| ?&))
2684     (modify-syntax-entry ch "." a68-mode-syntax-table))
2685
2686   (make-local-variable 'font-lock-keywords)
2687
2688   (let ((not-comment
2689          (let ((word "COMMENT"))
2690            (do ((regexp (concat "[^" (substring word 0 1) "]+")
2691                         (concat regexp "\\|"
2692                                 (substring word 0 i)
2693                                 "[^" (substring word i (1+ i)) "]"))
2694                 (i 1 (1+ i)))
2695                ((>= i (length word)) regexp)))))
2696     (setq font-lock-keywords
2697           (list (list (concat "\\<COMMENT\\>"
2698                               "\\(" not-comment "\\)\\{0,5\\}"
2699                               "\\(\\'\\|\\<COMMENT\\>\\)")
2700                       '(0 font-lock-comment-face))
2701                 (list (concat "\\<CO\\>"
2702                               "\\([^C]+\\|C[^O]\\)\\{0,5\\}"
2703                               "\\($\\|\\<CO\\>\\)")
2704                       '(0 font-lock-comment-face))
2705                 (list "\\<[A-Z_]+\\>"
2706                       '(0 font-lock-keyword-face))
2707                 (list (concat "\\<"
2708                               "[0-9]+"
2709                               "\\(\\.[0-9]+\\)?"
2710                               "\\([eE][-+]?[0-9]+\\)?"
2711                               "\\>")
2712                       '(0 mdw-number-face))
2713                 (list "\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/"
2714                       '(0 mdw-punct-face))))))
2715
2716 ;;;--------------------------------------------------------------------------
2717 ;;; REXX configuration.
2718
2719 (defun mdw-rexx-electric-* ()
2720   (interactive)
2721   (insert ?*)
2722   (rexx-indent-line))
2723
2724 (defun mdw-rexx-indent-newline-indent ()
2725   (interactive)
2726   (rexx-indent-line)
2727   (if abbrev-mode (expand-abbrev))
2728   (newline-and-indent))
2729
2730 (defun mdw-fontify-rexx ()
2731
2732   ;; Various bits of fiddling.
2733   (setq mdw-auto-indent nil)
2734   (local-set-key [?\C-m] 'mdw-rexx-indent-newline-indent)
2735   (local-set-key [?*] 'mdw-rexx-electric-*)
2736   (mapcar #'(lambda (ch) (modify-syntax-entry ch "w"))
2737           '(?! ?? ?# ?@ ?$))
2738   (mdw-standard-fill-prefix "\\([ \t]*/?\*[ \t]*\\)")
2739
2740   ;; Set up keywords and things for fontification.
2741   (make-local-variable 'font-lock-keywords-case-fold-search)
2742   (setq font-lock-keywords-case-fold-search t)
2743
2744   (setq rexx-indent 2)
2745   (setq rexx-end-indent rexx-indent)
2746   (setq rexx-cont-indent rexx-indent)
2747
2748   (make-local-variable 'font-lock-keywords)
2749   (let ((rexx-keywords
2750          (mdw-regexps "address" "arg" "by" "call" "digits" "do" "drop"
2751                       "else" "end" "engineering" "exit" "expose" "for"
2752                       "forever" "form" "fuzz" "if" "interpret" "iterate"
2753                       "leave" "linein" "name" "nop" "numeric" "off" "on"
2754                       "options" "otherwise" "parse" "procedure" "pull"
2755                       "push" "queue" "return" "say" "select" "signal"
2756                       "scientific" "source" "then" "trace" "to" "until"
2757                       "upper" "value" "var" "version" "when" "while"
2758                       "with"
2759
2760                       "abbrev" "abs" "bitand" "bitor" "bitxor" "b2x"
2761                       "center" "center" "charin" "charout" "chars"
2762                       "compare" "condition" "copies" "c2d" "c2x"
2763                       "datatype" "date" "delstr" "delword" "d2c" "d2x"
2764                       "errortext" "format" "fuzz" "insert" "lastpos"
2765                       "left" "length" "lineout" "lines" "max" "min"
2766                       "overlay" "pos" "queued" "random" "reverse" "right"
2767                       "sign" "sourceline" "space" "stream" "strip"
2768                       "substr" "subword" "symbol" "time" "translate"
2769                       "trunc" "value" "verify" "word" "wordindex"
2770                       "wordlength" "wordpos" "words" "xrange" "x2b" "x2c"
2771                       "x2d")))
2772
2773     (setq font-lock-keywords
2774           (list
2775
2776            ;; Set up the keywords defined above.
2777            (list (concat "\\<\\(" rexx-keywords "\\)\\>")
2778                  '(0 font-lock-keyword-face))
2779
2780            ;; Fontify all symbols the same way.
2781            (list (concat "\\<\\([0-9.][A-Za-z0-9.!?_#@$]*[Ee][+-]?[0-9]+\\|"
2782                          "[A-Za-z0-9.!?_#@$]+\\)")
2783                  '(0 font-lock-variable-name-face))
2784
2785            ;; And everything else is punctuation.
2786            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2787                  '(0 mdw-punct-face))))))
2788
2789 ;;;--------------------------------------------------------------------------
2790 ;;; Standard ML programming style.
2791
2792 (defun mdw-fontify-sml ()
2793
2794   ;; Make underscore an honorary letter.
2795   (modify-syntax-entry ?' "w")
2796
2797   ;; Set fill prefix.
2798   (mdw-standard-fill-prefix "\\([ \t]*(\*[ \t]*\\)")
2799
2800   ;; Now define fontification things.
2801   (make-local-variable 'font-lock-keywords)
2802   (let ((sml-keywords
2803          (mdw-regexps "abstype" "and" "andalso" "as"
2804                       "case"
2805                       "datatype" "do"
2806                       "else" "end" "eqtype" "exception"
2807                       "fn" "fun" "functor"
2808                       "handle"
2809                       "if" "in" "include" "infix" "infixr"
2810                       "let" "local"
2811                       "nonfix"
2812                       "of" "op" "open" "orelse"
2813                       "raise" "rec"
2814                       "sharing" "sig" "signature" "struct" "structure"
2815                       "then" "type"
2816                       "val"
2817                       "where" "while" "with" "withtype")))
2818
2819     (setq font-lock-keywords
2820           (list
2821
2822            ;; Set up the keywords defined above.
2823            (list (concat "\\<\\(" sml-keywords "\\)\\>")
2824                  '(0 font-lock-keyword-face))
2825
2826            ;; At least numbers are simpler than C.
2827            (list (concat "\\<\\(\\~\\|\\)"
2828                             "\\(0\\(\\([wW]\\|\\)[xX][0-9a-fA-F]+\\|"
2829                                    "[wW][0-9]+\\)\\|"
2830                                 "\\([0-9]+\\(\\.[0-9]+\\|\\)"
2831                                          "\\([eE]\\(\\~\\|\\)"
2832                                                 "[0-9]+\\|\\)\\)\\)")
2833                  '(0 mdw-number-face))
2834
2835            ;; And anything else is punctuation.
2836            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2837                  '(0 mdw-punct-face))))))
2838
2839 ;;;--------------------------------------------------------------------------
2840 ;;; Haskell configuration.
2841
2842 (defun mdw-fontify-haskell ()
2843
2844   ;; Fiddle with syntax table to get comments right.
2845   (modify-syntax-entry ?' "_")
2846   (modify-syntax-entry ?- ". 12")
2847   (modify-syntax-entry ?\n ">")
2848
2849   ;; Make punctuation be punctuation
2850   (let ((punct "=<>+-*/|&%!@?$.^:#`"))
2851     (do ((i 0 (1+ i)))
2852         ((>= i (length punct)))
2853       (modify-syntax-entry (aref punct i) ".")))
2854
2855   ;; Set fill prefix.
2856   (mdw-standard-fill-prefix "\\([ \t]*{?--?[ \t]*\\)")
2857
2858   ;; Fiddle with fontification.
2859   (make-local-variable 'font-lock-keywords)
2860   (let ((haskell-keywords
2861          (mdw-regexps "as"
2862                       "case" "ccall" "class"
2863                       "data" "default" "deriving" "do"
2864                       "else" "exists"
2865                       "forall" "foreign"
2866                       "hiding"
2867                       "if" "import" "in" "infix" "infixl" "infixr" "instance"
2868                       "let"
2869                       "mdo" "module"
2870                       "newtype"
2871                       "of"
2872                       "proc"
2873                       "qualified"
2874                       "rec"
2875                       "safe" "stdcall"
2876                       "then" "type"
2877                       "unsafe"
2878                       "where"))
2879         (control-sequences
2880          (mdw-regexps "ACK" "BEL" "BS" "CAN" "CR" "DC1" "DC2" "DC3" "DC4"
2881                       "DEL" "DLE" "EM" "ENQ" "EOT" "ESC" "ETB" "ETX" "FF"
2882                       "FS" "GS" "HT" "LF" "NAK" "NUL" "RS" "SI" "SO" "SOH"
2883                       "SP" "STX" "SUB" "SYN" "US" "VT")))
2884
2885     (setq font-lock-keywords
2886           (list
2887            (list (concat "{-" "[^-]*" "\\(-+[^-}][^-]*\\)*"
2888                               "\\(-+}\\|-*\\'\\)"
2889                          "\\|"
2890                          "--.*$")
2891                  '(0 font-lock-comment-face))
2892            (list (concat "\\_<\\(" haskell-keywords "\\)\\_>")
2893                  '(0 font-lock-keyword-face))
2894            (list (concat "'\\("
2895                          "[^\\]"
2896                          "\\|"
2897                          "\\\\"
2898                          "\\(" "[abfnrtv\\\"']" "\\|"
2899                                "^" "\\(" control-sequences "\\|"
2900                                          "[]A-Z@[\\^_]" "\\)" "\\|"
2901                                "\\|"
2902                                "[0-9]+" "\\|"
2903                                "[oO][0-7]+" "\\|"
2904                                "[xX][0-9A-Fa-f]+"
2905                          "\\)"
2906                          "\\)'")
2907                  '(0 font-lock-string-face))
2908            (list "\\_<[A-Z]\\(\\sw+\\|\\s_+\\)*\\_>"
2909                  '(0 font-lock-variable-name-face))
2910            (list (concat "\\_<0\\([xX][0-9a-fA-F]+\\|[oO][0-7]+\\)\\|"
2911                          "\\_<[0-9]+\\(\\.[0-9]*\\|\\)"
2912                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)")
2913                  '(0 mdw-number-face))
2914            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2915                  '(0 mdw-punct-face))))))
2916
2917 ;;;--------------------------------------------------------------------------
2918 ;;; Erlang configuration.
2919
2920 (setq erlang-electric-commands nil)
2921
2922 (defun mdw-fontify-erlang ()
2923
2924   ;; Set fill prefix.
2925   (mdw-standard-fill-prefix "\\([ \t]*{?%*[ \t]*\\)")
2926
2927   ;; Fiddle with fontification.
2928   (make-local-variable 'font-lock-keywords)
2929   (let ((erlang-keywords
2930          (mdw-regexps "after" "and" "andalso"
2931                       "band" "begin" "bnot" "bor" "bsl" "bsr" "bxor"
2932                       "case" "catch" "cond"
2933                       "div" "end" "fun" "if" "let" "not"
2934                       "of" "or" "orelse"
2935                       "query" "receive" "rem" "try" "when" "xor")))
2936
2937     (setq font-lock-keywords
2938           (list
2939            (list "%.*$"
2940                  '(0 font-lock-comment-face))
2941            (list (concat "\\<\\(" erlang-keywords "\\)\\>")
2942                  '(0 font-lock-keyword-face))
2943            (list (concat "^-\\sw+\\>")
2944                  '(0 font-lock-keyword-face))
2945            (list "\\<[0-9]+\\(\\|#[0-9a-zA-Z]+\\|[eE][+-]?[0-9]+\\)\\>"
2946                  '(0 mdw-number-face))
2947            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2948                  '(0 mdw-punct-face))))))
2949
2950 ;;;--------------------------------------------------------------------------
2951 ;;; Texinfo configuration.
2952
2953 (defun mdw-fontify-texinfo ()
2954
2955   ;; Set fill prefix.
2956   (mdw-standard-fill-prefix "\\([ \t]*@c[ \t]+\\)")
2957
2958   ;; Real fontification things.
2959   (make-local-variable 'font-lock-keywords)
2960   (setq font-lock-keywords
2961         (list
2962
2963          ;; Environment names are keywords.
2964          (list "@\\(end\\)  *\\([a-zA-Z]*\\)?"
2965                '(2 font-lock-keyword-face))
2966
2967          ;; Unmark escaped magic characters.
2968          (list "\\(@\\)\\([@{}]\\)"
2969                '(1 font-lock-keyword-face)
2970                '(2 font-lock-variable-name-face))
2971
2972          ;; Make sure we get comments properly.
2973          (list "@c\\(\\|omment\\)\\( .*\\)?$"
2974                '(0 font-lock-comment-face))
2975
2976          ;; Command names are keywords.
2977          (list "@\\([^a-zA-Z@]\\|[a-zA-Z@]*\\)"
2978                '(0 font-lock-keyword-face))
2979
2980          ;; Fontify TeX special characters as punctuation.
2981          (list "[{}]+"
2982                '(0 mdw-punct-face)))))
2983
2984 ;;;--------------------------------------------------------------------------
2985 ;;; TeX and LaTeX configuration.
2986
2987 (defun mdw-fontify-tex ()
2988   (setq ispell-parser 'tex)
2989   (turn-on-reftex)
2990
2991   ;; Don't make maths into a string.
2992   (modify-syntax-entry ?$ ".")
2993   (modify-syntax-entry ?$ "." font-lock-syntax-table)
2994   (local-set-key [?$] 'self-insert-command)
2995
2996   ;; Make `tab' be useful, given that tab stops in TeX don't work well.
2997   (local-set-key "\C-i" 'indent-relative)
2998   (setq indent-tabs-mode nil)
2999
3000   ;; Set fill prefix.
3001   (mdw-standard-fill-prefix "\\([ \t]*%+[ \t]*\\)")
3002
3003   ;; Real fontification things.
3004   (make-local-variable 'font-lock-keywords)
3005   (setq font-lock-keywords
3006         (list
3007
3008          ;; Environment names are keywords.
3009          (list (concat "\\\\\\(begin\\|end\\|newenvironment\\)"
3010                        "{\\([^}\n]*\\)}")
3011                '(2 font-lock-keyword-face))
3012
3013          ;; Suspended environment names are keywords too.
3014          (list (concat "\\\\\\(suspend\\|resume\\)\\(\\[[^]]*\\]\\)?"
3015                        "{\\([^}\n]*\\)}")
3016                '(3 font-lock-keyword-face))
3017
3018          ;; Command names are keywords.
3019          (list "\\\\\\([^a-zA-Z@]\\|[a-zA-Z@]*\\)"
3020                '(0 font-lock-keyword-face))
3021
3022          ;; Handle @/.../ for italics.
3023          ;; (list "\\(@/\\)\\([^/]*\\)\\(/\\)"
3024          ;;       '(1 font-lock-keyword-face)
3025          ;;       '(3 font-lock-keyword-face))
3026
3027          ;; Handle @*...* for boldness.
3028          ;; (list "\\(@\\*\\)\\([^*]*\\)\\(\\*\\)"
3029          ;;       '(1 font-lock-keyword-face)
3030          ;;       '(3 font-lock-keyword-face))
3031
3032          ;; Handle @`...' for literal syntax things.
3033          ;; (list "\\(@`\\)\\([^']*\\)\\('\\)"
3034          ;;       '(1 font-lock-keyword-face)
3035          ;;       '(3 font-lock-keyword-face))
3036
3037          ;; Handle @<...> for nonterminals.
3038          ;; (list "\\(@<\\)\\([^>]*\\)\\(>\\)"
3039          ;;       '(1 font-lock-keyword-face)
3040          ;;       '(3 font-lock-keyword-face))
3041
3042          ;; Handle other @-commands.
3043          ;; (list "@\\([^a-zA-Z]\\|[a-zA-Z]*\\)"
3044          ;;       '(0 font-lock-keyword-face))
3045
3046          ;; Make sure we get comments properly.
3047          (list "%.*"
3048                '(0 font-lock-comment-face))
3049
3050          ;; Fontify TeX special characters as punctuation.
3051          (list "[$^_{}#&]"
3052                '(0 mdw-punct-face)))))
3053
3054 ;;;--------------------------------------------------------------------------
3055 ;;; SGML hacking.
3056
3057 (defun mdw-sgml-mode ()
3058   (interactive)
3059   (sgml-mode)
3060   (mdw-standard-fill-prefix "")
3061   (make-local-variable 'sgml-delimiters)
3062   (setq sgml-delimiters
3063         '("AND" "&" "COM" "--" "CRO" "&#" "DSC" "]" "DSO" "[" "DTGC" "]"
3064           "DTGO" "[" "ERO" "&" "ETAGO" ":e" "GRPC" ")" "GRPO" "(" "LIT" "\""
3065           "LITA" "'" "MDC" ">" "MDO" "<!" "MINUS" "-" "MSC" "]]" "NESTC" "{"
3066           "NET" "}" "OPT" "?" "OR" "|" "PERO" "%" "PIC" ">" "PIO" "<?"
3067           "PLUS" "+" "REFC" "." "REP" "*" "RNI" "#" "SEQ" "," "STAGO" ":"
3068           "TAGC" "." "VI" "=" "MS-START" "<![" "MS-END" "]]>"
3069           "XML-ECOM" "-->" "XML-PIC" "?>" "XML-SCOM" "<!--" "XML-TAGCE" "/>"
3070           "NULL" ""))
3071   (setq major-mode 'mdw-sgml-mode)
3072   (setq mode-name "[mdw] SGML")
3073   (run-hooks 'mdw-sgml-mode-hook))
3074
3075 ;;;--------------------------------------------------------------------------
3076 ;;; Configuration files.
3077
3078 (defvar mdw-conf-quote-normal nil
3079   "*Control syntax category of quote characters `\"' and `''.
3080 If this is `t', consider quote characters to be normal
3081 punctuation, as for `conf-quote-normal'.  If this is `nil' then
3082 leave quote characters as quotes.  If this is a list, then
3083 consider the quote characters in the list to be normal
3084 punctuation.  If this is a single quote character, then consider
3085 that character only to be normal punctuation.")
3086 (defun mdw-conf-quote-normal-acceptable-value-p (value)
3087   "Is the VALUE is an acceptable value for `mdw-conf-quote-normal'?"
3088   (or (booleanp value)
3089       (every (lambda (v) (memq v '(?\" ?')))
3090              (if (listp value) value (list value)))))
3091 (put 'mdw-conf-quote-normal 'safe-local-variable
3092      'mdw-conf-quote-normal-acceptable-value-p)
3093
3094 (defun mdw-fix-up-quote ()
3095   "Apply the setting of `mdw-conf-quote-normal'."
3096   (let ((flag mdw-conf-quote-normal))
3097     (cond ((eq flag t)
3098            (conf-quote-normal t))
3099           ((not flag)
3100            nil)
3101           (t
3102            (let ((table (copy-syntax-table (syntax-table))))
3103              (mapc (lambda (ch) (modify-syntax-entry ch "." table))
3104                    (if (listp flag) flag (list flag)))
3105              (set-syntax-table table)
3106              (and font-lock-mode (font-lock-fontify-buffer)))))))
3107 (add-hook 'conf-mode-local-variables-hook 'mdw-fix-up-quote t t)
3108
3109 ;;;--------------------------------------------------------------------------
3110 ;;; Shell scripts.
3111
3112 (defun mdw-setup-sh-script-mode ()
3113
3114   ;; Fetch the shell interpreter's name.
3115   (let ((shell-name sh-shell-file))
3116
3117     ;; Try reading the hash-bang line.
3118     (save-excursion
3119       (goto-char (point-min))
3120       (if (looking-at "#![ \t]*\\([^ \t\n]*\\)")
3121           (setq shell-name (match-string 1))))
3122
3123     ;; Now try to set the shell.
3124     ;;
3125     ;; Don't let `sh-set-shell' bugger up my script.
3126     (let ((executable-set-magic #'(lambda (s &rest r) s)))
3127       (sh-set-shell shell-name)))
3128
3129   ;; Don't insert here-document scaffolding automatically.
3130   (local-set-key "<" 'self-insert-command)
3131
3132   ;; Now enable my keys and the fontification.
3133   (mdw-misc-mode-config)
3134
3135   ;; Set the indentation level correctly.
3136   (setq sh-indentation 2)
3137   (setq sh-basic-offset 2))
3138
3139 (setq sh-shell-file "/bin/sh")
3140
3141 ;; Awful hacking to override the shell detection for particular scripts.
3142 (defmacro define-custom-shell-mode (name shell)
3143   `(defun ,name ()
3144      (interactive)
3145      (set (make-local-variable 'sh-shell-file) ,shell)
3146      (sh-mode)))
3147 (define-custom-shell-mode bash-mode "/bin/bash")
3148 (define-custom-shell-mode rc-mode "/usr/bin/rc")
3149 (put 'sh-shell-file 'permanent-local t)
3150
3151 ;; Hack the rc syntax table.  Backquotes aren't paired in rc.
3152 (eval-after-load "sh-script"
3153   '(or (assq 'rc sh-mode-syntax-table-input)
3154        (let ((frag '(nil
3155                      ?# "<"
3156                      ?\n ">#"
3157                      ?\" "\"\""
3158                      ?\' "\"\'"
3159                      ?$ "'"
3160                      ?\` "."
3161                      ?! "_"
3162                      ?% "_"
3163                      ?. "_"
3164                      ?^ "_"
3165                      ?~ "_"
3166                      ?, "_"
3167                      ?= "."
3168                      ?< "."
3169                      ?> "."))
3170              (assoc (assq 'rc sh-mode-syntax-table-input)))
3171          (if assoc
3172              (rplacd assoc frag)
3173            (setq sh-mode-syntax-table-input
3174                  (cons (cons 'rc frag)
3175                        sh-mode-syntax-table-input))))))
3176
3177 ;;;--------------------------------------------------------------------------
3178 ;;; Emacs shell mode.
3179
3180 (defun mdw-eshell-prompt ()
3181   (let ((left "[") (right "]"))
3182     (when (= (user-uid) 0)
3183       (setq left "«" right "»"))
3184     (concat left
3185             (save-match-data
3186               (replace-regexp-in-string "\\..*$" "" (system-name)))
3187             " "
3188             (let* ((pwd (eshell/pwd)) (npwd (length pwd))
3189                    (home (expand-file-name "~")) (nhome (length home)))
3190               (if (and (>= npwd nhome)
3191                        (or (= nhome npwd)
3192                            (= (elt pwd nhome) ?/))
3193                        (string= (substring pwd 0 nhome) home))
3194                   (concat "~" (substring pwd (length home)))
3195                 pwd))
3196             right)))
3197 (setq eshell-prompt-function 'mdw-eshell-prompt)
3198 (setq eshell-prompt-regexp "^\\[[^]>]+\\(\\]\\|>>?\\)")
3199
3200 (defun eshell/e (file) (find-file file) nil)
3201 (defun eshell/ee (file) (find-file-other-window file) nil)
3202 (defun eshell/w3m (url) (w3m-goto-url url) nil)
3203
3204 (mdw-define-face eshell-prompt (t :weight bold))
3205 (mdw-define-face eshell-ls-archive (t :weight bold :foreground "red"))
3206 (mdw-define-face eshell-ls-backup (t :foreground "lightgrey" :slant italic))
3207 (mdw-define-face eshell-ls-product (t :foreground "lightgrey" :slant italic))
3208 (mdw-define-face eshell-ls-clutter (t :foreground "lightgrey" :slant italic))
3209 (mdw-define-face eshell-ls-executable (t :weight bold))
3210 (mdw-define-face eshell-ls-directory (t :foreground "cyan" :weight bold))
3211 (mdw-define-face eshell-ls-readonly (t nil))
3212 (mdw-define-face eshell-ls-symlink (t :foreground "cyan"))
3213
3214 ;;;--------------------------------------------------------------------------
3215 ;;; Messages-file mode.
3216
3217 (defun messages-mode-guts ()
3218   (setq messages-mode-syntax-table (make-syntax-table))
3219   (set-syntax-table messages-mode-syntax-table)
3220   (modify-syntax-entry ?0 "w" messages-mode-syntax-table)
3221   (modify-syntax-entry ?1 "w" messages-mode-syntax-table)
3222   (modify-syntax-entry ?2 "w" messages-mode-syntax-table)
3223   (modify-syntax-entry ?3 "w" messages-mode-syntax-table)
3224   (modify-syntax-entry ?4 "w" messages-mode-syntax-table)
3225   (modify-syntax-entry ?5 "w" messages-mode-syntax-table)
3226   (modify-syntax-entry ?6 "w" messages-mode-syntax-table)
3227   (modify-syntax-entry ?7 "w" messages-mode-syntax-table)
3228   (modify-syntax-entry ?8 "w" messages-mode-syntax-table)
3229   (modify-syntax-entry ?9 "w" messages-mode-syntax-table)
3230   (make-local-variable 'comment-start)
3231   (make-local-variable 'comment-end)
3232   (make-local-variable 'indent-line-function)
3233   (setq indent-line-function 'indent-relative)
3234   (mdw-standard-fill-prefix "\\([ \t]*\\(;\\|/?\\*\\)+[ \t]*\\)")
3235   (make-local-variable 'font-lock-defaults)
3236   (make-local-variable 'messages-mode-keywords)
3237   (let ((keywords
3238          (mdw-regexps "array" "bitmap" "callback" "docs[ \t]+enum"
3239                       "export" "enum" "fixed-octetstring" "flags"
3240                       "harmless" "map" "nested" "optional"
3241                       "optional-tagged" "package" "primitive"
3242                       "primitive-nullfree" "relaxed[ \t]+enum"
3243                       "set" "table" "tagged-optional"   "union"
3244                       "variadic" "vector" "version" "version-tag")))
3245     (setq messages-mode-keywords
3246           (list
3247            (list (concat "\\<\\(" keywords "\\)\\>:")
3248                  '(0 font-lock-keyword-face))
3249            '("\\([-a-zA-Z0-9]+:\\)" (0 font-lock-warning-face))
3250            '("\\(\\<[a-z][-_a-zA-Z0-9]*\\)"
3251              (0 font-lock-variable-name-face))
3252            '("\\<\\([0-9]+\\)\\>" (0 mdw-number-face))
3253            '("\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3254              (0 mdw-punct-face)))))
3255   (setq font-lock-defaults
3256         '(messages-mode-keywords nil nil nil nil))
3257   (run-hooks 'messages-file-hook))
3258
3259 (defun messages-mode ()
3260   (interactive)
3261   (fundamental-mode)
3262   (setq major-mode 'messages-mode)
3263   (setq mode-name "Messages")
3264   (messages-mode-guts)
3265   (modify-syntax-entry ?# "<" messages-mode-syntax-table)
3266   (modify-syntax-entry ?\n ">" messages-mode-syntax-table)
3267   (setq comment-start "# ")
3268   (setq comment-end "")
3269   (run-hooks 'messages-mode-hook))
3270
3271 (defun cpp-messages-mode ()
3272   (interactive)
3273   (fundamental-mode)
3274   (setq major-mode 'cpp-messages-mode)
3275   (setq mode-name "CPP Messages")
3276   (messages-mode-guts)
3277   (modify-syntax-entry ?* ". 23" messages-mode-syntax-table)
3278   (modify-syntax-entry ?/ ". 14" messages-mode-syntax-table)
3279   (setq comment-start "/* ")
3280   (setq comment-end " */")
3281   (let ((preprocessor-keywords
3282          (mdw-regexps "assert" "define" "elif" "else" "endif" "error"
3283                       "ident" "if" "ifdef" "ifndef" "import" "include"
3284                       "line" "pragma" "unassert" "undef" "warning")))
3285     (setq messages-mode-keywords
3286           (append (list (list (concat "^[ \t]*\\#[ \t]*"
3287                                       "\\(include\\|import\\)"
3288                                       "[ \t]*\\(<[^>]+\\(>\\|\\)\\)")
3289                               '(2 font-lock-string-face))
3290                         (list (concat "^\\([ \t]*#[ \t]*\\(\\("
3291                                       preprocessor-keywords
3292                                       "\\)\\>\\|[0-9]+\\|$\\)\\)")
3293                               '(1 font-lock-keyword-face)))
3294                   messages-mode-keywords)))
3295   (run-hooks 'cpp-messages-mode-hook))
3296
3297 (add-hook 'messages-mode-hook 'mdw-misc-mode-config t)
3298 (add-hook 'cpp-messages-mode-hook 'mdw-misc-mode-config t)
3299 ; (add-hook 'messages-file-hook 'mdw-fontify-messages t)
3300
3301 ;;;--------------------------------------------------------------------------
3302 ;;; Messages-file mode.
3303
3304 (defvar mallow-driver-substitution-face 'mallow-driver-substitution-face
3305   "Face to use for subsittution directives.")
3306 (make-face 'mallow-driver-substitution-face)
3307 (defvar mallow-driver-text-face 'mallow-driver-text-face
3308   "Face to use for body text.")
3309 (make-face 'mallow-driver-text-face)
3310
3311 (defun mallow-driver-mode ()
3312   (interactive)
3313   (fundamental-mode)
3314   (setq major-mode 'mallow-driver-mode)
3315   (setq mode-name "Mallow driver")
3316   (setq mallow-driver-mode-syntax-table (make-syntax-table))
3317   (set-syntax-table mallow-driver-mode-syntax-table)
3318   (make-local-variable 'comment-start)
3319   (make-local-variable 'comment-end)
3320   (make-local-variable 'indent-line-function)
3321   (setq indent-line-function 'indent-relative)
3322   (mdw-standard-fill-prefix "\\([ \t]*\\(;\\|/?\\*\\)+[ \t]*\\)")
3323   (make-local-variable 'font-lock-defaults)
3324   (make-local-variable 'mallow-driver-mode-keywords)
3325   (let ((keywords
3326          (mdw-regexps "each" "divert" "file" "if"
3327                       "perl" "set" "string" "type" "write")))
3328     (setq mallow-driver-mode-keywords
3329           (list
3330            (list (concat "^%\\s *\\(}\\|\\(" keywords "\\)\\>\\).*$")
3331                  '(0 font-lock-keyword-face))
3332            (list "^%\\s *\\(#.*\\|\\)$"
3333                  '(0 font-lock-comment-face))
3334            (list "^%"
3335                  '(0 font-lock-keyword-face))
3336            (list "^|?\\(.+\\)$" '(1 mallow-driver-text-face))
3337            (list "\\${[^}]*}"
3338                  '(0 mallow-driver-substitution-face t)))))
3339   (setq font-lock-defaults
3340         '(mallow-driver-mode-keywords nil nil nil nil))
3341   (modify-syntax-entry ?\" "_" mallow-driver-mode-syntax-table)
3342   (modify-syntax-entry ?\n ">" mallow-driver-mode-syntax-table)
3343   (setq comment-start "%# ")
3344   (setq comment-end "")
3345   (run-hooks 'mallow-driver-mode-hook))
3346
3347 (add-hook 'mallow-driver-hook 'mdw-misc-mode-config t)
3348
3349 ;;;--------------------------------------------------------------------------
3350 ;;; NFast debugs.
3351
3352 (defun nfast-debug-mode ()
3353   (interactive)
3354   (fundamental-mode)
3355   (setq major-mode 'nfast-debug-mode)
3356   (setq mode-name "NFast debug")
3357   (setq messages-mode-syntax-table (make-syntax-table))
3358   (set-syntax-table messages-mode-syntax-table)
3359   (make-local-variable 'font-lock-defaults)
3360   (make-local-variable 'nfast-debug-mode-keywords)
3361   (setq truncate-lines t)
3362   (setq nfast-debug-mode-keywords
3363         (list
3364          '("^\\(NFast_\\(Connect\\|Disconnect\\|Submit\\|Wait\\)\\)"
3365            (0 font-lock-keyword-face))
3366          (list (concat "^[ \t]+\\(\\("
3367                        "[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]"
3368                        "[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]"
3369                        "[ \t]+\\)*"
3370                        "[0-9a-fA-F]+\\)[ \t]*$")
3371            '(0 mdw-number-face))
3372          '("^[ \t]+\.status=[ \t]+\\<\\(OK\\)\\>"
3373            (1 font-lock-keyword-face))
3374          '("^[ \t]+\.status=[ \t]+\\<\\([a-zA-Z][0-9a-zA-Z]*\\)\\>"
3375            (1 font-lock-warning-face))
3376          '("^[ \t]+\.status[ \t]+\\<\\(zero\\)\\>"
3377            (1 nil))
3378          (list (concat "^[ \t]+\\.cmd=[ \t]+"
3379                        "\\<\\([a-zA-Z][0-9a-zA-Z]*\\)\\>")
3380            '(1 font-lock-keyword-face))
3381          '("-?\\<\\([0-9]+\\|0x[0-9a-fA-F]+\\)\\>" (0 mdw-number-face))
3382          '("^\\([ \t]+[a-z0-9.]+\\)" (0 font-lock-variable-name-face))
3383          '("\\<\\([a-z][a-z0-9.]+\\)\\>=" (1 font-lock-variable-name-face))
3384          '("\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)" (0 mdw-punct-face))))
3385   (setq font-lock-defaults
3386         '(nfast-debug-mode-keywords nil nil nil nil))
3387   (run-hooks 'nfast-debug-mode-hook))
3388
3389 ;;;--------------------------------------------------------------------------
3390 ;;; Other languages.
3391
3392 ;; Smalltalk.
3393
3394 (defun mdw-setup-smalltalk ()
3395   (and mdw-auto-indent
3396        (local-set-key "\C-m" 'smalltalk-newline-and-indent))
3397   (make-local-variable 'mdw-auto-indent)
3398   (setq mdw-auto-indent nil)
3399   (local-set-key "\C-i" 'smalltalk-reindent))
3400
3401 (defun mdw-fontify-smalltalk ()
3402   (make-local-variable 'font-lock-keywords)
3403   (setq font-lock-keywords
3404         (list
3405          (list "\\<[A-Z][a-zA-Z0-9]*\\>"
3406                '(0 font-lock-keyword-face))
3407          (list (concat "\\<0\\([xX][0-9a-fA-F_]+\\|[0-7_]+\\)\\|"
3408                        "[0-9][0-9_]*\\(\\.[0-9_]*\\|\\)"
3409                        "\\([eE]\\([-+]\\|\\)[0-9_]+\\|\\)")
3410                '(0 mdw-number-face))
3411          (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3412                '(0 mdw-punct-face)))))
3413
3414 ;; Lispy languages.
3415
3416 ;; Unpleasant bodge.
3417 (unless (boundp 'slime-repl-mode-map)
3418   (setq slime-repl-mode-map (make-sparse-keymap)))
3419
3420 (defun mdw-indent-newline-and-indent ()
3421   (interactive)
3422   (indent-for-tab-command)
3423   (newline-and-indent))
3424
3425 (eval-after-load "cl-indent"
3426   '(progn
3427      (mapc #'(lambda (pair)
3428                (put (car pair)
3429                     'common-lisp-indent-function
3430                     (cdr pair)))
3431       '((destructuring-bind . ((&whole 4 &rest 1) 4 &body))
3432         (multiple-value-bind . ((&whole 4 &rest 1) 4 &body))))))
3433
3434 (defun mdw-common-lisp-indent ()
3435   (make-local-variable 'lisp-indent-function)
3436   (setq lisp-indent-function 'common-lisp-indent-function))
3437
3438 (setq lisp-simple-loop-indentation 2
3439       lisp-loop-keyword-indentation 6
3440       lisp-loop-forms-indentation 6)
3441
3442 (defun mdw-fontify-lispy ()
3443
3444   ;; Set fill prefix.
3445   (mdw-standard-fill-prefix "\\([ \t]*;+[ \t]*\\)")
3446
3447   ;; Not much fontification needed.
3448   (make-local-variable 'font-lock-keywords)
3449   (setq font-lock-keywords
3450         (list (list (concat "\\("
3451                             "\\_<[-+]?"
3452                             "\\(" "[0-9]+/[0-9]+"
3453                             "\\|" "\\(" "[0-9]+" "\\(\\.[0-9]*\\)?" "\\|"
3454                                         "\\.[0-9]+" "\\)"
3455                                   "\\([dDeEfFlLsS][-+]?[0-9]+\\)?"
3456                             "\\)"
3457                             "\\|"
3458                             "#"
3459                             "\\(" "x" "[-+]?"
3460                                   "[0-9A-Fa-f]+" "\\(/[0-9A-Fa-f]+\\)?"
3461                             "\\|" "o" "[-+]?" "[0-7]+" "\\(/[0-7]+\\)?"
3462                             "\\|" "b" "[-+]?" "[01]+" "\\(/[01]+\\)?"
3463                             "\\|" "[0-9]+" "r" "[-+]?"
3464                                   "[0-9a-zA-Z]+" "\\(/[0-9a-zA-Z]+\\)?"
3465                             "\\)"
3466                             "\\)\\_>")
3467                     '(0 mdw-number-face))
3468               (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3469                     '(0 mdw-punct-face)))))
3470
3471 (defun comint-send-and-indent ()
3472   (interactive)
3473   (comint-send-input)
3474   (and mdw-auto-indent
3475        (indent-for-tab-command)))
3476
3477 (defun mdw-setup-m4 ()
3478
3479   ;; Inexplicably, Emacs doesn't match braces in m4 mode.  This is very
3480   ;; annoying: fix it.
3481   (modify-syntax-entry ?{ "(")
3482   (modify-syntax-entry ?} ")")
3483
3484   ;; Fill prefix.
3485   (mdw-standard-fill-prefix "\\([ \t]*\\(?:#+\\|\\<dnl\\>\\)[ \t]*\\)"))
3486
3487 ;;;--------------------------------------------------------------------------
3488 ;;; Text mode.
3489
3490 (defun mdw-text-mode ()
3491   (setq fill-column 72)
3492   (flyspell-mode t)
3493   (mdw-standard-fill-prefix
3494    "\\([ \t]*\\([>#|:] ?\\)*[ \t]*\\)" 3)
3495   (auto-fill-mode 1))
3496
3497 ;;;--------------------------------------------------------------------------
3498 ;;; Outline and hide/show modes.
3499
3500 (defun mdw-outline-collapse-all ()
3501   "Completely collapse everything in the entire buffer."
3502   (interactive)
3503   (save-excursion
3504     (goto-char (point-min))
3505     (while (< (point) (point-max))
3506       (hide-subtree)
3507       (forward-line))))
3508
3509 (setq hs-hide-comments-when-hiding-all nil)
3510
3511 (defadvice hs-hide-all (after hide-first-comment activate)
3512   (save-excursion (hs-hide-initial-comment-block)))
3513
3514 ;;;--------------------------------------------------------------------------
3515 ;;; Shell mode.
3516
3517 (defun mdw-sh-mode-setup ()
3518   (local-set-key [?\C-a] 'comint-bol)
3519   (add-hook 'comint-output-filter-functions
3520             'comint-watch-for-password-prompt))
3521
3522 (defun mdw-term-mode-setup ()
3523   (setq term-prompt-regexp shell-prompt-pattern)
3524   (make-local-variable 'mouse-yank-at-point)
3525   (make-local-variable 'transient-mark-mode)
3526   (setq mouse-yank-at-point t)
3527   (auto-fill-mode -1)
3528   (setq tab-width 8))
3529
3530 (defun term-send-meta-right () (interactive) (term-send-raw-string "\e\e[C"))
3531 (defun term-send-meta-left  () (interactive) (term-send-raw-string "\e\e[D"))
3532 (defun term-send-ctrl-uscore () (interactive) (term-send-raw-string "\C-_"))
3533 (defun term-send-meta-meta-something ()
3534   (interactive)
3535   (term-send-raw-string "\e\e")
3536   (term-send-raw))
3537 (eval-after-load 'term
3538   '(progn
3539      (define-key term-raw-map [?\e ?\e] nil)
3540      (define-key term-raw-map [?\e ?\e t] 'term-send-meta-meta-something)
3541      (define-key term-raw-map [?\C-/] 'term-send-ctrl-uscore)
3542      (define-key term-raw-map [M-right] 'term-send-meta-right)
3543      (define-key term-raw-map [?\e ?\M-O ?C] 'term-send-meta-right)
3544      (define-key term-raw-map [M-left] 'term-send-meta-left)
3545      (define-key term-raw-map [?\e ?\M-O ?D] 'term-send-meta-left)))
3546
3547 (defadvice term-exec (before program-args-list compile activate)
3548   "If the PROGRAM argument is a list, interpret it as (PROGRAM . SWITCHES).
3549 This allows you to pass a list of arguments through `ansi-term'."
3550   (let ((program (ad-get-arg 2)))
3551     (if (listp program)
3552         (progn
3553           (ad-set-arg 2 (car program))
3554           (ad-set-arg 4 (cdr program))))))
3555
3556 (defun ssh (host)
3557   "Open a terminal containing an ssh session to the HOST."
3558   (interactive "sHost: ")
3559   (ansi-term (list "ssh" host) (format "ssh@%s" host)))
3560
3561 (defvar git-grep-command
3562   "env PAGER=cat git grep --no-color -nH -e "
3563   "*The default command for \\[git-grep].")
3564
3565 (defvar git-grep-history nil)
3566
3567 (defun git-grep (command-args)
3568   "Run `git grep' with user-specified args and collect output in a buffer."
3569   (interactive
3570    (list (read-shell-command "Run git grep (like this): "
3571                              git-grep-command 'git-grep-history)))
3572   (grep command-args))
3573
3574 ;;;--------------------------------------------------------------------------
3575 ;;; Inferior Emacs Lisp.
3576
3577 (setq comint-prompt-read-only t)
3578
3579 (eval-after-load "comint"
3580   '(progn
3581      (define-key comint-mode-map "\C-w" 'comint-kill-region)
3582      (define-key comint-mode-map [C-S-backspace] 'comint-kill-whole-line)))
3583
3584 (eval-after-load "ielm"
3585   '(progn
3586      (define-key ielm-map "\C-w" 'comint-kill-region)
3587      (define-key ielm-map [C-S-backspace] 'comint-kill-whole-line)))
3588
3589 ;;;----- That's all, folks --------------------------------------------------
3590
3591 (provide 'dot-emacs)