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