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