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