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