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