chiark / gitweb /
el/dot-emacs.el: Hack quotes in configuration files.
[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 ;; Some error trapping.
56 ;;
57 ;; If individual bits of this file go tits-up, we don't particularly want
58 ;; the whole lot to stop right there and then, because it's bloody annoying.
59
60 (defmacro trap (&rest forms)
61   "Execute FORMS without allowing errors to propagate outside."
62   (declare (indent 0)
63            (debug t))
64   `(condition-case err
65        ,(if (cdr forms) (cons 'progn forms) (car forms))
66      (error (message "Error (trapped): %s in %s"
67                      (error-message-string err)
68                      ',forms))))
69
70 ;; Configuration reading.
71
72 (defvar mdw-config nil)
73 (defun mdw-config (sym)
74   "Read the configuration variable named SYM."
75   (unless mdw-config
76     (setq mdw-config
77           (flet ((replace (what with)
78                    (goto-char (point-min))
79                    (while (re-search-forward what nil t)
80                      (replace-match with t))))
81             (with-temp-buffer
82               (insert-file-contents "~/.mdw.conf")
83               (replace  "^[ \t]*\\(#.*\\|\\)\n" "")
84               (replace (concat "^[ \t]*"
85                                "\\([-a-zA-Z0-9_.]*\\)"
86                                "[ \t]*=[ \t]*"
87                                "\\(.*[^ \t\n]\\|\\)"
88                                "[ \t]**\\(\n\\|$\\)")
89                        "(\\1 . \"\\2\")\n")
90               (car (read-from-string
91                     (concat "(" (buffer-string) ")")))))))
92   (cdr (assq sym mdw-config)))
93
94 ;; Set up the load path convincingly.
95
96 (dolist (dir (append (and (boundp 'debian-emacs-flavor)
97                           (list (concat "/usr/share/"
98                                         (symbol-name debian-emacs-flavor)
99                                         "/site-lisp")))))
100   (dolist (sub (directory-files dir t))
101     (when (and (file-accessible-directory-p sub)
102                (not (member sub load-path)))
103       (setq load-path (nconc load-path (list sub))))))
104
105 ;; Is an Emacs library available?
106
107 (defun library-exists-p (name)
108   "Return non-nil if NAME is an available library.
109 Return non-nil if NAME.el (or NAME.elc) somewhere on the Emacs
110 load path.  The non-nil value is the filename we found for the
111 library."
112   (let ((path load-path) elt (foundp nil))
113     (while (and path (not foundp))
114       (setq elt (car path))
115       (setq path (cdr path))
116       (setq foundp (or (let ((file (concat elt "/" name ".elc")))
117                          (and (file-exists-p file) file))
118                        (let ((file (concat elt "/" name ".el")))
119                          (and (file-exists-p file) file)))))
120     foundp))
121
122 (defun maybe-autoload (symbol file &optional docstring interactivep type)
123   "Set an autoload if the file actually exists."
124   (and (library-exists-p file)
125        (autoload symbol file docstring interactivep type)))
126
127 ;; Splitting windows.
128
129 (unless (fboundp 'scroll-bar-columns)
130   (defun scroll-bar-columns (side)
131     (cond ((eq side 'left) 0)
132           (window-system 3)
133           (t 1))))
134 (unless (fboundp 'fringe-columns)
135   (defun fringe-columns (side)
136     (cond ((not window-system) 0)
137           ((eq side 'left) 1)
138           (t 2))))
139
140 (defun mdw-horizontal-window-overhead ()
141   "Computes the horizontal window overhead.
142 This is the number of columns used by fringes, scroll bars and other such
143 cruft."
144   (if (not window-system)
145       1
146     (let ((tot 0))
147       (dolist (what '(scroll-bar fringe))
148         (dolist (side '(left right))
149           (incf tot (funcall (intern (concat (symbol-name what) "-columns"))
150                              side))))
151       tot)))
152
153 (defun mdw-split-window-horizontally (&optional width)
154   "Split a window horizontally.
155 Without a numeric argument, split the window approximately in
156 half.  With a numeric argument WIDTH, allocate WIDTH columns to
157 the left-hand window (if positive) or -WIDTH columns to the
158 right-hand window (if negative).  Space for scroll bars and
159 fringes is not taken out of the allowance for WIDTH, unlike
160 \\[split-window-horizontally]."
161   (interactive "P")
162   (split-window-horizontally
163    (cond ((null width) nil)
164          ((>= width 0) (+ width (mdw-horizontal-window-overhead)))
165          ((< width 0) width))))
166
167 (defun mdw-divvy-window (&optional width)
168   "Split a wide window into appropriate widths."
169   (interactive "P")
170   (setq width (cond (width (prefix-numeric-value width))
171                     ((and window-system
172                           (>= emacs-major-version 22))
173                      77)
174                     (t 78)))
175   (let* ((win (selected-window))
176          (sb-width (mdw-horizontal-window-overhead))
177          (c (/ (+ (window-width) sb-width)
178                (+ width sb-width))))
179     (while (> c 1)
180       (setq c (1- c))
181       (split-window-horizontally (+ width sb-width))
182       (other-window 1))
183     (select-window win)))
184
185 ;; Transient mark mode hacks.
186
187 (defadvice exchange-point-and-mark
188     (around mdw-highlight (&optional arg) activate compile)
189   "Maybe don't actually exchange point and mark.
190 If `transient-mark-mode' is on and the mark is inactive, then
191 just activate it.  A non-trivial prefix argument will force the
192 usual behaviour.  A trivial prefix argument (i.e., just C-u) will
193 activate the mark and temporarily enable `transient-mark-mode' if
194 it's currently off."
195   (cond ((or mark-active
196              (and (not transient-mark-mode) (not arg))
197              (and arg (or (not (consp arg))
198                           (not (= (car arg) 4)))))
199          ad-do-it)
200         (t
201          (or transient-mark-mode (setq transient-mark-mode 'only))
202          (set-mark (mark t)))))
203
204 ;; Functions for sexp diary entries.
205
206 (defun mdw-weekday (l)
207   "Return non-nil if `date' falls on one of the days of the week in L.
208 L is a list of day numbers (from 0 to 6 for Sunday through to
209 Saturday) or symbols `sunday', `monday', etc. (or a mixture).  If
210 the date stored in `date' falls on a listed day, then the
211 function returns non-nil."
212   (let ((d (calendar-day-of-week date)))
213     (or (memq d l)
214         (memq (nth d '(sunday monday tuesday wednesday
215                               thursday friday saturday)) l))))
216
217 (defun mdw-todo (&optional when)
218   "Return non-nil today, or on WHEN, whichever is later."
219   (let ((w (calendar-absolute-from-gregorian (calendar-current-date)))
220         (d (calendar-absolute-from-gregorian date)))
221     (if when
222         (setq w (max w (calendar-absolute-from-gregorian
223                         (cond
224                          ((not european-calendar-style)
225                           when)
226                          ((> (car when) 100)
227                           (list (nth 1 when)
228                                 (nth 2 when)
229                                 (nth 0 when)))
230                          (t
231                           (list (nth 1 when)
232                                 (nth 0 when)
233                                 (nth 2 when))))))))
234     (eq w d)))
235
236 ;; Fighting with Org-mode's evil key maps.
237
238 (defvar mdw-evil-keymap-keys
239   '(([S-up] . [?\C-c up])
240     ([S-down] . [?\C-c down])
241     ([S-left] . [?\C-c left])
242     ([S-right] . [?\C-c right])
243     (([M-up] [?\e up]) . [C-up])
244     (([M-down] [?\e down]) . [C-down])
245     (([M-left] [?\e left]) . [C-left])
246     (([M-right] [?\e right]) . [C-right]))
247   "Defines evil keybindings to clobber in `mdw-clobber-evil-keymap'.
248 The value is an alist mapping evil keys (as a list, or singleton)
249 to good keys (in the same form).")
250
251 (defun mdw-clobber-evil-keymap (keymap)
252   "Replace evil key bindings in the KEYMAP.
253 Evil key bindings are defined in `mdw-evil-keymap-keys'."
254   (dolist (entry mdw-evil-keymap-keys)
255     (let ((binding nil)
256           (keys (if (listp (car entry))
257                     (car entry)
258                   (list (car entry))))
259           (replacements (if (listp (cdr entry))
260                             (cdr entry)
261                           (list (cdr entry)))))
262       (catch 'found
263         (dolist (key keys)
264           (setq binding (lookup-key keymap key))
265           (when binding
266             (throw 'found nil))))
267       (when binding
268         (dolist (key keys)
269           (define-key keymap key nil))
270         (dolist (key replacements)
271           (define-key keymap key binding))))))
272
273 (eval-after-load "org-latex"
274   '(progn
275      (push '("strayman"
276              "\\documentclass{strayman}
277 \\usepackage[utf8]{inputenc}
278 \\usepackage[palatino, helvetica, courier, maths=cmr]{mdwfonts}
279 \\usepackage[T1]{fontenc}
280 \\usepackage{graphicx, tikz, mdwtab, mdwmath, crypto, longtable}"
281              ("\\section{%s}" . "\\section*{%s}")
282              ("\\subsection{%s}" . "\\subsection*{%s}")
283              ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
284              ("\\paragraph{%s}" . "\\paragraph*{%s}")
285              ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))
286            org-export-latex-classes)))
287
288 (setq org-export-docbook-xslt-proc-command "xsltproc --output %o %s %i"
289       org-export-docbook-xsl-fo-proc-command "fop %i.safe %o"
290       org-export-docbook-xslt-stylesheet
291       "/usr/share/xml/docbook/stylesheet/docbook-xsl/fo/docbook.xsl")
292
293 ;;;--------------------------------------------------------------------------
294 ;;; Mail and news hacking.
295
296 (define-derived-mode  mdwmail-mode mail-mode "[mdw] mail"
297   "Major mode for editing news and mail messages from external programs.
298 Not much right now.  Just support for doing MailCrypt stuff."
299   :syntax-table nil
300   :abbrev-table nil
301   (run-hooks 'mail-setup-hook))
302
303 (define-key mdwmail-mode-map [?\C-c ?\C-c] 'disabled-operation)
304
305 (add-hook 'mdwail-mode-hook
306           (lambda ()
307             (set-buffer-file-coding-system 'utf-8)
308             (make-local-variable 'paragraph-separate)
309             (make-local-variable 'paragraph-start)
310             (setq paragraph-start
311                   (concat "[ \t]*[-_][-_][-_]+$\\|^-- \\|-----\\|"
312                           paragraph-start))
313             (setq paragraph-separate
314                   (concat "[ \t]*[-_][-_][-_]+$\\|^-- \\|-----\\|"
315                           paragraph-separate))))
316
317 ;; How to encrypt in mdwmail.
318
319 (defun mdwmail-mc-encrypt (&optional recip scm start end from sign)
320   (or start
321       (setq start (save-excursion
322                     (goto-char (point-min))
323                     (or (search-forward "\n\n" nil t) (point-min)))))
324   (or end
325       (setq end (point-max)))
326   (mc-encrypt-generic recip scm start end from sign))
327
328 ;; How to sign in mdwmail.
329
330 (defun mdwmail-mc-sign (key scm start end uclr)
331   (or start
332       (setq start (save-excursion
333                     (goto-char (point-min))
334                     (or (search-forward "\n\n" nil t) (point-min)))))
335   (or end
336       (setq end (point-max)))
337   (mc-sign-generic key scm start end uclr))
338
339 ;; Some signature mangling.
340
341 (defun mdwmail-mangle-signature ()
342   (save-excursion
343     (goto-char (point-min))
344     (perform-replace "\n-- \n" "\n-- " nil nil nil)))
345 (add-hook 'mail-setup-hook 'mdwmail-mangle-signature)
346 (add-hook 'message-setup-hook 'mdwmail-mangle-signature)
347
348 ;; Insert my login name into message-ids, so I can score replies.
349
350 (defadvice message-unique-id (after mdw-user-name last activate compile)
351   "Ensure that the user's name appears at the end of the message-id string,
352 so that it can be used for convenient filtering."
353   (setq ad-return-value (concat ad-return-value "." (user-login-name))))
354
355 ;; Tell my movemail hack where movemail is.
356 ;;
357 ;; This is needed to shup up warnings about LD_PRELOAD.
358
359 (let ((path exec-path))
360   (while path
361     (let ((try (expand-file-name "movemail" (car path))))
362       (if (file-executable-p try)
363           (setenv "REAL_MOVEMAIL" try))
364       (setq path (cdr path)))))
365
366 (eval-after-load "erc"
367     '(load "~/.ercrc.el"))
368
369 ;;;--------------------------------------------------------------------------
370 ;;; Utility functions.
371
372 (or (fboundp 'line-number-at-pos)
373     (defun line-number-at-pos (&optional pos)
374       (let ((opoint (or pos (point))) start)
375         (save-excursion
376           (save-restriction
377             (goto-char (point-min))
378             (widen)
379             (forward-line 0)
380             (setq start (point))
381             (goto-char opoint)
382             (forward-line 0)
383             (1+ (count-lines 1 (point))))))))
384
385 (defun mdw-uniquify-alist (&rest alists)
386   "Return the concatenation of the ALISTS with duplicate elements removed.
387 The first association with a given key prevails; others are
388 ignored.  The input lists are not modified, although they'll
389 probably become garbage."
390   (and alists
391        (let ((start-list (cons nil nil)))
392          (mdw-do-uniquify start-list
393                           start-list
394                           (car alists)
395                           (cdr alists)))))
396
397 (defun mdw-do-uniquify (done end l rest)
398   "A helper function for mdw-uniquify-alist.
399 The DONE argument is a list whose first element is `nil'.  It
400 contains the uniquified alist built so far.  The leading `nil' is
401 stripped off at the end of the operation; it's only there so that
402 DONE always references a cons cell.  END refers to the final cons
403 cell in the DONE list; it is modified in place each time to avoid
404 the overheads of `append'ing all the time.  The L argument is the
405 alist we're currently processing; the remaining alists are given
406 in REST."
407
408   ;; There are several different cases to deal with here.
409   (cond
410
411    ;; Current list isn't empty.  Add the first item to the DONE list if
412    ;; there's not an item with the same KEY already there.
413    (l (or (assoc (car (car l)) done)
414           (progn
415             (setcdr end (cons (car l) nil))
416             (setq end (cdr end))))
417       (mdw-do-uniquify done end (cdr l) rest))
418
419    ;; The list we were working on is empty.  Shunt the next list into the
420    ;; current list position and go round again.
421    (rest (mdw-do-uniquify done end (car rest) (cdr rest)))
422
423    ;; Everything's done.  Remove the leading `nil' from the DONE list and
424    ;; return it.  Finished!
425    (t (cdr done))))
426
427 (defun date ()
428   "Insert the current date in a pleasing way."
429   (interactive)
430   (insert (save-excursion
431             (let ((buffer (get-buffer-create "*tmp*")))
432               (unwind-protect (progn (set-buffer buffer)
433                                      (erase-buffer)
434                                      (shell-command "date +%Y-%m-%d" t)
435                                      (goto-char (mark))
436                                      (delete-backward-char 1)
437                                      (buffer-string))
438                 (kill-buffer buffer))))))
439
440 (defun uuencode (file &optional name)
441   "UUencodes a file, maybe calling it NAME, into the current buffer."
442   (interactive "fInput file name: ")
443
444   ;; If NAME isn't specified, then guess from the filename.
445   (if (not name)
446       (setq name
447             (substring file
448                        (or (string-match "[^/]*$" file) 0))))
449   (print (format "uuencode `%s' `%s'" file name))
450
451   ;; Now actually do the thing.
452   (call-process "uuencode" file t nil name))
453
454 (defvar np-file "~/.np"
455   "*Where the `now-playing' file is.")
456
457 (defun np (&optional arg)
458   "Grabs a `now-playing' string."
459   (interactive)
460   (save-excursion
461     (or arg (progn
462               (goto-char (point-max))
463               (insert "\nNP: ")
464               (insert-file-contents np-file)))))
465
466 (defun mdw-version-< (ver-a ver-b)
467   "Answer whether VER-A is strictly earlier than VER-B.
468 VER-A and VER-B are version numbers, which are strings containing digit
469 sequences separated by `.'."
470   (let* ((la (mapcar (lambda (x) (car (read-from-string x)))
471                      (split-string ver-a "\\.")))
472          (lb (mapcar (lambda (x) (car (read-from-string x)))
473                      (split-string ver-b "\\."))))
474     (catch 'done
475       (while t
476         (cond ((null la) (throw 'done lb))
477               ((null lb) (throw 'done nil))
478               ((< (car la) (car lb)) (throw 'done t))
479               ((= (car la) (car lb)) (setq la (cdr la) lb (cdr lb))))))))
480
481 (defun mdw-check-autorevert ()
482   "Sets global-auto-revert-ignore-buffer appropriately for this buffer.
483 This takes into consideration whether it's been found using
484 tramp, which seems to get itself into a twist."
485   (cond ((not (boundp 'global-auto-revert-ignore-buffer))
486          nil)
487         ((and (buffer-file-name)
488               (fboundp 'tramp-tramp-file-p)
489               (tramp-tramp-file-p (buffer-file-name)))
490          (unless global-auto-revert-ignore-buffer
491            (setq global-auto-revert-ignore-buffer 'tramp)))
492         ((eq global-auto-revert-ignore-buffer 'tramp)
493          (setq global-auto-revert-ignore-buffer nil))))
494
495 (defadvice find-file (after mdw-autorevert activate)
496   (mdw-check-autorevert))
497 (defadvice write-file (after mdw-autorevert activate)
498   (mdw-check-autorevert))
499
500 ;;;--------------------------------------------------------------------------
501 ;;; Dired hacking.
502
503 (defadvice dired-maybe-insert-subdir
504     (around mdw-marked-insertion first activate)
505   "The DIRNAME may be a list of directory names to insert.
506 Interactively, if files are marked, then insert all of them.
507 With a numeric prefix argument, select that many entries near
508 point; with a non-numeric prefix argument, prompt for listing
509 options."
510   (interactive
511    (list (dired-get-marked-files nil
512                                  (and (integerp current-prefix-arg)
513                                       current-prefix-arg)
514                                  #'file-directory-p)
515          (and current-prefix-arg
516               (not (integerp current-prefix-arg))
517               (read-string "Switches for listing: "
518                            (or dired-subdir-switches
519                                dired-actual-switches)))))
520   (let ((dirs (ad-get-arg 0)))
521     (dolist (dir (if (listp dirs) dirs (list dirs)))
522       (ad-set-arg 0 dir)
523       ad-do-it)))
524
525 ;;;--------------------------------------------------------------------------
526 ;;; URL viewing.
527
528 (defun mdw-w3m-browse-url (url &optional new-session-p)
529   "Invoke w3m on the URL in its current window, or at least a different one.
530 If NEW-SESSION-P, start a new session."
531   (interactive "sURL: \nP")
532   (save-excursion
533     (let ((window (selected-window)))
534       (unwind-protect
535           (progn
536             (select-window (or (and (not new-session-p)
537                                     (get-buffer-window "*w3m*"))
538                                (progn
539                                  (if (one-window-p t) (split-window))
540                                  (get-lru-window))))
541             (w3m-browse-url url new-session-p))
542         (select-window window)))))
543
544 (defvar mdw-good-url-browsers
545   '(browse-url-generic
546     (w3m . mdw-w3m-browse-url)
547     browse-url-w3
548     browse-url-mozilla)
549   "List of good browsers for mdw-good-url-browsers.
550 Each item is a browser function name, or a cons (CHECK . FUNC).
551 A symbol FOO stands for (FOO . FOO).")
552
553 (defun mdw-good-url-browser ()
554   "Return a good URL browser.
555 Trundle the list of such things, finding the first item for which
556 CHECK is fboundp, and returning the correponding FUNC."
557   (let ((bs mdw-good-url-browsers) b check func answer)
558     (while (and bs (not answer))
559       (setq b (car bs)
560             bs (cdr bs))
561       (if (consp b)
562           (setq check (car b) func (cdr b))
563         (setq check b func b))
564       (if (fboundp check)
565           (setq answer func)))
566     answer))
567
568 (eval-after-load "w3m-search"
569   '(progn
570      (dolist
571          (item
572           '(("g" "Google" "http://www.google.co.uk/search?q=%s")
573             ("gd" "Google Directory"
574              "http://www.google.com/search?cat=gwd/Top&q=%s")
575             ("gg" "Google Groups" "http://groups.google.com/groups?q=%s")
576             ("ward" "Ward's wiki" "http://c2.com/cgi/wiki?%s")
577             ("gi" "Images" "http://images.google.com/images?q=%s")
578             ("rfc" "RFC"
579              "http://metalzone.distorted.org.uk/ftp/pub/mirrors/rfc/rfc%s.txt.gz")
580             ("wp" "Wikipedia"
581              "http://en.wikipedia.org/wiki/Special:Search?go=Go&search=%s")
582             ("imdb" "IMDb" "http://www.imdb.com/Find?%s")
583             ("nc-wiki" "nCipher wiki"
584              "http://wiki.ncipher.com/wiki/bin/view/Devel/?topic=%s")
585             ("map" "Google maps" "http://maps.google.co.uk/maps?q=%s&hl=en")
586             ("lp" "Launchpad bug by number"
587              "https://bugs.launchpad.net/bugs/%s")
588             ("lppkg" "Launchpad bugs by package"
589              "https://bugs.launchpad.net/%s")
590             ("msdn" "MSDN"
591              "http://social.msdn.microsoft.com/Search/en-GB/?query=%s&ac=8")
592             ("debbug" "Debian bug by number"
593              "http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=%s")
594             ("debbugpkg" "Debian bugs by package"
595              "http://bugs.debian.org/cgi-bin/pkgreport.cgi?pkg=%s")
596             ("ljlogin" "LJ login" "http://www.livejournal.com/login.bml")))
597        (add-to-list 'w3m-search-engine-alist
598                     (list (cadr item) (caddr item) nil))
599        (add-to-list 'w3m-uri-replace-alist
600                     (list (concat "\\`" (car item) ":")
601                           'w3m-search-uri-replace
602                           (cadr item))))))
603
604 ;;;--------------------------------------------------------------------------
605 ;;; Paragraph filling.
606
607 ;; Useful variables.
608
609 (defvar mdw-fill-prefix nil
610   "*Used by `mdw-line-prefix' and `mdw-fill-paragraph'.
611 If there's no fill prefix currently set (by the `fill-prefix'
612 variable) and there's a match from one of the regexps here, it
613 gets used to set the fill-prefix for the current operation.
614
615 The variable is a list of items of the form `REGEXP . PREFIX'; if
616 the REGEXP matches, the PREFIX is used to set the fill prefix.
617 It in turn is a list of things:
618
619   STRING -- insert a literal string
620   (match . N) -- insert the thing matched by bracketed subexpression N
621   (pad . N) -- a string of whitespace the same width as subexpression N
622   (expr . FORM) -- the result of evaluating FORM")
623
624 (make-variable-buffer-local 'mdw-fill-prefix)
625
626 (defvar mdw-hanging-indents
627   (concat "\\(\\("
628             "\\([*o+]\\|-[-#]?\\|[0-9]+\\.\\|\\[[0-9]+\\]\\|([a-zA-Z])\\)"
629             "[ \t]+"
630           "\\)?\\)")
631   "*Standard regexp matching parts of a hanging indent.
632 This is mainly useful in `auto-fill-mode'.")
633
634 ;; Setting things up.
635
636 (fset 'mdw-do-auto-fill (symbol-function 'do-auto-fill))
637
638 ;; Utility functions.
639
640 (defun mdw-tabify (s)
641   "Tabify the string S.  This is a horrid hack."
642   (save-excursion
643     (save-match-data
644       (let (start end)
645         (beginning-of-line)
646         (setq start (point-marker))
647         (insert s "\n")
648         (setq end (point-marker))
649         (tabify start end)
650         (setq s (buffer-substring start (1- end)))
651         (delete-region start end)
652         (set-marker start nil)
653         (set-marker end nil)
654         s))))
655
656 (defun mdw-examine-fill-prefixes (l)
657   "Given a list of dynamic fill prefixes, pick one which matches
658 context and return the static fill prefix to use.  Point must be
659 at the start of a line, and match data must be saved."
660   (cond ((not l) nil)
661                ((looking-at (car (car l)))
662                 (mdw-tabify (apply (function concat)
663                                    (mapcar (function mdw-do-prefix-match)
664                                            (cdr (car l))))))
665                (t (mdw-examine-fill-prefixes (cdr l)))))
666
667 (defun mdw-maybe-car (p)
668   "If P is a pair, return (car P), otherwise just return P."
669   (if (consp p) (car p) p))
670
671 (defun mdw-padding (s)
672   "Return a string the same width as S but made entirely from whitespace."
673   (let* ((l (length s)) (i 0) (n (make-string l ? )))
674     (while (< i l)
675       (if (= 9 (aref s i))
676           (aset n i 9))
677       (setq i (1+ i)))
678     n))
679
680 (defun mdw-do-prefix-match (m)
681   "Expand a dynamic prefix match element.
682 See `mdw-fill-prefix' for details."
683   (cond ((not (consp m)) (format "%s" m))
684            ((eq (car m) 'match) (match-string (mdw-maybe-car (cdr m))))
685            ((eq (car m) 'pad) (mdw-padding (match-string
686                                             (mdw-maybe-car (cdr m)))))
687            ((eq (car m) 'eval) (eval (cdr m)))
688            (t "")))
689
690 (defun mdw-choose-dynamic-fill-prefix ()
691   "Work out the dynamic fill prefix based on the variable `mdw-fill-prefix'."
692   (cond ((and fill-prefix (not (string= fill-prefix ""))) fill-prefix)
693            ((not mdw-fill-prefix) fill-prefix)
694            (t (save-excursion
695                 (beginning-of-line)
696                 (save-match-data
697                   (mdw-examine-fill-prefixes mdw-fill-prefix))))))
698
699 (defun do-auto-fill ()
700   "Handle auto-filling, working out a dynamic fill prefix in the
701 case where there isn't a sensible static one."
702   (let ((fill-prefix (mdw-choose-dynamic-fill-prefix)))
703     (mdw-do-auto-fill)))
704
705 (defun mdw-fill-paragraph ()
706   "Fill paragraph, getting a dynamic fill prefix."
707   (interactive)
708   (let ((fill-prefix (mdw-choose-dynamic-fill-prefix)))
709     (fill-paragraph nil)))
710
711 (defun mdw-standard-fill-prefix (rx &optional mat)
712   "Set the dynamic fill prefix, handling standard hanging indents and stuff.
713 This is just a short-cut for setting the thing by hand, and by
714 design it doesn't cope with anything approximating a complicated
715 case."
716   (setq mdw-fill-prefix
717            `((,(concat rx mdw-hanging-indents)
718               (match . 1)
719               (pad . ,(or mat 2))))))
720
721 ;;;--------------------------------------------------------------------------
722 ;;; Other common declarations.
723
724 ;; Common mode settings.
725
726 (defvar mdw-auto-indent t
727   "Whether to indent automatically after a newline.")
728
729 (defun mdw-whitespace-mode (&optional arg)
730   "Turn on/off whitespace mode, but don't highlight trailing space."
731   (interactive "P")
732   (when (and (boundp 'whitespace-style)
733              (fboundp 'whitespace-mode))
734     (let ((whitespace-style (remove 'trailing whitespace-style)))
735       (whitespace-mode arg))
736     (setq show-trailing-whitespace whitespace-mode)))
737
738 (defun mdw-misc-mode-config ()
739   (and mdw-auto-indent
740        (cond ((eq major-mode 'lisp-mode)
741               (local-set-key "\C-m" 'mdw-indent-newline-and-indent))
742              ((or (eq major-mode 'slime-repl-mode)
743                   (eq major-mode 'asm-mode))
744               nil)
745              (t
746               (local-set-key "\C-m" 'newline-and-indent))))
747   (local-set-key [C-return] 'newline)
748   (make-local-variable 'page-delimiter)
749   (setq page-delimiter "\f\\|^.*-\\{6\\}.*$")
750   (setq comment-column 40)
751   (auto-fill-mode 1)
752   (setq fill-column 77)
753   (setq show-trailing-whitespace t)
754   (mdw-whitespace-mode 1)
755   (and (fboundp 'gtags-mode)
756        (gtags-mode))
757   (if (fboundp 'hs-minor-mode)
758       (hs-minor-mode t)
759     (outline-minor-mode t))
760   (reveal-mode t)
761   (trap (turn-on-font-lock)))
762
763 (defun mdw-post-config-mode-hack ()
764   (mdw-whitespace-mode 1))
765
766 (eval-after-load 'gtags
767   '(progn
768      (dolist (key '([mouse-2] [mouse-3]))
769        (define-key gtags-mode-map key nil))
770      (define-key gtags-mode-map [C-S-mouse-2] 'gtags-find-tag-by-event)
771      (define-key gtags-select-mode-map [C-S-mouse-2]
772        'gtags-select-tag-by-event)
773      (dolist (map (list gtags-mode-map gtags-select-mode-map))
774        (define-key map [C-S-mouse-3] 'gtags-pop-stack))))
775
776 ;; Backup file handling.
777
778 (defvar mdw-backup-disable-regexps nil
779   "*List of regular expressions: if a file name matches any of
780 these then the file is not backed up.")
781
782 (defun mdw-backup-enable-predicate (name)
783   "[mdw]'s default backup predicate.
784 Allows a backup if the standard predicate would allow it, and it
785 doesn't match any of the regular expressions in
786 `mdw-backup-disable-regexps'."
787   (and (normal-backup-enable-predicate name)
788        (let ((answer t) (list mdw-backup-disable-regexps))
789          (save-match-data
790            (while list
791              (if (string-match (car list) name)
792                  (setq answer nil))
793              (setq list (cdr list)))
794            answer))))
795 (setq backup-enable-predicate 'mdw-backup-enable-predicate)
796
797 ;; Frame cleanup.
798
799 (defun mdw-last-one-out-turn-off-the-lights (frame)
800   "Disconnect from an X display if this was the last frame on that display."
801   (let ((frame-display (frame-parameter frame 'display)))
802     (when (and frame-display
803                (eq window-system 'x)
804                (not (some (lambda (fr)
805                             (and (not (eq fr frame))
806                                  (string= (frame-parameter fr 'display)
807                                           frame-display)))
808                           (frame-list))))
809       (run-with-idle-timer 0 nil #'x-close-connection frame-display))))
810 (add-hook 'delete-frame-functions 'mdw-last-one-out-turn-off-the-lights)
811
812 ;;;--------------------------------------------------------------------------
813 ;;; General fontification.
814
815 (defmacro mdw-define-face (name &rest body)
816   "Define a face, and make sure it's actually set as the definition."
817   (declare (indent 1)
818            (debug 0))
819   `(progn
820      (make-face ',name)
821      (defvar ,name ',name)
822      (put ',name 'face-defface-spec ',body)
823      (face-spec-set ',name ',body nil)))
824
825 (mdw-define-face default
826   (((type w32)) :family "courier new" :height 85)
827   (((type x)) :family "6x13" :height 130)
828   (((type color)) :foreground "white" :background "black")
829   (t nil))
830 (mdw-define-face fixed-pitch
831   (((type w32)) :family "courier new" :height 85)
832   (((type x)) :family "6x13" :height 130)
833   (t :foreground "white" :background "black"))
834 (if (>= emacs-major-version 23)
835     (mdw-define-face variable-pitch
836       (((type x)) :family "sans" :height 100))
837   (mdw-define-face variable-pitch
838     (((type x)) :family "helvetica" :height 90)))
839 (mdw-define-face region
840   (((type tty) (class color)) :background "blue")
841   (((type tty) (class mono)) :inverse-video t)
842   (t :background "grey30"))
843 (mdw-define-face minibuffer-prompt
844   (t :weight bold))
845 (mdw-define-face mode-line
846   (((class color)) :foreground "blue" :background "yellow"
847                    :box (:line-width 1 :style released-button))
848   (t :inverse-video t))
849 (mdw-define-face mode-line-inactive
850   (((class color)) :foreground "yellow" :background "blue"
851                    :box (:line-width 1 :style released-button))
852   (t :inverse-video t))
853 (mdw-define-face scroll-bar
854   (t :foreground "black" :background "lightgrey"))
855 (mdw-define-face fringe
856   (t :foreground "yellow"))
857 (mdw-define-face show-paren-match
858   (((class color)) :background "darkgreen")
859   (t :underline t))
860 (mdw-define-face show-paren-mismatch
861   (((class color)) :background "red")
862   (t :inverse-video t))
863 (mdw-define-face highlight
864   (((class color)) :background "DarkSeaGreen4")
865   (t :inverse-video t))
866
867 (mdw-define-face holiday-face
868   (t :background "red"))
869 (mdw-define-face calendar-today-face
870   (t :foreground "yellow" :weight bold))
871
872 (mdw-define-face comint-highlight-prompt
873   (t :weight bold))
874 (mdw-define-face comint-highlight-input
875   (t nil))
876
877 (mdw-define-face dired-directory
878   (t :foreground "cyan" :weight bold))
879 (mdw-define-face dired-symlink
880   (t :foreground "cyan"))
881 (mdw-define-face dired-perm-write
882   (t nil))
883
884 (mdw-define-face trailing-whitespace
885   (((class color)) :background "red")
886   (t :inverse-video t))
887 (mdw-define-face mdw-punct-face
888   (((type tty)) :foreground "yellow") (t :foreground "burlywood2"))
889 (mdw-define-face mdw-number-face
890   (t :foreground "yellow"))
891 (mdw-define-face font-lock-function-name-face
892   (t :slant italic))
893 (mdw-define-face font-lock-keyword-face
894   (t :weight bold))
895 (mdw-define-face font-lock-constant-face
896   (t :slant italic))
897 (mdw-define-face font-lock-builtin-face
898   (t :weight bold))
899 (mdw-define-face font-lock-type-face
900   (t :weight bold :slant italic))
901 (mdw-define-face font-lock-reference-face
902   (t :weight bold))
903 (mdw-define-face font-lock-variable-name-face
904   (t :slant italic))
905 (mdw-define-face font-lock-comment-delimiter-face
906   (((class mono)) :weight bold)
907   (((type tty) (class color)) :foreground "green")
908   (t :slant italic :foreground "SeaGreen1"))
909 (mdw-define-face font-lock-comment-face
910   (((class mono)) :weight bold)
911   (((type tty) (class color)) :foreground "green")
912   (t :slant italic :foreground "SeaGreen1"))
913 (mdw-define-face font-lock-string-face
914   (((class mono)) :weight bold)
915   (((class color)) :foreground "SkyBlue1"))
916 (mdw-define-face message-separator
917   (t :background "red" :foreground "white" :weight bold))
918 (mdw-define-face message-cited-text
919   (default :slant italic)
920   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
921 (mdw-define-face message-header-cc
922   (default :weight bold)
923   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
924 (mdw-define-face message-header-newsgroups
925   (default :weight bold)
926   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
927 (mdw-define-face message-header-subject
928   (default :weight bold)
929   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
930 (mdw-define-face message-header-to
931   (default :weight bold)
932   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
933 (mdw-define-face message-header-xheader
934   (default :weight bold)
935   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
936 (mdw-define-face message-header-other
937   (default :weight bold)
938   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
939 (mdw-define-face message-header-name
940   (((type tty)) :foreground "green") (t :foreground "SeaGreen1"))
941 (mdw-define-face which-func
942   (t nil))
943
944 (mdw-define-face diff-header
945   (t nil))
946 (mdw-define-face diff-index
947   (t :weight bold))
948 (mdw-define-face diff-file-header
949   (t :weight bold))
950 (mdw-define-face diff-hunk-header
951   (t :foreground "SkyBlue1"))
952 (mdw-define-face diff-function
953   (t :foreground "SkyBlue1" :weight bold))
954 (mdw-define-face diff-header
955   (t :background "grey10"))
956 (mdw-define-face diff-added
957   (t :foreground "green"))
958 (mdw-define-face diff-removed
959   (t :foreground "red"))
960 (mdw-define-face diff-context
961   (t nil))
962 (mdw-define-face diff-refine-change
963   (t :background "RoyalBlue4"))
964
965 (mdw-define-face erc-input-face
966   (t :foreground "red"))
967
968 (mdw-define-face woman-bold
969   (t :weight bold))
970 (mdw-define-face woman-italic
971   (t :slant italic))
972
973 (mdw-define-face p4-depot-added-face
974   (t :foreground "green"))
975 (mdw-define-face p4-depot-branch-op-face
976   (t :foreground "yellow"))
977 (mdw-define-face p4-depot-deleted-face
978   (t :foreground "red"))
979 (mdw-define-face p4-depot-unmapped-face
980   (t :foreground "SkyBlue1"))
981 (mdw-define-face p4-diff-change-face
982   (t :foreground "yellow"))
983 (mdw-define-face p4-diff-del-face
984   (t :foreground "red"))
985 (mdw-define-face p4-diff-file-face
986   (t :foreground "SkyBlue1"))
987 (mdw-define-face p4-diff-head-face
988   (t :background "grey10"))
989 (mdw-define-face p4-diff-ins-face
990   (t :foreground "green"))
991
992 (mdw-define-face whizzy-slice-face
993   (t :background "grey10"))
994 (mdw-define-face whizzy-error-face
995   (t :background "darkred"))
996
997 ;; Ellipses used to indicate hidden text (and similar).
998 (mdw-define-face mdw-ellipsis-face
999   (((type tty)) :foreground "blue") (t :foreground "grey60"))
1000 (let ((dot (make-glyph-code ?. 'mdw-ellipsis-face)))
1001   (set-display-table-slot standard-display-table 4
1002                           (vector dot dot dot)))
1003
1004 ;;;--------------------------------------------------------------------------
1005 ;;; C programming configuration.
1006
1007 ;; Linux kernel hacking.
1008
1009 (defvar linux-c-mode-hook)
1010
1011 (defun linux-c-mode ()
1012   (interactive)
1013   (c-mode)
1014   (setq major-mode 'linux-c-mode)
1015   (setq mode-name "Linux C")
1016   (run-hooks 'linux-c-mode-hook))
1017
1018 ;; Make C indentation nice.
1019
1020 (defun mdw-c-lineup-arglist (langelem)
1021   "Hack for DWIMmery in c-lineup-arglist."
1022   (if (save-excursion
1023         (c-block-in-arglist-dwim (c-langelem-2nd-pos c-syntactic-element)))
1024       0
1025     (c-lineup-arglist langelem)))
1026
1027 (defun mdw-c-indent-extern-mumble (langelem)
1028   "Indent `extern \"...\" {' lines."
1029   (save-excursion
1030     (back-to-indentation)
1031     (if (looking-at
1032          "\\s-*\\<extern\\>\\s-*\"\\([^\\\\\"]+\\|\\.\\)*\"\\s-*{")
1033         c-basic-offset
1034       nil)))
1035
1036 (defun mdw-c-style ()
1037   (c-add-style "[mdw] C and C++ style"
1038                '((c-basic-offset . 2)
1039                  (comment-column . 40)
1040                  (c-class-key . "class")
1041                  (c-backslash-column . 72)
1042                  (c-offsets-alist
1043                   (substatement-open . (add 0 c-indent-one-line-block))
1044                   (defun-open . (add 0 c-indent-one-line-block))
1045                   (arglist-cont-nonempty . mdw-c-lineup-arglist)
1046                   (topmost-intro . mdw-c-indent-extern-mumble)
1047                   (cpp-define-intro . 0)
1048                   (knr-argdecl . 0)
1049                   (inextern-lang . [0])
1050                   (label . 0)
1051                   (case-label . +)
1052                   (access-label . -)
1053                   (inclass . +)
1054                   (inline-open . ++)
1055                   (statement-cont . +)
1056                   (statement-case-intro . +)))
1057                t))
1058
1059 (defvar mdw-c-comment-fill-prefix
1060   `((,(concat "\\([ \t]*/?\\)"
1061               "\\(\*\\|//]\\)"
1062               "\\([ \t]*\\)"
1063               "\\([A-Za-z]+:[ \t]*\\)?"
1064               mdw-hanging-indents)
1065      (pad . 1) (match . 2) (pad . 3) (pad . 4) (pad . 5)))
1066   "Fill prefix matching C comments (both kinds).")
1067
1068 (defun mdw-fontify-c-and-c++ ()
1069
1070   ;; Fiddle with some syntax codes.
1071   (modify-syntax-entry ?* ". 23")
1072   (modify-syntax-entry ?/ ". 124b")
1073   (modify-syntax-entry ?\n "> b")
1074
1075   ;; Other stuff.
1076   (mdw-c-style)
1077   (setq c-hanging-comment-ender-p nil)
1078   (setq c-backslash-column 72)
1079   (setq c-label-minimum-indentation 0)
1080   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
1081
1082   ;; Now define things to be fontified.
1083   (make-local-variable 'font-lock-keywords)
1084   (let ((c-keywords
1085          (mdw-regexps "and"             ;C++
1086                       "and_eq"          ;C++
1087                       "asm"             ;K&R, GCC
1088                       "auto"            ;K&R, C89
1089                       "bitand"          ;C++
1090                       "bitor"           ;C++
1091                       "bool"            ;C++, C9X macro
1092                       "break"           ;K&R, C89
1093                       "case"            ;K&R, C89
1094                       "catch"           ;C++
1095                       "char"            ;K&R, C89
1096                       "class"           ;C++
1097                       "complex"         ;C9X macro, C++ template type
1098                       "compl"           ;C++
1099                       "const"           ;C89
1100                       "const_cast"      ;C++
1101                       "continue"        ;K&R, C89
1102                       "defined"         ;C89 preprocessor
1103                       "default"         ;K&R, C89
1104                       "delete"          ;C++
1105                       "do"              ;K&R, C89
1106                       "double"          ;K&R, C89
1107                       "dynamic_cast"    ;C++
1108                       "else"            ;K&R, C89
1109                       ;; "entry"        ;K&R -- never used
1110                       "enum"            ;C89
1111                       "explicit"        ;C++
1112                       "export"          ;C++
1113                       "extern"          ;K&R, C89
1114                       "false"           ;C++, C9X macro
1115                       "float"           ;K&R, C89
1116                       "for"             ;K&R, C89
1117                       ;; "fortran"      ;K&R
1118                       "friend"          ;C++
1119                       "goto"            ;K&R, C89
1120                       "if"              ;K&R, C89
1121                       "imaginary"       ;C9X macro
1122                       "inline"          ;C++, C9X, GCC
1123                       "int"             ;K&R, C89
1124                       "long"            ;K&R, C89
1125                       "mutable"         ;C++
1126                       "namespace"       ;C++
1127                       "new"             ;C++
1128                       "operator"        ;C++
1129                       "or"              ;C++
1130                       "or_eq"           ;C++
1131                       "private"         ;C++
1132                       "protected"       ;C++
1133                       "public"          ;C++
1134                       "register"        ;K&R, C89
1135                       "reinterpret_cast" ;C++
1136                       "restrict"         ;C9X
1137                       "return"           ;K&R, C89
1138                       "short"            ;K&R, C89
1139                       "signed"           ;C89
1140                       "sizeof"           ;K&R, C89
1141                       "static"           ;K&R, C89
1142                       "static_cast"      ;C++
1143                       "struct"           ;K&R, C89
1144                       "switch"           ;K&R, C89
1145                       "template"         ;C++
1146                       "this"             ;C++
1147                       "throw"            ;C++
1148                       "true"             ;C++, C9X macro
1149                       "try"              ;C++
1150                       "this"             ;C++
1151                       "typedef"          ;C89
1152                       "typeid"           ;C++
1153                       "typeof"           ;GCC
1154                       "typename"         ;C++
1155                       "union"            ;K&R, C89
1156                       "unsigned"         ;K&R, C89
1157                       "using"            ;C++
1158                       "virtual"          ;C++
1159                       "void"             ;C89
1160                       "volatile"         ;C89
1161                       "wchar_t"          ;C++, C89 library type
1162                       "while"            ;K&R, C89
1163                       "xor"              ;C++
1164                       "xor_eq"           ;C++
1165                       "_Bool"            ;C9X
1166                       "_Complex"         ;C9X
1167                       "_Imaginary"       ;C9X
1168                       "_Pragma"          ;C9X preprocessor
1169                       "__alignof__"      ;GCC
1170                       "__asm__"          ;GCC
1171                       "__attribute__"    ;GCC
1172                       "__complex__"      ;GCC
1173                       "__const__"        ;GCC
1174                       "__extension__"    ;GCC
1175                       "__imag__"         ;GCC
1176                       "__inline__"       ;GCC
1177                       "__label__"        ;GCC
1178                       "__real__"         ;GCC
1179                       "__signed__"       ;GCC
1180                       "__typeof__"       ;GCC
1181                       "__volatile__"     ;GCC
1182                       ))
1183         (preprocessor-keywords
1184          (mdw-regexps "assert" "define" "elif" "else" "endif" "error"
1185                       "ident" "if" "ifdef" "ifndef" "import" "include"
1186                       "line" "pragma" "unassert" "undef" "warning"))
1187         (objc-keywords
1188          (mdw-regexps "class" "defs" "encode" "end" "implementation"
1189                       "interface" "private" "protected" "protocol" "public"
1190                       "selector")))
1191
1192     (setq font-lock-keywords
1193           (list
1194
1195            ;; Fontify include files as strings.
1196            (list (concat "^[ \t]*\\#[ \t]*"
1197                          "\\(include\\|import\\)"
1198                          "[ \t]*\\(<[^>]+\\(>\\|\\)\\)")
1199                  '(2 font-lock-string-face))
1200
1201            ;; Preprocessor directives are `references'?.
1202            (list (concat "^\\([ \t]*#[ \t]*\\(\\("
1203                          preprocessor-keywords
1204                          "\\)\\>\\|[0-9]+\\|$\\)\\)")
1205                  '(1 font-lock-keyword-face))
1206
1207            ;; Handle the keywords defined above.
1208            (list (concat "@\\<\\(" objc-keywords "\\)\\>")
1209                  '(0 font-lock-keyword-face))
1210
1211            (list (concat "\\<\\(" c-keywords "\\)\\>")
1212                  '(0 font-lock-keyword-face))
1213
1214            ;; Handle numbers too.
1215            ;;
1216            ;; This looks strange, I know.  It corresponds to the
1217            ;; preprocessor's idea of what a number looks like, rather than
1218            ;; anything sensible.
1219            (list (concat "\\(\\<[0-9]\\|\\.[0-9]\\)"
1220                          "\\([Ee][+-]\\|[0-9A-Za-z_.]\\)*")
1221                  '(0 mdw-number-face))
1222
1223            ;; And anything else is punctuation.
1224            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1225                  '(0 mdw-punct-face))))
1226
1227     (mdw-post-config-mode-hack)))
1228
1229 ;;;--------------------------------------------------------------------------
1230 ;;; AP calc mode.
1231
1232 (defun apcalc-mode ()
1233   (interactive)
1234   (c-mode)
1235   (setq major-mode 'apcalc-mode)
1236   (setq mode-name "AP Calc")
1237   (run-hooks 'apcalc-mode-hook))
1238
1239 (defun mdw-fontify-apcalc ()
1240
1241   ;; Fiddle with some syntax codes.
1242   (modify-syntax-entry ?* ". 23")
1243   (modify-syntax-entry ?/ ". 14")
1244
1245   ;; Other stuff.
1246   (mdw-c-style)
1247   (setq c-hanging-comment-ender-p nil)
1248   (setq c-backslash-column 72)
1249   (setq comment-start "/* ")
1250   (setq comment-end " */")
1251   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
1252
1253   ;; Now define things to be fontified.
1254   (make-local-variable 'font-lock-keywords)
1255   (let ((c-keywords
1256          (mdw-regexps "break" "case" "cd" "continue" "define" "default"
1257                       "do" "else" "exit" "for" "global" "goto" "help" "if"
1258                       "local" "mat" "obj" "print" "quit" "read" "return"
1259                       "show" "static" "switch" "while" "write")))
1260
1261     (setq font-lock-keywords
1262           (list
1263
1264            ;; Handle the keywords defined above.
1265            (list (concat "\\<\\(" c-keywords "\\)\\>")
1266                  '(0 font-lock-keyword-face))
1267
1268            ;; Handle numbers too.
1269            ;;
1270            ;; This looks strange, I know.  It corresponds to the
1271            ;; preprocessor's idea of what a number looks like, rather than
1272            ;; anything sensible.
1273            (list (concat "\\(\\<[0-9]\\|\\.[0-9]\\)"
1274                          "\\([Ee][+-]\\|[0-9A-Za-z_.]\\)*")
1275                  '(0 mdw-number-face))
1276
1277            ;; And anything else is punctuation.
1278            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1279                  '(0 mdw-punct-face)))))
1280
1281   (mdw-post-config-mode-hack))
1282
1283 ;;;--------------------------------------------------------------------------
1284 ;;; Java programming configuration.
1285
1286 ;; Make indentation nice.
1287
1288 (defun mdw-java-style ()
1289   (c-add-style "[mdw] Java style"
1290                '((c-basic-offset . 2)
1291                  (c-offsets-alist (substatement-open . 0)
1292                                   (label . +)
1293                                   (case-label . +)
1294                                   (access-label . 0)
1295                                   (inclass . +)
1296                                   (statement-case-intro . +)))
1297                t))
1298
1299 ;; Declare Java fontification style.
1300
1301 (defun mdw-fontify-java ()
1302
1303   ;; Other stuff.
1304   (mdw-java-style)
1305   (setq c-hanging-comment-ender-p nil)
1306   (setq c-backslash-column 72)
1307   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
1308
1309   ;; Now define things to be fontified.
1310   (make-local-variable 'font-lock-keywords)
1311   (let ((java-keywords
1312          (mdw-regexps "abstract" "boolean" "break" "byte" "case" "catch"
1313                       "char" "class" "const" "continue" "default" "do"
1314                       "double" "else" "extends" "final" "finally" "float"
1315                       "for" "goto" "if" "implements" "import" "instanceof"
1316                       "int" "interface" "long" "native" "new" "package"
1317                       "private" "protected" "public" "return" "short"
1318                       "static" "super" "switch" "synchronized" "this"
1319                       "throw" "throws" "transient" "try" "void" "volatile"
1320                       "while"
1321
1322                       "false" "null" "true")))
1323
1324     (setq font-lock-keywords
1325           (list
1326
1327            ;; Handle the keywords defined above.
1328            (list (concat "\\<\\(" java-keywords "\\)\\>")
1329                  '(0 font-lock-keyword-face))
1330
1331            ;; Handle numbers too.
1332            ;;
1333            ;; The following isn't quite right, but it's close enough.
1334            (list (concat "\\<\\("
1335                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
1336                          "[0-9]+\\(\\.[0-9]*\\|\\)"
1337                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)"
1338                          "[lLfFdD]?")
1339                  '(0 mdw-number-face))
1340
1341            ;; And anything else is punctuation.
1342            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1343                  '(0 mdw-punct-face)))))
1344
1345   (mdw-post-config-mode-hack))
1346
1347 ;;;--------------------------------------------------------------------------
1348 ;;; Javascript programming configuration.
1349
1350 (defun mdw-javascript-style ()
1351   (setq js-indent-level 2)
1352   (setq js-expr-indent-offset 0))
1353
1354 (defun mdw-fontify-javascript ()
1355
1356   ;; Other stuff.
1357   (mdw-javascript-style)
1358   (setq js-auto-indent-flag t)
1359
1360   ;; Now define things to be fontified.
1361   (make-local-variable 'font-lock-keywords)
1362   (let ((javascript-keywords
1363          (mdw-regexps "abstract" "boolean" "break" "byte" "case" "catch"
1364                       "char" "class" "const" "continue" "debugger" "default"
1365                       "delete" "do" "double" "else" "enum" "export" "extends"
1366                       "final" "finally" "float" "for" "function" "goto" "if"
1367                       "implements" "import" "in" "instanceof" "int"
1368                       "interface" "let" "long" "native" "new" "package"
1369                       "private" "protected" "public" "return" "short"
1370                       "static" "super" "switch" "synchronized" "throw"
1371                       "throws" "transient" "try" "typeof" "var" "void"
1372                       "volatile" "while" "with" "yield"
1373
1374                       "boolean" "byte" "char" "double" "float" "int" "long"
1375                       "short" "void"))
1376         (javascript-constants
1377          (mdw-regexps "false" "null" "undefined" "Infinity" "NaN" "true"
1378                       "arguments" "this")))
1379
1380     (setq font-lock-keywords
1381           (list
1382
1383            ;; Handle the keywords defined above.
1384            (list (concat "\\<\\(" javascript-keywords "\\)\\>")
1385                  '(0 font-lock-keyword-face))
1386
1387            ;; Handle the predefined constants defined above.
1388            (list (concat "\\<\\(" javascript-constants "\\)\\>")
1389                  '(0 font-lock-variable-name-face))
1390
1391            ;; Handle numbers too.
1392            ;;
1393            ;; The following isn't quite right, but it's close enough.
1394            (list (concat "\\<\\("
1395                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
1396                          "[0-9]+\\(\\.[0-9]*\\|\\)"
1397                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)"
1398                          "[lLfFdD]?")
1399                  '(0 mdw-number-face))
1400
1401            ;; And anything else is punctuation.
1402            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1403                  '(0 mdw-punct-face)))))
1404
1405   (mdw-post-config-mode-hack))
1406
1407 ;;;--------------------------------------------------------------------------
1408 ;;; C# programming configuration.
1409
1410 ;; Make indentation nice.
1411
1412 (defun mdw-csharp-style ()
1413   (c-add-style "[mdw] C# style"
1414                '((c-basic-offset . 2)
1415                  (c-offsets-alist (substatement-open . 0)
1416                                   (label . 0)
1417                                   (case-label . +)
1418                                   (access-label . 0)
1419                                   (inclass . +)
1420                                   (statement-case-intro . +)))
1421                t))
1422
1423 ;; Declare C# fontification style.
1424
1425 (defun mdw-fontify-csharp ()
1426
1427   ;; Other stuff.
1428   (mdw-csharp-style)
1429   (setq c-hanging-comment-ender-p nil)
1430   (setq c-backslash-column 72)
1431   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
1432
1433   ;; Now define things to be fontified.
1434   (make-local-variable 'font-lock-keywords)
1435   (let ((csharp-keywords
1436          (mdw-regexps "abstract" "as" "base" "bool" "break"
1437                       "byte" "case" "catch" "char" "checked"
1438                       "class" "const" "continue" "decimal" "default"
1439                       "delegate" "do" "double" "else" "enum"
1440                       "event" "explicit" "extern" "false" "finally"
1441                       "fixed" "float" "for" "foreach" "goto"
1442                       "if" "implicit" "in" "int" "interface"
1443                       "internal" "is" "lock" "long" "namespace"
1444                       "new" "null" "object" "operator" "out"
1445                       "override" "params" "private" "protected" "public"
1446                       "readonly" "ref" "return" "sbyte" "sealed"
1447                       "short" "sizeof" "stackalloc" "static" "string"
1448                       "struct" "switch" "this" "throw" "true"
1449                       "try" "typeof" "uint" "ulong" "unchecked"
1450                       "unsafe" "ushort" "using" "virtual" "void"
1451                       "volatile" "while" "yield")))
1452
1453     (setq font-lock-keywords
1454           (list
1455
1456            ;; Handle the keywords defined above.
1457            (list (concat "\\<\\(" csharp-keywords "\\)\\>")
1458                  '(0 font-lock-keyword-face))
1459
1460            ;; Handle numbers too.
1461            ;;
1462            ;; The following isn't quite right, but it's close enough.
1463            (list (concat "\\<\\("
1464                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
1465                          "[0-9]+\\(\\.[0-9]*\\|\\)"
1466                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)"
1467                          "[lLfFdD]?")
1468                  '(0 mdw-number-face))
1469
1470            ;; And anything else is punctuation.
1471            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1472                  '(0 mdw-punct-face)))))
1473
1474   (mdw-post-config-mode-hack))
1475
1476 (define-derived-mode csharp-mode java-mode "C#"
1477   "Major mode for editing C# code.")
1478
1479 ;;;--------------------------------------------------------------------------
1480 ;;; Go programming configuration.
1481
1482 (defun mdw-fontify-go ()
1483
1484   (make-local-variable 'font-lock-keywords)
1485   (let ((go-keywords
1486          (mdw-regexps "break" "case" "chan" "const" "continue"
1487                       "default" "defer" "else" "fallthrough" "for"
1488                       "func" "go" "goto" "if" "import"
1489                       "interface" "map" "package" "range" "return"
1490                       "select" "struct" "switch" "type" "var")))
1491
1492     (setq font-lock-keywords
1493           (list
1494
1495            ;; Handle the keywords defined above.
1496            (list (concat "\\<\\(" go-keywords "\\)\\>")
1497                  '(0 font-lock-keyword-face))
1498
1499            ;; Handle numbers too.
1500            ;;
1501            ;; The following isn't quite right, but it's close enough.
1502            (list (concat "\\<\\("
1503                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
1504                          "[0-9]+\\(\\.[0-9]*\\|\\)"
1505                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)")
1506                  '(0 mdw-number-face))
1507
1508            ;; And anything else is punctuation.
1509            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1510                  '(0 mdw-punct-face)))))
1511
1512   (mdw-post-config-mode-hack))
1513
1514 ;;;--------------------------------------------------------------------------
1515 ;;; Awk programming configuration.
1516
1517 ;; Make Awk indentation nice.
1518
1519 (defun mdw-awk-style ()
1520   (c-add-style "[mdw] Awk style"
1521                '((c-basic-offset . 2)
1522                  (c-offsets-alist (substatement-open . 0)
1523                                   (statement-cont . 0)
1524                                   (statement-case-intro . +)))
1525                t))
1526
1527 ;; Declare Awk fontification style.
1528
1529 (defun mdw-fontify-awk ()
1530
1531   ;; Miscellaneous fiddling.
1532   (mdw-awk-style)
1533   (setq c-backslash-column 72)
1534   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
1535
1536   ;; Now define things to be fontified.
1537   (make-local-variable 'font-lock-keywords)
1538   (let ((c-keywords
1539          (mdw-regexps "BEGIN" "END" "ARGC" "ARGIND" "ARGV" "CONVFMT"
1540                       "ENVIRON" "ERRNO" "FIELDWIDTHS" "FILENAME" "FNR"
1541                       "FS" "IGNORECASE" "NF" "NR" "OFMT" "OFS" "ORS" "RS"
1542                       "RSTART" "RLENGTH" "RT"   "SUBSEP"
1543                       "atan2" "break" "close" "continue" "cos" "delete"
1544                       "do" "else" "exit" "exp" "fflush" "file" "for" "func"
1545                       "function" "gensub" "getline" "gsub" "if" "in"
1546                       "index" "int" "length" "log" "match" "next" "rand"
1547                       "return" "print" "printf" "sin" "split" "sprintf"
1548                       "sqrt" "srand" "strftime" "sub" "substr" "system"
1549                       "systime" "tolower" "toupper" "while")))
1550
1551     (setq font-lock-keywords
1552           (list
1553
1554            ;; Handle the keywords defined above.
1555            (list (concat "\\<\\(" c-keywords "\\)\\>")
1556                  '(0 font-lock-keyword-face))
1557
1558            ;; Handle numbers too.
1559            ;;
1560            ;; The following isn't quite right, but it's close enough.
1561            (list (concat "\\<\\("
1562                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
1563                          "[0-9]+\\(\\.[0-9]*\\|\\)"
1564                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)"
1565                          "[uUlL]*")
1566                  '(0 mdw-number-face))
1567
1568            ;; And anything else is punctuation.
1569            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1570                  '(0 mdw-punct-face)))))
1571
1572   (mdw-post-config-mode-hack))
1573
1574 ;;;--------------------------------------------------------------------------
1575 ;;; Perl programming style.
1576
1577 ;; Perl indentation style.
1578
1579 (fset 'perl-mode 'cperl-mode)
1580 (setq cperl-indent-level 2)
1581 (setq cperl-continued-statement-offset 2)
1582 (setq cperl-continued-brace-offset 0)
1583 (setq cperl-brace-offset -2)
1584 (setq cperl-brace-imaginary-offset 0)
1585 (setq cperl-label-offset 0)
1586
1587 ;; Define perl fontification style.
1588
1589 (defun mdw-fontify-perl ()
1590
1591   ;; Miscellaneous fiddling.
1592   (modify-syntax-entry ?$ "\\")
1593   (modify-syntax-entry ?$ "\\" font-lock-syntax-table)
1594   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
1595
1596   ;; Now define fontification things.
1597   (make-local-variable 'font-lock-keywords)
1598   (let ((perl-keywords
1599          (mdw-regexps "and" "break" "cmp" "continue" "do" "else" "elsif" "eq"
1600                       "for" "foreach" "ge" "given" "gt" "goto" "if"
1601                       "last" "le" "lt" "local" "my" "ne" "next" "or"
1602                       "our" "package" "redo" "require" "return" "sub"
1603                       "undef" "unless" "until" "use" "when" "while")))
1604
1605     (setq font-lock-keywords
1606           (list
1607
1608            ;; Set up the keywords defined above.
1609            (list (concat "\\<\\(" perl-keywords "\\)\\>")
1610                  '(0 font-lock-keyword-face))
1611
1612            ;; At least numbers are simpler than C.
1613            (list (concat "\\<0\\([xX][0-9a-fA-F_]+\\|[0-7_]+\\)\\|"
1614                          "\\<[0-9][0-9_]*\\(\\.[0-9_]*\\|\\)"
1615                          "\\([eE]\\([-+]\\|\\)[0-9_]+\\|\\)")
1616                  '(0 mdw-number-face))
1617
1618            ;; And anything else is punctuation.
1619            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1620                  '(0 mdw-punct-face)))))
1621
1622   (mdw-post-config-mode-hack))
1623
1624 (defun perl-number-tests (&optional arg)
1625   "Assign consecutive numbers to lines containing `#t'.  With ARG,
1626 strip numbers instead."
1627   (interactive "P")
1628   (save-excursion
1629     (goto-char (point-min))
1630     (let ((i 0) (fmt (if arg "" " %4d")))
1631       (while (search-forward "#t" nil t)
1632         (delete-region (point) (line-end-position))
1633         (setq i (1+ i))
1634         (insert (format fmt i)))
1635       (goto-char (point-min))
1636       (if (re-search-forward "\\(tests\\s-*=>\\s-*\\)\\w*" nil t)
1637           (replace-match (format "\\1%d" i))))))
1638
1639 ;;;--------------------------------------------------------------------------
1640 ;;; Python programming style.
1641
1642 (defun mdw-fontify-pythonic (keywords)
1643
1644   ;; Miscellaneous fiddling.
1645   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
1646   (setq indent-tabs-mode nil)
1647
1648   ;; Now define fontification things.
1649   (make-local-variable 'font-lock-keywords)
1650   (setq font-lock-keywords
1651         (list
1652
1653          ;; Set up the keywords defined above.
1654          (list (concat "\\<\\(" keywords "\\)\\>")
1655                '(0 font-lock-keyword-face))
1656
1657          ;; At least numbers are simpler than C.
1658          (list (concat "\\<0\\([xX][0-9a-fA-F_]+\\|[0-7_]+\\)\\|"
1659                        "\\<[0-9][0-9_]*\\(\\.[0-9_]*\\|\\)"
1660                        "\\([eE]\\([-+]\\|\\)[0-9_]+\\|[lL]\\|\\)")
1661                '(0 mdw-number-face))
1662
1663          ;; And anything else is punctuation.
1664          (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1665                '(0 mdw-punct-face))))
1666
1667   (mdw-post-config-mode-hack))
1668
1669 ;; Define Python fontification styles.
1670
1671 (defun mdw-fontify-python ()
1672   (mdw-fontify-pythonic
1673    (mdw-regexps "and" "as" "assert" "break" "class" "continue" "def"
1674                 "del" "elif" "else" "except" "exec" "finally" "for"
1675                 "from" "global" "if" "import" "in" "is" "lambda"
1676                 "not" "or" "pass" "print" "raise" "return" "try"
1677                 "while" "with" "yield")))
1678
1679 (defun mdw-fontify-pyrex ()
1680   (mdw-fontify-pythonic
1681    (mdw-regexps "and" "as" "assert" "break" "cdef" "class" "continue"
1682                 "ctypedef" "def" "del" "elif" "else" "except" "exec"
1683                 "extern" "finally" "for" "from" "global" "if"
1684                 "import" "in" "is" "lambda" "not" "or" "pass" "print"
1685                 "raise" "return" "struct" "try" "while" "with"
1686                 "yield")))
1687
1688 ;;;--------------------------------------------------------------------------
1689 ;;; Icon programming style.
1690
1691 ;; Icon indentation style.
1692
1693 (setq icon-brace-offset 0
1694       icon-continued-brace-offset 0
1695       icon-continued-statement-offset 2
1696       icon-indent-level 2)
1697
1698 ;; Define Icon fontification style.
1699
1700 (defun mdw-fontify-icon ()
1701
1702   ;; Miscellaneous fiddling.
1703   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
1704
1705   ;; Now define fontification things.
1706   (make-local-variable 'font-lock-keywords)
1707   (let ((icon-keywords
1708          (mdw-regexps "break" "by" "case" "create" "default" "do" "else"
1709                       "end" "every" "fail" "global" "if" "initial"
1710                       "invocable" "link" "local" "next" "not" "of"
1711                       "procedure" "record" "repeat" "return" "static"
1712                       "suspend" "then" "to" "until" "while"))
1713         (preprocessor-keywords
1714          (mdw-regexps "define" "else" "endif" "error" "ifdef" "ifndef"
1715                       "include" "line" "undef")))
1716     (setq font-lock-keywords
1717           (list
1718
1719            ;; Set up the keywords defined above.
1720            (list (concat "\\<\\(" icon-keywords "\\)\\>")
1721                  '(0 font-lock-keyword-face))
1722
1723            ;; The things that Icon calls keywords.
1724            (list "&\\sw+\\>" '(0 font-lock-variable-name-face))
1725
1726            ;; At least numbers are simpler than C.
1727            (list (concat "\\<[0-9]+"
1728                          "\\([rR][0-9a-zA-Z]+\\|"
1729                          "\\.[0-9]+\\([eE][+-]?[0-9]+\\)?\\)\\>\\|"
1730                          "\\.[0-9]+\\([eE][+-]?[0-9]+\\)?\\>")
1731                  '(0 mdw-number-face))
1732
1733            ;; Preprocessor.
1734            (list (concat "^[ \t]*$[ \t]*\\<\\("
1735                          preprocessor-keywords
1736                          "\\)\\>")
1737                  '(0 font-lock-keyword-face))
1738
1739            ;; And anything else is punctuation.
1740            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1741                  '(0 mdw-punct-face)))))
1742
1743   (mdw-post-config-mode-hack))
1744
1745 ;;;--------------------------------------------------------------------------
1746 ;;; ARM assembler programming configuration.
1747
1748 ;; There doesn't appear to be an Emacs mode for this yet.
1749 ;;
1750 ;; Better do something about that, I suppose.
1751
1752 (defvar arm-assembler-mode-map nil)
1753 (defvar arm-assembler-abbrev-table nil)
1754 (defvar arm-assembler-mode-syntax-table (make-syntax-table))
1755
1756 (or arm-assembler-mode-map
1757     (progn
1758       (setq arm-assembler-mode-map (make-sparse-keymap))
1759       (define-key arm-assembler-mode-map "\C-m" 'arm-assembler-newline)
1760       (define-key arm-assembler-mode-map [C-return] 'newline)
1761       (define-key arm-assembler-mode-map "\t" 'tab-to-tab-stop)))
1762
1763 (defun arm-assembler-mode ()
1764   "Major mode for ARM assembler programs"
1765   (interactive)
1766
1767   ;; Do standard major mode things.
1768   (kill-all-local-variables)
1769   (use-local-map arm-assembler-mode-map)
1770   (setq local-abbrev-table arm-assembler-abbrev-table)
1771   (setq major-mode 'arm-assembler-mode)
1772   (setq mode-name "ARM assembler")
1773
1774   ;; Set up syntax table.
1775   (set-syntax-table arm-assembler-mode-syntax-table)
1776   (modify-syntax-entry ?;   ; Nasty hack
1777                        "<" arm-assembler-mode-syntax-table)
1778   (modify-syntax-entry ?\n ">" arm-assembler-mode-syntax-table)
1779   (modify-syntax-entry ?_ "_" arm-assembler-mode-syntax-table)
1780   (modify-syntax-entry ?' "\"'" arm-assembler-mode-syntax-table)
1781
1782   (make-local-variable 'comment-start)
1783   (setq comment-start ";")
1784   (make-local-variable 'comment-end)
1785   (setq comment-end "")
1786   (make-local-variable 'comment-column)
1787   (setq comment-column 48)
1788   (make-local-variable 'comment-start-skip)
1789   (setq comment-start-skip ";+[ \t]*")
1790
1791   ;; Play with indentation.
1792   (make-local-variable 'indent-line-function)
1793   (setq indent-line-function 'indent-relative-maybe)
1794
1795   ;; Set fill prefix.
1796   (mdw-standard-fill-prefix "\\([ \t]*;+[ \t]*\\)")
1797
1798   ;; Fiddle with fontification.
1799   (make-local-variable 'font-lock-keywords)
1800   (setq font-lock-keywords
1801         (list
1802
1803          ;; Handle numbers too.
1804          ;;
1805          ;; The following isn't quite right, but it's close enough.
1806          (list (concat "\\("
1807                        "&[0-9a-fA-F]+\\|"
1808                        "\\<[0-9]+\\(\\.[0-9]*\\|_[0-9a-zA-Z]+\\|\\)"
1809                        "\\)")
1810                '(0 mdw-number-face))
1811
1812          ;; Do something about operators.
1813          (list "^[^ \t]*[ \t]+\\(GET\\|LNK\\)[ \t]+\\([^;\n]*\\)"
1814                '(1 font-lock-keyword-face)
1815                '(2 font-lock-string-face))
1816          (list ":[a-zA-Z]+:"
1817                '(0 font-lock-keyword-face))
1818
1819          ;; Do menemonics and directives.
1820          (list "^[^ \t]*[ \t]+\\([a-zA-Z]+\\)"
1821                '(1 font-lock-keyword-face))
1822
1823          ;; And anything else is punctuation.
1824          (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1825                '(0 mdw-punct-face)))
1826
1827   (mdw-post-config-mode-hack))
1828   (run-hooks 'arm-assembler-mode-hook))
1829
1830 ;;;--------------------------------------------------------------------------
1831 ;;; Assembler mode.
1832
1833 (defun mdw-fontify-asm ()
1834   (modify-syntax-entry ?' "\"")
1835   (modify-syntax-entry ?. "w")
1836   (setf fill-prefix nil)
1837   (mdw-standard-fill-prefix "\\([ \t]*;+[ \t]*\\)"))
1838
1839 ;;;--------------------------------------------------------------------------
1840 ;;; TCL configuration.
1841
1842 (defun mdw-fontify-tcl ()
1843   (mapcar #'(lambda (ch) (modify-syntax-entry ch ".")) '(?$))
1844   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
1845   (make-local-variable 'font-lock-keywords)
1846   (setq font-lock-keywords
1847         (list
1848          (list (concat "\\<0\\([xX][0-9a-fA-F_]+\\|[0-7_]+\\)\\|"
1849                        "\\<[0-9][0-9_]*\\(\\.[0-9_]*\\|\\)"
1850                        "\\([eE]\\([-+]\\|\\)[0-9_]+\\|\\)")
1851                '(0 mdw-number-face))
1852          (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1853                '(0 mdw-punct-face))))
1854   (mdw-post-config-mode-hack))
1855
1856 ;;;--------------------------------------------------------------------------
1857 ;;; REXX configuration.
1858
1859 (defun mdw-rexx-electric-* ()
1860   (interactive)
1861   (insert ?*)
1862   (rexx-indent-line))
1863
1864 (defun mdw-rexx-indent-newline-indent ()
1865   (interactive)
1866   (rexx-indent-line)
1867   (if abbrev-mode (expand-abbrev))
1868   (newline-and-indent))
1869
1870 (defun mdw-fontify-rexx ()
1871
1872   ;; Various bits of fiddling.
1873   (setq mdw-auto-indent nil)
1874   (local-set-key [?\C-m] 'mdw-rexx-indent-newline-indent)
1875   (local-set-key [?*] 'mdw-rexx-electric-*)
1876   (mapcar #'(lambda (ch) (modify-syntax-entry ch "w"))
1877           '(?! ?? ?# ?@ ?$))
1878   (mdw-standard-fill-prefix "\\([ \t]*/?\*[ \t]*\\)")
1879
1880   ;; Set up keywords and things for fontification.
1881   (make-local-variable 'font-lock-keywords-case-fold-search)
1882   (setq font-lock-keywords-case-fold-search t)
1883
1884   (setq rexx-indent 2)
1885   (setq rexx-end-indent rexx-indent)
1886   (setq rexx-cont-indent rexx-indent)
1887
1888   (make-local-variable 'font-lock-keywords)
1889   (let ((rexx-keywords
1890          (mdw-regexps "address" "arg" "by" "call" "digits" "do" "drop"
1891                       "else" "end" "engineering" "exit" "expose" "for"
1892                       "forever" "form" "fuzz" "if" "interpret" "iterate"
1893                       "leave" "linein" "name" "nop" "numeric" "off" "on"
1894                       "options" "otherwise" "parse" "procedure" "pull"
1895                       "push" "queue" "return" "say" "select" "signal"
1896                       "scientific" "source" "then" "trace" "to" "until"
1897                       "upper" "value" "var" "version" "when" "while"
1898                       "with"
1899
1900                       "abbrev" "abs" "bitand" "bitor" "bitxor" "b2x"
1901                       "center" "center" "charin" "charout" "chars"
1902                       "compare" "condition" "copies" "c2d" "c2x"
1903                       "datatype" "date" "delstr" "delword" "d2c" "d2x"
1904                       "errortext" "format" "fuzz" "insert" "lastpos"
1905                       "left" "length" "lineout" "lines" "max" "min"
1906                       "overlay" "pos" "queued" "random" "reverse" "right"
1907                       "sign" "sourceline" "space" "stream" "strip"
1908                       "substr" "subword" "symbol" "time" "translate"
1909                       "trunc" "value" "verify" "word" "wordindex"
1910                       "wordlength" "wordpos" "words" "xrange" "x2b" "x2c"
1911                       "x2d")))
1912
1913     (setq font-lock-keywords
1914           (list
1915
1916            ;; Set up the keywords defined above.
1917            (list (concat "\\<\\(" rexx-keywords "\\)\\>")
1918                  '(0 font-lock-keyword-face))
1919
1920            ;; Fontify all symbols the same way.
1921            (list (concat "\\<\\([0-9.][A-Za-z0-9.!?_#@$]*[Ee][+-]?[0-9]+\\|"
1922                          "[A-Za-z0-9.!?_#@$]+\\)")
1923                  '(0 font-lock-variable-name-face))
1924
1925            ;; And everything else is punctuation.
1926            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1927                  '(0 mdw-punct-face)))))
1928
1929   (mdw-post-config-mode-hack))
1930
1931 ;;;--------------------------------------------------------------------------
1932 ;;; Standard ML programming style.
1933
1934 (defun mdw-fontify-sml ()
1935
1936   ;; Make underscore an honorary letter.
1937   (modify-syntax-entry ?' "w")
1938
1939   ;; Set fill prefix.
1940   (mdw-standard-fill-prefix "\\([ \t]*(\*[ \t]*\\)")
1941
1942   ;; Now define fontification things.
1943   (make-local-variable 'font-lock-keywords)
1944   (let ((sml-keywords
1945          (mdw-regexps "abstype" "and" "andalso" "as"
1946                       "case"
1947                       "datatype" "do"
1948                       "else" "end" "eqtype" "exception"
1949                       "fn" "fun" "functor"
1950                       "handle"
1951                       "if" "in" "include" "infix" "infixr"
1952                       "let" "local"
1953                       "nonfix"
1954                       "of" "op" "open" "orelse"
1955                       "raise" "rec"
1956                       "sharing" "sig" "signature" "struct" "structure"
1957                       "then" "type"
1958                       "val"
1959                       "where" "while" "with" "withtype")))
1960
1961     (setq font-lock-keywords
1962           (list
1963
1964            ;; Set up the keywords defined above.
1965            (list (concat "\\<\\(" sml-keywords "\\)\\>")
1966                  '(0 font-lock-keyword-face))
1967
1968            ;; At least numbers are simpler than C.
1969            (list (concat "\\<\\(\\~\\|\\)"
1970                             "\\(0\\(\\([wW]\\|\\)[xX][0-9a-fA-F]+\\|"
1971                                    "[wW][0-9]+\\)\\|"
1972                                 "\\([0-9]+\\(\\.[0-9]+\\|\\)"
1973                                          "\\([eE]\\(\\~\\|\\)"
1974                                                 "[0-9]+\\|\\)\\)\\)")
1975                  '(0 mdw-number-face))
1976
1977            ;; And anything else is punctuation.
1978            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1979                  '(0 mdw-punct-face)))))
1980
1981   (mdw-post-config-mode-hack))
1982
1983 ;;;--------------------------------------------------------------------------
1984 ;;; Haskell configuration.
1985
1986 (defun mdw-fontify-haskell ()
1987
1988   ;; Fiddle with syntax table to get comments right.
1989   (modify-syntax-entry ?' "\"")
1990   (modify-syntax-entry ?- ". 123")
1991   (modify-syntax-entry ?{ ". 1b")
1992   (modify-syntax-entry ?} ". 4b")
1993   (modify-syntax-entry ?\n ">")
1994
1995   ;; Set fill prefix.
1996   (mdw-standard-fill-prefix "\\([ \t]*{?--?[ \t]*\\)")
1997
1998   ;; Fiddle with fontification.
1999   (make-local-variable 'font-lock-keywords)
2000   (let ((haskell-keywords
2001          (mdw-regexps "as" "case" "ccall" "class" "data" "default"
2002                       "deriving" "do" "else" "foreign" "hiding" "if"
2003                       "import" "in" "infix" "infixl" "infixr" "instance"
2004                       "let" "module" "newtype" "of" "qualified" "safe"
2005                       "stdcall" "then" "type" "unsafe" "where")))
2006
2007     (setq font-lock-keywords
2008           (list
2009            (list "--.*$"
2010                  '(0 font-lock-comment-face))
2011            (list (concat "\\<\\(" haskell-keywords "\\)\\>")
2012                  '(0 font-lock-keyword-face))
2013            (list (concat "\\<0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
2014                          "\\<[0-9][0-9_]*\\(\\.[0-9]*\\|\\)"
2015                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)")
2016                  '(0 mdw-number-face))
2017            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2018                  '(0 mdw-punct-face)))))
2019
2020   (mdw-post-config-mode-hack))
2021
2022 ;;;--------------------------------------------------------------------------
2023 ;;; Erlang configuration.
2024
2025 (setq erlang-electric-commands nil)
2026
2027 (defun mdw-fontify-erlang ()
2028
2029   ;; Set fill prefix.
2030   (mdw-standard-fill-prefix "\\([ \t]*{?%*[ \t]*\\)")
2031
2032   ;; Fiddle with fontification.
2033   (make-local-variable 'font-lock-keywords)
2034   (let ((erlang-keywords
2035          (mdw-regexps "after" "and" "andalso"
2036                       "band" "begin" "bnot" "bor" "bsl" "bsr" "bxor"
2037                       "case" "catch" "cond"
2038                       "div" "end" "fun" "if" "let" "not"
2039                       "of" "or" "orelse"
2040                       "query" "receive" "rem" "try" "when" "xor")))
2041
2042     (setq font-lock-keywords
2043           (list
2044            (list "%.*$"
2045                  '(0 font-lock-comment-face))
2046            (list (concat "\\<\\(" erlang-keywords "\\)\\>")
2047                  '(0 font-lock-keyword-face))
2048            (list (concat "^-\\sw+\\>")
2049                  '(0 font-lock-keyword-face))
2050            (list "\\<[0-9]+\\(\\|#[0-9a-zA-Z]+\\|[eE][+-]?[0-9]+\\)\\>"
2051                  '(0 mdw-number-face))
2052            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2053                  '(0 mdw-punct-face)))))
2054
2055   (mdw-post-config-mode-hack))
2056
2057 ;;;--------------------------------------------------------------------------
2058 ;;; Texinfo configuration.
2059
2060 (defun mdw-fontify-texinfo ()
2061
2062   ;; Set fill prefix.
2063   (mdw-standard-fill-prefix "\\([ \t]*@c[ \t]+\\)")
2064
2065   ;; Real fontification things.
2066   (make-local-variable 'font-lock-keywords)
2067   (setq font-lock-keywords
2068         (list
2069
2070          ;; Environment names are keywords.
2071          (list "@\\(end\\)  *\\([a-zA-Z]*\\)?"
2072                '(2 font-lock-keyword-face))
2073
2074          ;; Unmark escaped magic characters.
2075          (list "\\(@\\)\\([@{}]\\)"
2076                '(1 font-lock-keyword-face)
2077                '(2 font-lock-variable-name-face))
2078
2079          ;; Make sure we get comments properly.
2080          (list "@c\\(\\|omment\\)\\( .*\\)?$"
2081                '(0 font-lock-comment-face))
2082
2083          ;; Command names are keywords.
2084          (list "@\\([^a-zA-Z@]\\|[a-zA-Z@]*\\)"
2085                '(0 font-lock-keyword-face))
2086
2087          ;; Fontify TeX special characters as punctuation.
2088          (list "[{}]+"
2089                '(0 mdw-punct-face))))
2090
2091   (mdw-post-config-mode-hack))
2092
2093 ;;;--------------------------------------------------------------------------
2094 ;;; TeX and LaTeX configuration.
2095
2096 (defun mdw-fontify-tex ()
2097   (setq ispell-parser 'tex)
2098   (turn-on-reftex)
2099
2100   ;; Don't make maths into a string.
2101   (modify-syntax-entry ?$ ".")
2102   (modify-syntax-entry ?$ "." font-lock-syntax-table)
2103   (local-set-key [?$] 'self-insert-command)
2104
2105   ;; Set fill prefix.
2106   (mdw-standard-fill-prefix "\\([ \t]*%+[ \t]*\\)")
2107
2108   ;; Real fontification things.
2109   (make-local-variable 'font-lock-keywords)
2110   (setq font-lock-keywords
2111         (list
2112
2113          ;; Environment names are keywords.
2114          (list (concat "\\\\\\(begin\\|end\\|newenvironment\\)"
2115                        "{\\([^}\n]*\\)}")
2116                '(2 font-lock-keyword-face))
2117
2118          ;; Suspended environment names are keywords too.
2119          (list (concat "\\\\\\(suspend\\|resume\\)\\(\\[[^]]*\\]\\)?"
2120                        "{\\([^}\n]*\\)}")
2121                '(3 font-lock-keyword-face))
2122
2123          ;; Command names are keywords.
2124          (list "\\\\\\([^a-zA-Z@]\\|[a-zA-Z@]*\\)"
2125                '(0 font-lock-keyword-face))
2126
2127          ;; Handle @/.../ for italics.
2128          ;; (list "\\(@/\\)\\([^/]*\\)\\(/\\)"
2129          ;;       '(1 font-lock-keyword-face)
2130          ;;       '(3 font-lock-keyword-face))
2131
2132          ;; Handle @*...* for boldness.
2133          ;; (list "\\(@\\*\\)\\([^*]*\\)\\(\\*\\)"
2134          ;;       '(1 font-lock-keyword-face)
2135          ;;       '(3 font-lock-keyword-face))
2136
2137          ;; Handle @`...' for literal syntax things.
2138          ;; (list "\\(@`\\)\\([^']*\\)\\('\\)"
2139          ;;       '(1 font-lock-keyword-face)
2140          ;;       '(3 font-lock-keyword-face))
2141
2142          ;; Handle @<...> for nonterminals.
2143          ;; (list "\\(@<\\)\\([^>]*\\)\\(>\\)"
2144          ;;       '(1 font-lock-keyword-face)
2145          ;;       '(3 font-lock-keyword-face))
2146
2147          ;; Handle other @-commands.
2148          ;; (list "@\\([^a-zA-Z]\\|[a-zA-Z]*\\)"
2149          ;;       '(0 font-lock-keyword-face))
2150
2151          ;; Make sure we get comments properly.
2152          (list "%.*"
2153                '(0 font-lock-comment-face))
2154
2155          ;; Fontify TeX special characters as punctuation.
2156          (list "[$^_{}#&]"
2157                '(0 mdw-punct-face))))
2158
2159   (mdw-post-config-mode-hack))
2160
2161 ;;;--------------------------------------------------------------------------
2162 ;;; SGML hacking.
2163
2164 (defun mdw-sgml-mode ()
2165   (interactive)
2166   (sgml-mode)
2167   (mdw-standard-fill-prefix "")
2168   (make-local-variable 'sgml-delimiters)
2169   (setq sgml-delimiters
2170         '("AND" "&" "COM" "--" "CRO" "&#" "DSC" "]" "DSO" "[" "DTGC" "]"
2171           "DTGO" "[" "ERO" "&" "ETAGO" ":e" "GRPC" ")" "GRPO" "(" "LIT" "\""
2172           "LITA" "'" "MDC" ">" "MDO" "<!" "MINUS" "-" "MSC" "]]" "NESTC" "{"
2173           "NET" "}" "OPT" "?" "OR" "|" "PERO" "%" "PIC" ">" "PIO" "<?"
2174           "PLUS" "+" "REFC" "." "REP" "*" "RNI" "#" "SEQ" "," "STAGO" ":"
2175           "TAGC" "." "VI" "=" "MS-START" "<![" "MS-END" "]]>"
2176           "XML-ECOM" "-->" "XML-PIC" "?>" "XML-SCOM" "<!--" "XML-TAGCE" "/>"
2177           "NULL" ""))
2178   (setq major-mode 'mdw-sgml-mode)
2179   (setq mode-name "[mdw] SGML")
2180   (run-hooks 'mdw-sgml-mode-hook))
2181
2182 ;;;--------------------------------------------------------------------------
2183 ;;; Configuration files.
2184
2185 (defvar mdw-conf-quote-normal nil
2186   "*Control syntax category of quote characters `\"' and `''.
2187 If this is `t', consider quote characters to be normal
2188 punctuation, as for `conf-quote-normal'.  If this is `nil' then
2189 leave quote characters as quotes.  If this is a list, then
2190 consider the quote characters in the list to be normal
2191 punctuation.  If this is a single quote character, then consider
2192 that character only to be normal punctuation.")
2193 (defun mdw-conf-quote-normal-acceptable-value-p (value)
2194   "Is the VALUE is an acceptable value for `mdw-conf-quote-normal'?"
2195   (or (booleanp value)
2196       (every (lambda (v) (memq v '(?\" ?')))
2197              (if (listp value) value (list value)))))
2198 (put 'mdw-conf-quote-normal 'safe-local-variable '
2199      mdw-conf-quote-normal-acceptable-value-p)
2200
2201 (defun mdw-fix-up-quote ()
2202   "Apply the setting of `mdw-conf-quote-normal'."
2203   (let ((flag mdw-conf-quote-normal))
2204     (cond ((eq flag t)
2205            (conf-quote-normal t))
2206           ((not flag)
2207            nil)
2208           (t
2209            (let ((table (copy-syntax-table (syntax-table))))
2210              (mapc (lambda (ch) (modify-syntax-entry ch "." table))
2211                    (if (listp flag) flag (list flag)))
2212              (set-syntax-table table)
2213              (and font-lock-mode (font-lock-fontify-buffer)))))))
2214 (defun mdw-fix-up-quote-hack ()
2215   "Unpleasant hack to call `mdw-fix-up-quote' at the right time.
2216 Annoyingly, `hack-local-variables' is done after `set-auto-mode'
2217 so we wouldn't see a local-variable setting of
2218 `mdw-conf-quote-normal' in `conf-mode-hook'.  Instead, wire
2219 ourselves onto `hack-local-variables-hook' here, and check the
2220 setting once it's actually been made."
2221   (add-hook 'hack-local-variables-hook 'mdw-fix-up-quote t t))
2222 (add-hook 'conf-mode-hook 'mdw-fix-up-quote-hack t)
2223
2224 ;;;--------------------------------------------------------------------------
2225 ;;; Shell scripts.
2226
2227 (defun mdw-setup-sh-script-mode ()
2228
2229   ;; Fetch the shell interpreter's name.
2230   (let ((shell-name sh-shell-file))
2231
2232     ;; Try reading the hash-bang line.
2233     (save-excursion
2234       (goto-char (point-min))
2235       (if (looking-at "#![ \t]*\\([^ \t\n]*\\)")
2236           (setq shell-name (match-string 1))))
2237
2238     ;; Now try to set the shell.
2239     ;;
2240     ;; Don't let `sh-set-shell' bugger up my script.
2241     (let ((executable-set-magic #'(lambda (s &rest r) s)))
2242       (sh-set-shell shell-name)))
2243
2244   ;; Now enable my keys and the fontification.
2245   (mdw-misc-mode-config)
2246
2247   ;; Set the indentation level correctly.
2248   (setq sh-indentation 2)
2249   (setq sh-basic-offset 2))
2250
2251 (setq sh-shell-file "/bin/sh")
2252
2253 ;; Awful hacking to override the shell detection for particular scripts.
2254 (defmacro define-custom-shell-mode (name shell)
2255   `(defun ,name ()
2256      (interactive)
2257      (set (make-local-variable 'sh-shell-file) ,shell)
2258      (sh-mode)))
2259 (define-custom-shell-mode bash-mode "/bin/bash")
2260 (define-custom-shell-mode rc-mode "/usr/bin/rc")
2261 (put 'sh-shell-file 'permanent-local t)
2262
2263 ;; Hack the rc syntax table.  Backquotes aren't paired in rc.
2264 (eval-after-load "sh-script"
2265   '(or (assq 'rc sh-mode-syntax-table-input)
2266        (let ((frag '(nil
2267                      ?# "<"
2268                      ?\n ">#"
2269                      ?\" "\"\""
2270                      ?\' "\"\'"
2271                      ?$ "'"
2272                      ?\` "."
2273                      ?! "_"
2274                      ?% "_"
2275                      ?. "_"
2276                      ?^ "_"
2277                      ?~ "_"
2278                      ?, "_"
2279                      ?= "."
2280                      ?< "."
2281                      ?> "."))
2282              (assoc (assq 'rc sh-mode-syntax-table-input)))
2283          (if assoc
2284              (rplacd assoc frag)
2285            (setq sh-mode-syntax-table-input
2286                  (cons (cons 'rc frag)
2287                        sh-mode-syntax-table-input))))))
2288
2289 ;;;--------------------------------------------------------------------------
2290 ;;; Emacs shell mode.
2291
2292 (defun mdw-eshell-prompt ()
2293   (let ((left "[") (right "]"))
2294     (when (= (user-uid) 0)
2295       (setq left "«" right "»"))
2296     (concat left
2297             (save-match-data
2298               (replace-regexp-in-string "\\..*$" "" (system-name)))
2299             " "
2300             (let* ((pwd (eshell/pwd)) (npwd (length pwd))
2301                    (home (expand-file-name "~")) (nhome (length home)))
2302               (if (and (>= npwd nhome)
2303                        (or (= nhome npwd)
2304                            (= (elt pwd nhome) ?/))
2305                        (string= (substring pwd 0 nhome) home))
2306                   (concat "~" (substring pwd (length home)))
2307                 pwd))
2308             right)))
2309 (setq eshell-prompt-function 'mdw-eshell-prompt)
2310 (setq eshell-prompt-regexp "^\\[[^]>]+\\(\\]\\|>>?\\)")
2311
2312 (defun eshell/e (file) (find-file file) nil)
2313 (defun eshell/ee (file) (find-file-other-window file) nil)
2314 (defun eshell/w3m (url) (w3m-goto-url url) nil)
2315
2316 (mdw-define-face eshell-prompt (t :weight bold))
2317 (mdw-define-face eshell-ls-archive (t :weight bold :foreground "red"))
2318 (mdw-define-face eshell-ls-backup (t :foreground "lightgrey" :slant italic))
2319 (mdw-define-face eshell-ls-product (t :foreground "lightgrey" :slant italic))
2320 (mdw-define-face eshell-ls-clutter (t :foreground "lightgrey" :slant italic))
2321 (mdw-define-face eshell-ls-executable (t :weight bold))
2322 (mdw-define-face eshell-ls-directory (t :foreground "cyan" :weight bold))
2323 (mdw-define-face eshell-ls-readonly (t nil))
2324 (mdw-define-face eshell-ls-symlink (t :foreground "cyan"))
2325
2326 ;;;--------------------------------------------------------------------------
2327 ;;; Messages-file mode.
2328
2329 (defun messages-mode-guts ()
2330   (setq messages-mode-syntax-table (make-syntax-table))
2331   (set-syntax-table messages-mode-syntax-table)
2332   (modify-syntax-entry ?0 "w" messages-mode-syntax-table)
2333   (modify-syntax-entry ?1 "w" messages-mode-syntax-table)
2334   (modify-syntax-entry ?2 "w" messages-mode-syntax-table)
2335   (modify-syntax-entry ?3 "w" messages-mode-syntax-table)
2336   (modify-syntax-entry ?4 "w" messages-mode-syntax-table)
2337   (modify-syntax-entry ?5 "w" messages-mode-syntax-table)
2338   (modify-syntax-entry ?6 "w" messages-mode-syntax-table)
2339   (modify-syntax-entry ?7 "w" messages-mode-syntax-table)
2340   (modify-syntax-entry ?8 "w" messages-mode-syntax-table)
2341   (modify-syntax-entry ?9 "w" messages-mode-syntax-table)
2342   (make-local-variable 'comment-start)
2343   (make-local-variable 'comment-end)
2344   (make-local-variable 'indent-line-function)
2345   (setq indent-line-function 'indent-relative)
2346   (mdw-standard-fill-prefix "\\([ \t]*\\(;\\|/?\\*\\)+[ \t]*\\)")
2347   (make-local-variable 'font-lock-defaults)
2348   (make-local-variable 'messages-mode-keywords)
2349   (let ((keywords
2350          (mdw-regexps "array" "bitmap" "callback" "docs[ \t]+enum"
2351                       "export" "enum" "fixed-octetstring" "flags"
2352                       "harmless" "map" "nested" "optional"
2353                       "optional-tagged" "package" "primitive"
2354                       "primitive-nullfree" "relaxed[ \t]+enum"
2355                       "set" "table" "tagged-optional"   "union"
2356                       "variadic" "vector" "version" "version-tag")))
2357     (setq messages-mode-keywords
2358           (list
2359            (list (concat "\\<\\(" keywords "\\)\\>:")
2360                  '(0 font-lock-keyword-face))
2361            '("\\([-a-zA-Z0-9]+:\\)" (0 font-lock-warning-face))
2362            '("\\(\\<[a-z][-_a-zA-Z0-9]*\\)"
2363              (0 font-lock-variable-name-face))
2364            '("\\<\\([0-9]+\\)\\>" (0 mdw-number-face))
2365            '("\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2366              (0 mdw-punct-face)))))
2367   (setq font-lock-defaults
2368         '(messages-mode-keywords nil nil nil nil))
2369   (run-hooks 'messages-file-hook))
2370
2371 (defun messages-mode ()
2372   (interactive)
2373   (fundamental-mode)
2374   (setq major-mode 'messages-mode)
2375   (setq mode-name "Messages")
2376   (messages-mode-guts)
2377   (modify-syntax-entry ?# "<" messages-mode-syntax-table)
2378   (modify-syntax-entry ?\n ">" messages-mode-syntax-table)
2379   (setq comment-start "# ")
2380   (setq comment-end "")
2381   (run-hooks 'messages-mode-hook))
2382
2383 (defun cpp-messages-mode ()
2384   (interactive)
2385   (fundamental-mode)
2386   (setq major-mode 'cpp-messages-mode)
2387   (setq mode-name "CPP Messages")
2388   (messages-mode-guts)
2389   (modify-syntax-entry ?* ". 23" messages-mode-syntax-table)
2390   (modify-syntax-entry ?/ ". 14" messages-mode-syntax-table)
2391   (setq comment-start "/* ")
2392   (setq comment-end " */")
2393   (let ((preprocessor-keywords
2394          (mdw-regexps "assert" "define" "elif" "else" "endif" "error"
2395                       "ident" "if" "ifdef" "ifndef" "import" "include"
2396                       "line" "pragma" "unassert" "undef" "warning")))
2397     (setq messages-mode-keywords
2398           (append (list (list (concat "^[ \t]*\\#[ \t]*"
2399                                       "\\(include\\|import\\)"
2400                                       "[ \t]*\\(<[^>]+\\(>\\|\\)\\)")
2401                               '(2 font-lock-string-face))
2402                         (list (concat "^\\([ \t]*#[ \t]*\\(\\("
2403                                       preprocessor-keywords
2404                                       "\\)\\>\\|[0-9]+\\|$\\)\\)")
2405                               '(1 font-lock-keyword-face)))
2406                   messages-mode-keywords)))
2407   (run-hooks 'cpp-messages-mode-hook))
2408
2409 (add-hook 'messages-mode-hook 'mdw-misc-mode-config t)
2410 (add-hook 'cpp-messages-mode-hook 'mdw-misc-mode-config t)
2411 ; (add-hook 'messages-file-hook 'mdw-fontify-messages t)
2412
2413 ;;;--------------------------------------------------------------------------
2414 ;;; Messages-file mode.
2415
2416 (defvar mallow-driver-substitution-face 'mallow-driver-substitution-face
2417   "Face to use for subsittution directives.")
2418 (make-face 'mallow-driver-substitution-face)
2419 (defvar mallow-driver-text-face 'mallow-driver-text-face
2420   "Face to use for body text.")
2421 (make-face 'mallow-driver-text-face)
2422
2423 (defun mallow-driver-mode ()
2424   (interactive)
2425   (fundamental-mode)
2426   (setq major-mode 'mallow-driver-mode)
2427   (setq mode-name "Mallow driver")
2428   (setq mallow-driver-mode-syntax-table (make-syntax-table))
2429   (set-syntax-table mallow-driver-mode-syntax-table)
2430   (make-local-variable 'comment-start)
2431   (make-local-variable 'comment-end)
2432   (make-local-variable 'indent-line-function)
2433   (setq indent-line-function 'indent-relative)
2434   (mdw-standard-fill-prefix "\\([ \t]*\\(;\\|/?\\*\\)+[ \t]*\\)")
2435   (make-local-variable 'font-lock-defaults)
2436   (make-local-variable 'mallow-driver-mode-keywords)
2437   (let ((keywords
2438          (mdw-regexps "each" "divert" "file" "if"
2439                       "perl" "set" "string" "type" "write")))
2440     (setq mallow-driver-mode-keywords
2441           (list
2442            (list (concat "^%\\s *\\(}\\|\\(" keywords "\\)\\>\\).*$")
2443                  '(0 font-lock-keyword-face))
2444            (list "^%\\s *\\(#.*\\|\\)$"
2445                  '(0 font-lock-comment-face))
2446            (list "^%"
2447                  '(0 font-lock-keyword-face))
2448            (list "^|?\\(.+\\)$" '(1 mallow-driver-text-face))
2449            (list "\\${[^}]*}"
2450                  '(0 mallow-driver-substitution-face t)))))
2451   (setq font-lock-defaults
2452         '(mallow-driver-mode-keywords nil nil nil nil))
2453   (modify-syntax-entry ?\" "_" mallow-driver-mode-syntax-table)
2454   (modify-syntax-entry ?\n ">" mallow-driver-mode-syntax-table)
2455   (setq comment-start "%# ")
2456   (setq comment-end "")
2457   (run-hooks 'mallow-driver-mode-hook))
2458
2459 (add-hook 'mallow-driver-hook 'mdw-misc-mode-config t)
2460
2461 ;;;--------------------------------------------------------------------------
2462 ;;; NFast debugs.
2463
2464 (defun nfast-debug-mode ()
2465   (interactive)
2466   (fundamental-mode)
2467   (setq major-mode 'nfast-debug-mode)
2468   (setq mode-name "NFast debug")
2469   (setq messages-mode-syntax-table (make-syntax-table))
2470   (set-syntax-table messages-mode-syntax-table)
2471   (make-local-variable 'font-lock-defaults)
2472   (make-local-variable 'nfast-debug-mode-keywords)
2473   (setq truncate-lines t)
2474   (setq nfast-debug-mode-keywords
2475         (list
2476          '("^\\(NFast_\\(Connect\\|Disconnect\\|Submit\\|Wait\\)\\)"
2477            (0 font-lock-keyword-face))
2478          (list (concat "^[ \t]+\\(\\("
2479                        "[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]"
2480                        "[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]"
2481                        "[ \t]+\\)*"
2482                        "[0-9a-fA-F]+\\)[ \t]*$")
2483            '(0 mdw-number-face))
2484          '("^[ \t]+\.status=[ \t]+\\<\\(OK\\)\\>"
2485            (1 font-lock-keyword-face))
2486          '("^[ \t]+\.status=[ \t]+\\<\\([a-zA-Z][0-9a-zA-Z]*\\)\\>"
2487            (1 font-lock-warning-face))
2488          '("^[ \t]+\.status[ \t]+\\<\\(zero\\)\\>"
2489            (1 nil))
2490          (list (concat "^[ \t]+\\.cmd=[ \t]+"
2491                        "\\<\\([a-zA-Z][0-9a-zA-Z]*\\)\\>")
2492            '(1 font-lock-keyword-face))
2493          '("-?\\<\\([0-9]+\\|0x[0-9a-fA-F]+\\)\\>" (0 mdw-number-face))
2494          '("^\\([ \t]+[a-z0-9.]+\\)" (0 font-lock-variable-name-face))
2495          '("\\<\\([a-z][a-z0-9.]+\\)\\>=" (1 font-lock-variable-name-face))
2496          '("\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)" (0 mdw-punct-face))))
2497   (setq font-lock-defaults
2498         '(nfast-debug-mode-keywords nil nil nil nil))
2499   (run-hooks 'nfast-debug-mode-hook))
2500
2501 ;;;--------------------------------------------------------------------------
2502 ;;; Other languages.
2503
2504 ;; Smalltalk.
2505
2506 (defun mdw-setup-smalltalk ()
2507   (and mdw-auto-indent
2508        (local-set-key "\C-m" 'smalltalk-newline-and-indent))
2509   (make-local-variable 'mdw-auto-indent)
2510   (setq mdw-auto-indent nil)
2511   (local-set-key "\C-i" 'smalltalk-reindent))
2512
2513 (defun mdw-fontify-smalltalk ()
2514   (make-local-variable 'font-lock-keywords)
2515   (setq font-lock-keywords
2516         (list
2517          (list "\\<[A-Z][a-zA-Z0-9]*\\>"
2518                '(0 font-lock-keyword-face))
2519          (list (concat "\\<0\\([xX][0-9a-fA-F_]+\\|[0-7_]+\\)\\|"
2520                        "[0-9][0-9_]*\\(\\.[0-9_]*\\|\\)"
2521                        "\\([eE]\\([-+]\\|\\)[0-9_]+\\|\\)")
2522                '(0 mdw-number-face))
2523          (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2524                '(0 mdw-punct-face))))
2525   (mdw-post-config-mode-hack))
2526
2527 ;; Lispy languages.
2528
2529 ;; Unpleasant bodge.
2530 (unless (boundp 'slime-repl-mode-map)
2531   (setq slime-repl-mode-map (make-sparse-keymap)))
2532
2533 (defun mdw-indent-newline-and-indent ()
2534   (interactive)
2535   (indent-for-tab-command)
2536   (newline-and-indent))
2537
2538 (eval-after-load "cl-indent"
2539   '(progn
2540      (mapc #'(lambda (pair)
2541                (put (car pair)
2542                     'common-lisp-indent-function
2543                     (cdr pair)))
2544       '((destructuring-bind . ((&whole 4 &rest 1) 4 &body))
2545         (multiple-value-bind . ((&whole 4 &rest 1) 4 &body))))))
2546
2547 (defun mdw-common-lisp-indent ()
2548   (make-local-variable 'lisp-indent-function)
2549   (setq lisp-indent-function 'common-lisp-indent-function))
2550
2551 (setq lisp-simple-loop-indentation 2
2552       lisp-loop-keyword-indentation 6
2553       lisp-loop-forms-indentation 6)
2554
2555 (defun mdw-fontify-lispy ()
2556
2557   ;; Set fill prefix.
2558   (mdw-standard-fill-prefix "\\([ \t]*;+[ \t]*\\)")
2559
2560   ;; Not much fontification needed.
2561   (make-local-variable 'font-lock-keywords)
2562   (setq font-lock-keywords
2563         (list
2564          (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2565                '(0 mdw-punct-face))))
2566
2567   (mdw-post-config-mode-hack))
2568
2569 (defun comint-send-and-indent ()
2570   (interactive)
2571   (comint-send-input)
2572   (and mdw-auto-indent
2573        (indent-for-tab-command)))
2574
2575 (defun mdw-setup-m4 ()
2576   (mdw-standard-fill-prefix "\\([ \t]*\\(?:#+\\|\\<dnl\\>\\)[ \t]*\\)"))
2577
2578 ;;;--------------------------------------------------------------------------
2579 ;;; Text mode.
2580
2581 (defun mdw-text-mode ()
2582   (setq fill-column 72)
2583   (flyspell-mode t)
2584   (mdw-standard-fill-prefix
2585    "\\([ \t]*\\([>#|:] ?\\)*[ \t]*\\)" 3)
2586   (auto-fill-mode 1))
2587
2588 ;;;--------------------------------------------------------------------------
2589 ;;; Outline and hide/show modes.
2590
2591 (defun mdw-outline-collapse-all ()
2592   "Completely collapse everything in the entire buffer."
2593   (interactive)
2594   (save-excursion
2595     (goto-char (point-min))
2596     (while (< (point) (point-max))
2597       (hide-subtree)
2598       (forward-line))))
2599
2600 (setq hs-hide-comments-when-hiding-all nil)
2601
2602 (defadvice hs-hide-all (after hide-first-comment activate)
2603   (save-excursion (hs-hide-initial-comment-block)))
2604
2605 ;;;--------------------------------------------------------------------------
2606 ;;; Shell mode.
2607
2608 (defun mdw-sh-mode-setup ()
2609   (local-set-key [?\C-a] 'comint-bol)
2610   (add-hook 'comint-output-filter-functions
2611             'comint-watch-for-password-prompt))
2612
2613 (defun mdw-term-mode-setup ()
2614   (setq term-prompt-regexp shell-prompt-pattern)
2615   (make-local-variable 'mouse-yank-at-point)
2616   (make-local-variable 'transient-mark-mode)
2617   (setq mouse-yank-at-point t)
2618   (auto-fill-mode -1)
2619   (setq tab-width 8))
2620
2621 (defun term-send-meta-right () (interactive) (term-send-raw-string "\e\e[C"))
2622 (defun term-send-meta-left  () (interactive) (term-send-raw-string "\e\e[D"))
2623 (defun term-send-ctrl-uscore () (interactive) (term-send-raw-string "\C-_"))
2624 (defun term-send-meta-meta-something ()
2625   (interactive)
2626   (term-send-raw-string "\e\e")
2627   (term-send-raw))
2628 (eval-after-load 'term
2629   '(progn
2630      (define-key term-raw-map [?\e ?\e] nil)
2631      (define-key term-raw-map [?\e ?\e t] 'term-send-meta-meta-something)
2632      (define-key term-raw-map [?\C-/] 'term-send-ctrl-uscore)
2633      (define-key term-raw-map [M-right] 'term-send-meta-right)
2634      (define-key term-raw-map [?\e ?\M-O ?C] 'term-send-meta-right)
2635      (define-key term-raw-map [M-left] 'term-send-meta-left)
2636      (define-key term-raw-map [?\e ?\M-O ?D] 'term-send-meta-left)))
2637
2638 (defadvice term-exec (before program-args-list compile activate)
2639   "If the PROGRAM argument is a list, interpret it as (PROGRAM . SWITCHES).
2640 This allows you to pass a list of arguments through `ansi-term'."
2641   (let ((program (ad-get-arg 2)))
2642     (if (listp program)
2643         (progn
2644           (ad-set-arg 2 (car program))
2645           (ad-set-arg 4 (cdr program))))))
2646
2647 (defun ssh (host)
2648   "Open a terminal containing an ssh session to the HOST."
2649   (interactive "sHost: ")
2650   (ansi-term (list "ssh" host) (format "ssh@%s" host)))
2651
2652 ;;;--------------------------------------------------------------------------
2653 ;;; Inferior Emacs Lisp.
2654
2655 (setq comint-prompt-read-only t)
2656
2657 (eval-after-load "comint"
2658   '(progn
2659      (define-key comint-mode-map "\C-w" 'comint-kill-region)
2660      (define-key comint-mode-map [C-S-backspace] 'comint-kill-whole-line)))
2661
2662 (eval-after-load "ielm"
2663   '(progn
2664      (define-key ielm-map "\C-w" 'comint-kill-region)
2665      (define-key ielm-map [C-S-backspace] 'comint-kill-whole-line)))
2666
2667 ;;;----- That's all, folks --------------------------------------------------
2668
2669 (provide 'dot-emacs)