chiark / gitweb /
el/dot-emacs.el: Tweak face settings for 256-colour terminals.
[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   (((min-colors 64)) :background "grey30")
1256   (((class color)) :background "blue")
1257   ((t) :inverse-video t))
1258 (mdw-define-face match
1259   (((class color)) :background "blue")
1260   (t :inverse-video t))
1261 (mdw-define-face mc/cursor-face
1262   (((class color)) :background "red")
1263   (t :inverse-video t))
1264 (mdw-define-face minibuffer-prompt
1265   (t :weight bold))
1266 (mdw-define-face mode-line
1267   (((class color)) :foreground "blue" :background "yellow"
1268                    :box (:line-width 1 :style released-button))
1269   (t :inverse-video t))
1270 (mdw-define-face mode-line-inactive
1271   (((class color)) :foreground "yellow" :background "blue"
1272                    :box (:line-width 1 :style released-button))
1273   (t :inverse-video t))
1274 (mdw-define-face nobreak-space
1275   (((type tty)))
1276   (t :inherit escape-glyph :underline t))
1277 (mdw-define-face scroll-bar
1278   (t :foreground "black" :background "lightgrey"))
1279 (mdw-define-face fringe
1280   (t :foreground "yellow"))
1281 (mdw-define-face show-paren-match
1282   (((class color)) :background "darkgreen")
1283   (t :underline t))
1284 (mdw-define-face show-paren-mismatch
1285   (((class color)) :background "red")
1286   (t :inverse-video t))
1287 (mdw-define-face highlight
1288   (((min-colors 64)) :background "DarkSeaGreen4")
1289   (((class color)) :background "cyan")
1290   (t :inverse-video t))
1291
1292 (mdw-define-face holiday-face
1293   (t :background "red"))
1294 (mdw-define-face calendar-today-face
1295   (t :foreground "yellow" :weight bold))
1296
1297 (mdw-define-face comint-highlight-prompt
1298   (t :weight bold))
1299 (mdw-define-face comint-highlight-input
1300   (t nil))
1301
1302 (mdw-define-face ido-subdir
1303   (t :foreground "cyan" :weight bold))
1304
1305 (mdw-define-face dired-directory
1306   (t :foreground "cyan" :weight bold))
1307 (mdw-define-face dired-symlink
1308   (t :foreground "cyan"))
1309 (mdw-define-face dired-perm-write
1310   (t nil))
1311
1312 (mdw-define-face trailing-whitespace
1313   (((class color)) :background "red")
1314   (t :inverse-video t))
1315 (mdw-define-face whitespace-line
1316   (((class color)) :background "darkred")
1317   (t :inverse-video t))
1318 (mdw-define-face mdw-punct-face
1319   (((min-colors 64)) :foreground "burlywood2")
1320   (((class color)) :foreground "yellow"))
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   (((min-colors 64)) :slant italic :foreground "SeaGreen1")
1340   (((class color)) :foreground "green")
1341   (t :weight bold))
1342 (mdw-define-face font-lock-comment-face
1343   (((min-colors 64)) :slant italic :foreground "SeaGreen1")
1344   (((class color)) :foreground "green")
1345   (t :weight bold))
1346 (mdw-define-face font-lock-string-face
1347   (((min-colors 64)) :foreground "SkyBlue1")
1348   (((class color)) :foreground "cyan")
1349   (t :weight bold))
1350
1351 (mdw-define-face message-separator
1352   (t :background "red" :foreground "white" :weight bold))
1353 (mdw-define-face message-cited-text
1354   (default :slant italic)
1355   (((min-colors 64)) :foreground "SkyBlue1")
1356   (((class color)) :foreground "cyan"))
1357 (mdw-define-face message-header-cc
1358   (default :slant italic)
1359   (((min-colors 64)) :foreground "SeaGreen1")
1360   (((class color)) :foreground "green"))
1361 (mdw-define-face message-header-newsgroups
1362   (default :slant italic)
1363   (((min-colors 64)) :foreground "SeaGreen1")
1364   (((class color)) :foreground "green"))
1365 (mdw-define-face message-header-subject
1366   (((min-colors 64)) :foreground "SeaGreen1")
1367   (((class color)) :foreground "green"))
1368 (mdw-define-face message-header-to
1369   (((min-colors 64)) :foreground "SeaGreen1")
1370   (((class color)) :foreground "green"))
1371 (mdw-define-face message-header-xheader
1372   (default :slant italic)
1373   (((min-colors 64)) :foreground "SeaGreen1")
1374   (((class color)) :foreground "green"))
1375 (mdw-define-face message-header-other
1376   (default :slant italic)
1377   (((min-colors 64)) :foreground "SeaGreen1")
1378   (((class color)) :foreground "green"))
1379 (mdw-define-face message-header-name
1380   (default :weight bold)
1381   (((min-colors 64)) :foreground "SeaGreen1")
1382   (((class color)) :foreground "green"))
1383
1384 (mdw-define-face which-func
1385   (t nil))
1386
1387 (mdw-define-face gnus-header-name
1388   (default :weight bold)
1389   (((min-colors 64)) :foreground "SeaGreen1")
1390   (((class color)) :foreground "green"))
1391 (mdw-define-face gnus-header-subject
1392   (((min-colors 64)) :foreground "SeaGreen1")
1393   (((class color)) :foreground "green"))
1394 (mdw-define-face gnus-header-from
1395   (((min-colors 64)) :foreground "SeaGreen1")
1396   (((class color)) :foreground "green"))
1397 (mdw-define-face gnus-header-to
1398   (((min-colors 64)) :foreground "SeaGreen1")
1399   (((class color)) :foreground "green"))
1400 (mdw-define-face gnus-header-content
1401   (default :slant italic)
1402   (((min-colors 64)) :foreground "SeaGreen1")
1403   (((class color)) :foreground "green"))
1404
1405 (mdw-define-face gnus-cite-1
1406   (((min-colors 64)) :foreground "SkyBlue1")
1407   (((class color)) :foreground "cyan"))
1408 (mdw-define-face gnus-cite-2
1409   (((min-colors 64)) :foreground "RoyalBlue2")
1410   (((class color)) :foreground "blue"))
1411 (mdw-define-face gnus-cite-3
1412   (((min-colors 64)) :foreground "MediumOrchid")
1413   (((class color)) :foreground "magenta"))
1414 (mdw-define-face gnus-cite-4
1415   (((min-colors 64)) :foreground "firebrick2")
1416   (((class color)) :foreground "red"))
1417 (mdw-define-face gnus-cite-5
1418   (((min-colors 64)) :foreground "burlywood2")
1419   (((class color)) :foreground "yellow"))
1420 (mdw-define-face gnus-cite-6
1421   (((min-colors 64)) :foreground "SeaGreen1")
1422   (((class color)) :foreground "green"))
1423 (mdw-define-face gnus-cite-7
1424   (((min-colors 64)) :foreground "SlateBlue1")
1425   (((class color)) :foreground "cyan"))
1426 (mdw-define-face gnus-cite-8
1427   (((min-colors 64)) :foreground "RoyalBlue2")
1428   (((class color)) :foreground "blue"))
1429 (mdw-define-face gnus-cite-9
1430   (((min-colors 64)) :foreground "purple2")
1431   (((class color)) :foreground "magenta"))
1432 (mdw-define-face gnus-cite-10
1433   (((min-colors 64)) :foreground "DarkOrange2")
1434   (((class color)) :foreground "red"))
1435 (mdw-define-face gnus-cite-11
1436   (t :foreground "grey"))
1437
1438 (mdw-define-face diff-header
1439   (t nil))
1440 (mdw-define-face diff-index
1441   (t :weight bold))
1442 (mdw-define-face diff-file-header
1443   (t :weight bold))
1444 (mdw-define-face diff-hunk-header
1445   (((min-colors 64)) :foreground "SkyBlue1")
1446   (((class color)) :foreground "cyan"))
1447 (mdw-define-face diff-function
1448   (default :weight bold)
1449   (((min-colors 64)) :foreground "SkyBlue1")
1450   (((class color)) :foreground "cyan"))
1451 (mdw-define-face diff-header
1452   (((min-colors 64)) :background "grey10"))
1453 (mdw-define-face diff-added
1454   (((class color)) :foreground "green"))
1455 (mdw-define-face diff-removed
1456   (((class color)) :foreground "red"))
1457 (mdw-define-face diff-context
1458   (t nil))
1459 (mdw-define-face diff-refine-change
1460   (((min-colors 64)) :background "RoyalBlue4")
1461   (t :underline t))
1462 (mdw-define-face diff-refine-removed
1463   (((min-colors 64)) :background "#500")
1464   (t :underline t))
1465 (mdw-define-face diff-refine-added
1466   (((min-colors 64)) :background "#050")
1467   (t :underline t))
1468
1469 (setq ediff-force-faces t)
1470 (mdw-define-face ediff-current-diff-A
1471   (((min-colors 64)) :background "darkred")
1472   (((class color)) :background "red")
1473   (t :inverse-video t))
1474 (mdw-define-face ediff-fine-diff-A
1475   (((min-colors 64)) :background "red3")
1476   (((class color)) :inverse-video t)
1477   (t :inverse-video nil))
1478 (mdw-define-face ediff-even-diff-A
1479   (((min-colors 64)) :background "#300"))
1480 (mdw-define-face ediff-odd-diff-A
1481   (((min-colors 64)) :background "#300"))
1482 (mdw-define-face ediff-current-diff-B
1483   (((min-colors 64)) :background "darkgreen")
1484   (((class color)) :background "magenta")
1485   (t :inverse-video t))
1486 (mdw-define-face ediff-fine-diff-B
1487   (((min-colors 64)) :background "green4")
1488   (((class color)) :inverse-video t)
1489   (t :inverse-video nil))
1490 (mdw-define-face ediff-even-diff-B
1491   (((min-colors 64)) :background "#020"))
1492 (mdw-define-face ediff-odd-diff-B
1493   (((min-colors 64)) :background "#020"))
1494 (mdw-define-face ediff-current-diff-C
1495   (((min-colors 64)) :background "darkblue")
1496   (((class color)) :background "blue")
1497   (t :inverse-video t))
1498 (mdw-define-face ediff-fine-diff-C
1499   (((min-colors 64)) :background "blue1")
1500   (((class color)) :inverse-video t)
1501   (t :inverse-video nil))
1502 (mdw-define-face ediff-even-diff-C
1503   (((min-colors 64)) :background "#004"))
1504 (mdw-define-face ediff-odd-diff-C
1505   (((min-colors 64)) :background "#004"))
1506 (mdw-define-face ediff-current-diff-Ancestor
1507   (((min-colors 64)) :background "#630")
1508   (((class color)) :background "blue")
1509   (t :inverse-video t))
1510 (mdw-define-face ediff-even-diff-Ancestor
1511   (((min-colors 64)) :background "#320"))
1512 (mdw-define-face ediff-odd-diff-Ancestor
1513   (((min-colors 64)) :background "#320"))
1514
1515 (mdw-define-face magit-hash
1516   (((min-colors 64)) :foreground "grey40")
1517   (((class color)) :foreground "blue"))
1518 (mdw-define-face magit-diff-hunk-heading
1519   (((min-colors 64)) :foreground "grey70" :background "grey25")
1520   (((class color)) :foreground "yellow"))
1521 (mdw-define-face magit-diff-hunk-heading-highlight
1522   (((min-colors 64)) :foreground "grey70" :background "grey35")
1523   (((class color)) :foreground "yellow" :background "blue"))
1524 (mdw-define-face magit-diff-added
1525   (((min-colors 64)) :foreground "#ddffdd" :background "#335533")
1526   (((class color)) :foreground "green"))
1527 (mdw-define-face magit-diff-added-highlight
1528   (((min-colors 64)) :foreground "#cceecc" :background "#336633")
1529   (((class color)) :foreground "green" :background "blue"))
1530 (mdw-define-face magit-diff-removed
1531   (((min-colors 64)) :foreground "#ffdddd" :background "#553333")
1532   (((class color)) :foreground "red"))
1533 (mdw-define-face magit-diff-removed-highlight
1534   (((min-colors 64)) :foreground "#eecccc" :background "#663333")
1535   (((class color)) :foreground "red" :background "blue"))
1536
1537 (mdw-define-face dylan-header-background
1538   (((min-colors 64)) :background "NavyBlue")
1539   (((class color)) :background "blue"))
1540
1541 (mdw-define-face erc-input-face
1542   (t :foreground "red"))
1543
1544 (mdw-define-face woman-bold
1545   (t :weight bold))
1546 (mdw-define-face woman-italic
1547   (t :slant italic))
1548
1549 (eval-after-load "rst"
1550   '(progn
1551      (mdw-define-face rst-level-1-face
1552        (t :foreground "SkyBlue1" :weight bold))
1553      (mdw-define-face rst-level-2-face
1554        (t :foreground "SeaGreen1" :weight bold))
1555      (mdw-define-face rst-level-3-face
1556        (t :weight bold))
1557      (mdw-define-face rst-level-4-face
1558        (t :slant italic))
1559      (mdw-define-face rst-level-5-face
1560        (t :underline t))
1561      (mdw-define-face rst-level-6-face
1562        ())))
1563
1564 (mdw-define-face p4-depot-added-face
1565   (t :foreground "green"))
1566 (mdw-define-face p4-depot-branch-op-face
1567   (t :foreground "yellow"))
1568 (mdw-define-face p4-depot-deleted-face
1569   (t :foreground "red"))
1570 (mdw-define-face p4-depot-unmapped-face
1571   (t :foreground "SkyBlue1"))
1572 (mdw-define-face p4-diff-change-face
1573   (t :foreground "yellow"))
1574 (mdw-define-face p4-diff-del-face
1575   (t :foreground "red"))
1576 (mdw-define-face p4-diff-file-face
1577   (t :foreground "SkyBlue1"))
1578 (mdw-define-face p4-diff-head-face
1579   (t :background "grey10"))
1580 (mdw-define-face p4-diff-ins-face
1581   (t :foreground "green"))
1582
1583 (mdw-define-face w3m-anchor-face
1584   (t :foreground "SkyBlue1" :underline t))
1585 (mdw-define-face w3m-arrived-anchor-face
1586   (t :foreground "SkyBlue1" :underline t))
1587
1588 (mdw-define-face whizzy-slice-face
1589   (t :background "grey10"))
1590 (mdw-define-face whizzy-error-face
1591   (t :background "darkred"))
1592
1593 ;; Ellipses used to indicate hidden text (and similar).
1594 (mdw-define-face mdw-ellipsis-face
1595   (((type tty)) :foreground "blue") (t :foreground "grey60"))
1596 (let ((dollar (make-glyph-code ?$ 'mdw-ellipsis-face))
1597       (backslash (make-glyph-code ?\\ 'mdw-ellipsis-face))
1598       (dot (make-glyph-code ?. 'mdw-ellipsis-face))
1599       (bar (make-glyph-code ?| mdw-ellipsis-face)))
1600   (set-display-table-slot standard-display-table 0 dollar)
1601   (set-display-table-slot standard-display-table 1 backslash)
1602   (set-display-table-slot standard-display-table 4
1603                           (vector dot dot dot))
1604   (set-display-table-slot standard-display-table 5 bar))
1605
1606 ;;;--------------------------------------------------------------------------
1607 ;;; C programming configuration.
1608
1609 ;; Make C indentation nice.
1610
1611 (defun mdw-c-lineup-arglist (langelem)
1612   "Hack for DWIMmery in c-lineup-arglist."
1613   (if (save-excursion
1614         (c-block-in-arglist-dwim (c-langelem-2nd-pos c-syntactic-element)))
1615       0
1616     (c-lineup-arglist langelem)))
1617
1618 (defun mdw-c-indent-extern-mumble (langelem)
1619   "Indent `extern \"...\" {' lines."
1620   (save-excursion
1621     (back-to-indentation)
1622     (if (looking-at
1623          "\\s-*\\<extern\\>\\s-*\"\\([^\\\\\"]+\\|\\.\\)*\"\\s-*{")
1624         c-basic-offset
1625       nil)))
1626
1627 (defun mdw-c-indent-arglist-nested (langelem)
1628   "Indent continued argument lists.
1629 If we've nested more than one argument list, then only introduce a single
1630 indentation anyway."
1631   (let ((context c-syntactic-context)
1632         (pos (c-langelem-2nd-pos c-syntactic-element))
1633         (should-indent-p t))
1634     (while (and context
1635                 (eq (caar context) 'arglist-cont-nonempty))
1636       (when (and (= (caddr (pop context)) pos)
1637                  context
1638                  (memq (caar context) '(arglist-intro
1639                                         arglist-cont-nonempty)))
1640         (setq should-indent-p nil)))
1641     (if should-indent-p '+ 0)))
1642
1643 (defvar mdw-define-c-styles-hook nil
1644   "Hook run when `cc-mode' starts up to define styles.")
1645
1646 (defmacro mdw-define-c-style (name &rest assocs)
1647   "Define a C style, called NAME (a symbol), setting ASSOCs.
1648 A function, named `mdw-define-c-style/NAME', is defined to actually install
1649 the style using `c-add-style', and added to the hook
1650 `mdw-define-c-styles-hook'.  If CC Mode is already loaded, then the style is
1651 set."
1652   (declare (indent defun))
1653   (let* ((name-string (symbol-name name))
1654          (func (intern (concat "mdw-define-c-style/" name-string))))
1655     `(progn
1656        (defun ,func () (c-add-style ,name-string ',assocs))
1657        (and (featurep 'cc-mode) (,func))
1658        (add-hook 'mdw-define-c-styles-hook ',func))))
1659
1660 (eval-after-load "cc-mode"
1661   '(run-hooks 'mdw-define-c-styles-hook))
1662
1663 (mdw-define-c-style mdw-trustonic-c
1664   (c-basic-offset . 4)
1665   (comment-column . 0)
1666   (c-indent-comment-alist (anchored-comment . (column . 0))
1667                           (end-block . (space . 1))
1668                           (cpp-end-block . (space . 1))
1669                           (other . (space . 1)))
1670   (c-class-key . "class")
1671   (c-backslash-column . 0)
1672   (c-auto-align-backslashes . nil)
1673   (c-label-minimum-indentation . 0)
1674   (c-offsets-alist (substatement-open . (add 0 c-indent-one-line-block))
1675                    (defun-open . (add 0 c-indent-one-line-block))
1676                    (arglist-cont-nonempty . mdw-c-indent-arglist-nested)
1677                    (topmost-intro . mdw-c-indent-extern-mumble)
1678                    (cpp-define-intro . 0)
1679                    (knr-argdecl . 0)
1680                    (inextern-lang . [0])
1681                    (label . 0)
1682                    (case-label . +)
1683                    (access-label . -2)
1684                    (inclass . +)
1685                    (inline-open . ++)
1686                    (statement-cont . +)
1687                    (statement-case-intro . +)))
1688
1689 (mdw-define-c-style mdw-c
1690   (c-basic-offset . 2)
1691   (comment-column . 40)
1692   (c-class-key . "class")
1693   (c-backslash-column . 72)
1694   (c-label-minimum-indentation . 0)
1695   (c-offsets-alist (substatement-open . (add 0 c-indent-one-line-block))
1696                    (defun-open . (add 0 c-indent-one-line-block))
1697                    (arglist-cont-nonempty . mdw-c-lineup-arglist)
1698                    (topmost-intro . mdw-c-indent-extern-mumble)
1699                    (cpp-define-intro . 0)
1700                    (knr-argdecl . 0)
1701                    (inextern-lang . [0])
1702                    (label . 0)
1703                    (case-label . +)
1704                    (access-label . -)
1705                    (inclass . +)
1706                    (inline-open . ++)
1707                    (statement-cont . +)
1708                    (statement-case-intro . +)))
1709
1710 (defun mdw-set-default-c-style (modes style)
1711   "Update the default CC Mode style for MODES to be STYLE.
1712
1713 MODES may be a list of major mode names or a singleton.  STYLE is a style
1714 name, as a symbol."
1715   (let ((modes (if (listp modes) modes (list modes)))
1716         (style (symbol-name style)))
1717     (setq c-default-style
1718           (append (mapcar (lambda (mode)
1719                             (cons mode style))
1720                           modes)
1721                   (remove-if (lambda (assoc)
1722                                (memq (car assoc) modes))
1723                              (if (listp c-default-style)
1724                                  c-default-style
1725                                (list (cons 'other c-default-style))))))))
1726 (setq c-default-style "mdw-c")
1727
1728 (mdw-set-default-c-style '(c-mode c++-mode) 'mdw-c)
1729
1730 (defvar mdw-c-comment-fill-prefix
1731   `((,(concat "\\([ \t]*/?\\)"
1732               "\\(\*\\|//]\\)"
1733               "\\([ \t]*\\)"
1734               "\\([A-Za-z]+:[ \t]*\\)?"
1735               mdw-hanging-indents)
1736      (pad . 1) (match . 2) (pad . 3) (pad . 4) (pad . 5)))
1737   "Fill prefix matching C comments (both kinds).")
1738
1739 (defun mdw-fontify-c-and-c++ ()
1740
1741   ;; Fiddle with some syntax codes.
1742   (modify-syntax-entry ?* ". 23")
1743   (modify-syntax-entry ?/ ". 124b")
1744   (modify-syntax-entry ?\n "> b")
1745
1746   ;; Other stuff.
1747   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
1748
1749   ;; Now define things to be fontified.
1750   (make-local-variable 'font-lock-keywords)
1751   (let ((c-keywords
1752          (mdw-regexps "alignas"          ;C11 macro, C++11
1753                       "alignof"          ;C++11
1754                       "and"              ;C++, C95 macro
1755                       "and_eq"           ;C++, C95 macro
1756                       "asm"              ;K&R, C++, GCC
1757                       "atomic"           ;C11 macro, C++11 template type
1758                       "auto"             ;K&R, C89
1759                       "bitand"           ;C++, C95 macro
1760                       "bitor"            ;C++, C95 macro
1761                       "bool"             ;C++, C99 macro
1762                       "break"            ;K&R, C89
1763                       "case"             ;K&R, C89
1764                       "catch"            ;C++
1765                       "char"             ;K&R, C89
1766                       "char16_t"         ;C++11, C11 library type
1767                       "char32_t"         ;C++11, C11 library type
1768                       "class"            ;C++
1769                       "complex"          ;C99 macro, C++ template type
1770                       "compl"            ;C++, C95 macro
1771                       "const"            ;C89
1772                       "constexpr"        ;C++11
1773                       "const_cast"       ;C++
1774                       "continue"         ;K&R, C89
1775                       "decltype"         ;C++11
1776                       "defined"          ;C89 preprocessor
1777                       "default"          ;K&R, C89
1778                       "delete"           ;C++
1779                       "do"               ;K&R, C89
1780                       "double"           ;K&R, C89
1781                       "dynamic_cast"     ;C++
1782                       "else"             ;K&R, C89
1783                       ;; "entry"         ;K&R -- never used
1784                       "enum"             ;C89
1785                       "explicit"         ;C++
1786                       "export"           ;C++
1787                       "extern"           ;K&R, C89
1788                       "float"            ;K&R, C89
1789                       "for"              ;K&R, C89
1790                       ;; "fortran"       ;K&R
1791                       "friend"           ;C++
1792                       "goto"             ;K&R, C89
1793                       "if"               ;K&R, C89
1794                       "imaginary"        ;C99 macro
1795                       "inline"           ;C++, C99, GCC
1796                       "int"              ;K&R, C89
1797                       "long"             ;K&R, C89
1798                       "mutable"          ;C++
1799                       "namespace"        ;C++
1800                       "new"              ;C++
1801                       "noexcept"         ;C++11
1802                       "noreturn"         ;C11 macro
1803                       "not"              ;C++, C95 macro
1804                       "not_eq"           ;C++, C95 macro
1805                       "nullptr"          ;C++11
1806                       "operator"         ;C++
1807                       "or"               ;C++, C95 macro
1808                       "or_eq"            ;C++, C95 macro
1809                       "private"          ;C++
1810                       "protected"        ;C++
1811                       "public"           ;C++
1812                       "register"         ;K&R, C89
1813                       "reinterpret_cast" ;C++
1814                       "restrict"         ;C99
1815                       "return"           ;K&R, C89
1816                       "short"            ;K&R, C89
1817                       "signed"           ;C89
1818                       "sizeof"           ;K&R, C89
1819                       "static"           ;K&R, C89
1820                       "static_assert"    ;C11 macro, C++11
1821                       "static_cast"      ;C++
1822                       "struct"           ;K&R, C89
1823                       "switch"           ;K&R, C89
1824                       "template"         ;C++
1825                       "throw"            ;C++
1826                       "try"              ;C++
1827                       "thread_local"     ;C11 macro, C++11
1828                       "typedef"          ;C89
1829                       "typeid"           ;C++
1830                       "typeof"           ;GCC
1831                       "typename"         ;C++
1832                       "union"            ;K&R, C89
1833                       "unsigned"         ;K&R, C89
1834                       "using"            ;C++
1835                       "virtual"          ;C++
1836                       "void"             ;C89
1837                       "volatile"         ;C89
1838                       "wchar_t"          ;C++, C89 library type
1839                       "while"            ;K&R, C89
1840                       "xor"              ;C++, C95 macro
1841                       "xor_eq"           ;C++, C95 macro
1842                       "_Alignas"         ;C11
1843                       "_Alignof"         ;C11
1844                       "_Atomic"          ;C11
1845                       "_Bool"            ;C99
1846                       "_Complex"         ;C99
1847                       "_Generic"         ;C11
1848                       "_Imaginary"       ;C99
1849                       "_Noreturn"        ;C11
1850                       "_Pragma"          ;C99 preprocessor
1851                       "_Static_assert"   ;C11
1852                       "_Thread_local"    ;C11
1853                       "__alignof__"      ;GCC
1854                       "__asm__"          ;GCC
1855                       "__attribute__"    ;GCC
1856                       "__complex__"      ;GCC
1857                       "__const__"        ;GCC
1858                       "__extension__"    ;GCC
1859                       "__imag__"         ;GCC
1860                       "__inline__"       ;GCC
1861                       "__label__"        ;GCC
1862                       "__real__"         ;GCC
1863                       "__signed__"       ;GCC
1864                       "__typeof__"       ;GCC
1865                       "__volatile__"     ;GCC
1866                       ))
1867         (c-constants
1868          (mdw-regexps "false"            ;C++, C99 macro
1869                       "this"             ;C++
1870                       "true"             ;C++, C99 macro
1871                       ))
1872         (preprocessor-keywords
1873          (mdw-regexps "assert" "define" "elif" "else" "endif" "error"
1874                       "ident" "if" "ifdef" "ifndef" "import" "include"
1875                       "line" "pragma" "unassert" "undef" "warning"))
1876         (objc-keywords
1877          (mdw-regexps "class" "defs" "encode" "end" "implementation"
1878                       "interface" "private" "protected" "protocol" "public"
1879                       "selector")))
1880
1881     (setq font-lock-keywords
1882           (list
1883
1884            ;; Fontify include files as strings.
1885            (list (concat "^[ \t]*\\#[ \t]*"
1886                          "\\(include\\|import\\)"
1887                          "[ \t]*\\(<[^>]+\\(>\\|\\)\\)")
1888                  '(2 font-lock-string-face))
1889
1890            ;; Preprocessor directives are `references'?.
1891            (list (concat "^\\([ \t]*#[ \t]*\\(\\("
1892                          preprocessor-keywords
1893                          "\\)\\>\\|[0-9]+\\|$\\)\\)")
1894                  '(1 font-lock-keyword-face))
1895
1896            ;; Handle the keywords defined above.
1897            (list (concat "@\\<\\(" objc-keywords "\\)\\>")
1898                  '(0 font-lock-keyword-face))
1899
1900            (list (concat "\\<\\(" c-keywords "\\)\\>")
1901                  '(0 font-lock-keyword-face))
1902
1903            (list (concat "\\<\\(" c-constants "\\)\\>")
1904                  '(0 font-lock-variable-name-face))
1905
1906            ;; Handle numbers too.
1907            ;;
1908            ;; This looks strange, I know.  It corresponds to the
1909            ;; preprocessor's idea of what a number looks like, rather than
1910            ;; anything sensible.
1911            (list (concat "\\(\\<[0-9]\\|\\.[0-9]\\)"
1912                          "\\([Ee][+-]\\|[0-9A-Za-z_.]\\)*")
1913                  '(0 mdw-number-face))
1914
1915            ;; And anything else is punctuation.
1916            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1917                  '(0 mdw-punct-face))))))
1918
1919 (define-derived-mode sod-mode c-mode "Sod"
1920   "Major mode for editing Sod code.")
1921 (push '("\\.sod$" . sod-mode) auto-mode-alist)
1922
1923 ;;;--------------------------------------------------------------------------
1924 ;;; AP calc mode.
1925
1926 (define-derived-mode apcalc-mode c-mode "AP Calc"
1927   "Major mode for editing Calc code.")
1928
1929 (defun mdw-fontify-apcalc ()
1930
1931   ;; Fiddle with some syntax codes.
1932   (modify-syntax-entry ?* ". 23")
1933   (modify-syntax-entry ?/ ". 14")
1934
1935   ;; Other stuff.
1936   (setq comment-start "/* ")
1937   (setq comment-end " */")
1938   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
1939
1940   ;; Now define things to be fontified.
1941   (make-local-variable 'font-lock-keywords)
1942   (let ((c-keywords
1943          (mdw-regexps "break" "case" "cd" "continue" "define" "default"
1944                       "do" "else" "exit" "for" "global" "goto" "help" "if"
1945                       "local" "mat" "obj" "print" "quit" "read" "return"
1946                       "show" "static" "switch" "while" "write")))
1947
1948     (setq font-lock-keywords
1949           (list
1950
1951            ;; Handle the keywords defined above.
1952            (list (concat "\\<\\(" c-keywords "\\)\\>")
1953                  '(0 font-lock-keyword-face))
1954
1955            ;; Handle numbers too.
1956            ;;
1957            ;; This looks strange, I know.  It corresponds to the
1958            ;; preprocessor's idea of what a number looks like, rather than
1959            ;; anything sensible.
1960            (list (concat "\\(\\<[0-9]\\|\\.[0-9]\\)"
1961                          "\\([Ee][+-]\\|[0-9A-Za-z_.]\\)*")
1962                  '(0 mdw-number-face))
1963
1964            ;; And anything else is punctuation.
1965            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
1966                  '(0 mdw-punct-face))))))
1967
1968 ;;;--------------------------------------------------------------------------
1969 ;;; Java programming configuration.
1970
1971 ;; Make indentation nice.
1972
1973 (mdw-define-c-style mdw-java
1974   (c-basic-offset . 2)
1975   (c-backslash-column . 72)
1976   (c-offsets-alist (substatement-open . 0)
1977                    (label . +)
1978                    (case-label . +)
1979                    (access-label . 0)
1980                    (inclass . +)
1981                    (statement-case-intro . +)))
1982 (mdw-set-default-c-style 'java-mode 'mdw-java)
1983
1984 ;; Declare Java fontification style.
1985
1986 (defun mdw-fontify-java ()
1987
1988   ;; Other stuff.
1989   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
1990
1991   ;; Now define things to be fontified.
1992   (make-local-variable 'font-lock-keywords)
1993   (let ((java-keywords
1994          (mdw-regexps "abstract" "boolean" "break" "byte" "case" "catch"
1995                       "char" "class" "const" "continue" "default" "do"
1996                       "double" "else" "extends" "final" "finally" "float"
1997                       "for" "goto" "if" "implements" "import" "instanceof"
1998                       "int" "interface" "long" "native" "new" "package"
1999                       "private" "protected" "public" "return" "short"
2000                       "static" "switch" "synchronized" "throw" "throws"
2001                       "transient" "try" "void" "volatile" "while"))
2002
2003         (java-constants
2004          (mdw-regexps "false" "null" "super" "this" "true")))
2005
2006     (setq font-lock-keywords
2007           (list
2008
2009            ;; Handle the keywords defined above.
2010            (list (concat "\\<\\(" java-keywords "\\)\\>")
2011                  '(0 font-lock-keyword-face))
2012
2013            ;; Handle the magic constants defined above.
2014            (list (concat "\\<\\(" java-constants "\\)\\>")
2015                  '(0 font-lock-variable-name-face))
2016
2017            ;; Handle numbers too.
2018            ;;
2019            ;; The following isn't quite right, but it's close enough.
2020            (list (concat "\\<\\("
2021                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
2022                          "[0-9]+\\(\\.[0-9]*\\|\\)"
2023                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)"
2024                          "[lLfFdD]?")
2025                  '(0 mdw-number-face))
2026
2027            ;; And anything else is punctuation.
2028            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2029                  '(0 mdw-punct-face))))))
2030
2031 ;;;--------------------------------------------------------------------------
2032 ;;; Javascript programming configuration.
2033
2034 (defun mdw-javascript-style ()
2035   (setq js-indent-level 2)
2036   (setq js-expr-indent-offset 0))
2037
2038 (defun mdw-fontify-javascript ()
2039
2040   ;; Other stuff.
2041   (mdw-javascript-style)
2042   (setq js-auto-indent-flag t)
2043
2044   ;; Now define things to be fontified.
2045   (make-local-variable 'font-lock-keywords)
2046   (let ((javascript-keywords
2047          (mdw-regexps "abstract" "boolean" "break" "byte" "case" "catch"
2048                       "char" "class" "const" "continue" "debugger" "default"
2049                       "delete" "do" "double" "else" "enum" "export" "extends"
2050                       "final" "finally" "float" "for" "function" "goto" "if"
2051                       "implements" "import" "in" "instanceof" "int"
2052                       "interface" "let" "long" "native" "new" "package"
2053                       "private" "protected" "public" "return" "short"
2054                       "static" "super" "switch" "synchronized" "throw"
2055                       "throws" "transient" "try" "typeof" "var" "void"
2056                       "volatile" "while" "with" "yield"
2057
2058                       "boolean" "byte" "char" "double" "float" "int" "long"
2059                       "short" "void"))
2060         (javascript-constants
2061          (mdw-regexps "false" "null" "undefined" "Infinity" "NaN" "true"
2062                       "arguments" "this")))
2063
2064     (setq font-lock-keywords
2065           (list
2066
2067            ;; Handle the keywords defined above.
2068            (list (concat "\\_<\\(" javascript-keywords "\\)\\_>")
2069                  '(0 font-lock-keyword-face))
2070
2071            ;; Handle the predefined constants defined above.
2072            (list (concat "\\_<\\(" javascript-constants "\\)\\_>")
2073                  '(0 font-lock-variable-name-face))
2074
2075            ;; Handle numbers too.
2076            ;;
2077            ;; The following isn't quite right, but it's close enough.
2078            (list (concat "\\_<\\("
2079                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
2080                          "[0-9]+\\(\\.[0-9]*\\|\\)"
2081                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)"
2082                          "[lLfFdD]?")
2083                  '(0 mdw-number-face))
2084
2085            ;; And anything else is punctuation.
2086            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2087                  '(0 mdw-punct-face))))))
2088
2089 ;;;--------------------------------------------------------------------------
2090 ;;; Scala programming configuration.
2091
2092 (defun mdw-fontify-scala ()
2093
2094   ;; Comment filling.
2095   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
2096
2097   ;; Define things to be fontified.
2098   (make-local-variable 'font-lock-keywords)
2099   (let ((scala-keywords
2100          (mdw-regexps "abstract" "case" "catch" "class" "def" "do" "else"
2101                       "extends" "final" "finally" "for" "forSome" "if"
2102                       "implicit" "import" "lazy" "match" "new" "object"
2103                       "override" "package" "private" "protected" "return"
2104                       "sealed" "throw" "trait" "try" "type" "val"
2105                       "var" "while" "with" "yield"))
2106         (scala-constants
2107          (mdw-regexps "false" "null" "super" "this" "true"))
2108         (punctuation "[-!%^&*=+:@#~/?\\|`]"))
2109
2110     (setq font-lock-keywords
2111           (list
2112
2113            ;; Magical identifiers between backticks.
2114            (list (concat "`\\([^`]+\\)`")
2115                  '(1 font-lock-variable-name-face))
2116
2117            ;; Handle the keywords defined above.
2118            (list (concat "\\_<\\(" scala-keywords "\\)\\_>")
2119                  '(0 font-lock-keyword-face))
2120
2121            ;; Handle the constants defined above.
2122            (list (concat "\\_<\\(" scala-constants "\\)\\_>")
2123                  '(0 font-lock-variable-name-face))
2124
2125            ;; Magical identifiers between backticks.
2126            (list (concat "`\\([^`]+\\)`")
2127                  '(1 font-lock-variable-name-face))
2128
2129            ;; Handle numbers too.
2130            ;;
2131            ;; As usual, not quite right.
2132            (list (concat "\\_<\\("
2133                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
2134                          "[0-9]+\\(\\.[0-9]*\\|\\)"
2135                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)"
2136                          "[lLfFdD]?")
2137                  '(0 mdw-number-face))
2138
2139            ;; Identifiers with trailing operators.
2140            (list (concat "_\\(" punctuation "\\)+")
2141                  '(0 mdw-trivial-face))
2142
2143            ;; And everything else is punctuation.
2144            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2145                  '(0 mdw-punct-face)))
2146
2147           font-lock-syntactic-keywords
2148           (list
2149
2150            ;; Single quotes around characters.  But not when used to quote
2151            ;; symbol names.  Ugh.
2152            (list (concat "\\('\\)"
2153                          "\\(" "."
2154                          "\\|" "\\\\" "\\(" "\\\\\\\\" "\\)*"
2155                                "u+" "[0-9a-fA-F]\\{4\\}"
2156                          "\\|" "\\\\" "[0-7]\\{1,3\\}"
2157                          "\\|" "\\\\" "." "\\)"
2158                          "\\('\\)")
2159                  '(1 "\"")
2160                  '(4 "\""))))))
2161
2162 ;;;--------------------------------------------------------------------------
2163 ;;; C# programming configuration.
2164
2165 ;; Make indentation nice.
2166
2167 (mdw-define-c-style mdw-csharp
2168   (c-basic-offset . 2)
2169   (c-backslash-column . 72)
2170   (c-offsets-alist (substatement-open . 0)
2171                    (label . 0)
2172                    (case-label . +)
2173                    (access-label . 0)
2174                    (inclass . +)
2175                    (statement-case-intro . +)))
2176 (mdw-set-default-c-style 'csharp-mode 'mdw-csharp)
2177
2178 ;; Declare C# fontification style.
2179
2180 (defun mdw-fontify-csharp ()
2181
2182   ;; Other stuff.
2183   (setq mdw-fill-prefix mdw-c-comment-fill-prefix)
2184
2185   ;; Now define things to be fontified.
2186   (make-local-variable 'font-lock-keywords)
2187   (let ((csharp-keywords
2188          (mdw-regexps "abstract" "as" "bool" "break" "byte" "case" "catch"
2189                       "char" "checked" "class" "const" "continue" "decimal"
2190                       "default" "delegate" "do" "double" "else" "enum"
2191                       "event" "explicit" "extern" "finally" "fixed" "float"
2192                       "for" "foreach" "goto" "if" "implicit" "in" "int"
2193                       "interface" "internal" "is" "lock" "long" "namespace"
2194                       "new" "object" "operator" "out" "override" "params"
2195                       "private" "protected" "public" "readonly" "ref"
2196                       "return" "sbyte" "sealed" "short" "sizeof"
2197                       "stackalloc" "static" "string" "struct" "switch"
2198                       "throw" "try" "typeof" "uint" "ulong" "unchecked"
2199                       "unsafe" "ushort" "using" "virtual" "void" "volatile"
2200                       "while" "yield"))
2201
2202         (csharp-constants
2203          (mdw-regexps "base" "false" "null" "this" "true")))
2204
2205     (setq font-lock-keywords
2206           (list
2207
2208            ;; Handle the keywords defined above.
2209            (list (concat "\\<\\(" csharp-keywords "\\)\\>")
2210                  '(0 font-lock-keyword-face))
2211
2212            ;; Handle the magic constants defined above.
2213            (list (concat "\\<\\(" csharp-constants "\\)\\>")
2214                  '(0 font-lock-variable-name-face))
2215
2216            ;; Handle numbers too.
2217            ;;
2218            ;; The following isn't quite right, but it's close enough.
2219            (list (concat "\\<\\("
2220                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
2221                          "[0-9]+\\(\\.[0-9]*\\|\\)"
2222                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)"
2223                          "[lLfFdD]?")
2224                  '(0 mdw-number-face))
2225
2226            ;; And anything else is punctuation.
2227            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2228                  '(0 mdw-punct-face))))))
2229
2230 (define-derived-mode csharp-mode java-mode "C#"
2231   "Major mode for editing C# code.")
2232
2233 ;;;--------------------------------------------------------------------------
2234 ;;; F# programming configuration.
2235
2236 (setq fsharp-indent-offset 2)
2237
2238 (defun mdw-fontify-fsharp ()
2239
2240   (let ((punct "=<>+-*/|&%!@?"))
2241     (do ((i 0 (1+ i)))
2242         ((>= i (length punct)))
2243       (modify-syntax-entry (aref punct i) ".")))
2244
2245   (modify-syntax-entry ?_ "_")
2246   (modify-syntax-entry ?( "(")
2247   (modify-syntax-entry ?) ")")
2248
2249   (setq indent-tabs-mode nil)
2250
2251   (let ((fsharp-keywords
2252          (mdw-regexps "abstract" "and" "as" "assert" "atomic"
2253                       "begin" "break"
2254                       "checked" "class" "component" "const" "constraint"
2255                       "constructor" "continue"
2256                       "default" "delegate" "do" "done" "downcast" "downto"
2257                       "eager" "elif" "else" "end" "exception" "extern"
2258                       "finally" "fixed" "for" "fori" "fun" "function"
2259                       "functor"
2260                       "global"
2261                       "if" "in" "include" "inherit" "inline" "interface"
2262                       "internal"
2263                       "lazy" "let"
2264                       "match" "measure" "member" "method" "mixin" "module"
2265                       "mutable"
2266                       "namespace" "new"
2267                       "object" "of" "open" "or" "override"
2268                       "parallel" "params" "private" "process" "protected"
2269                       "public" "pure"
2270                       "rec" "recursive" "return"
2271                       "sealed" "sig" "static" "struct"
2272                       "tailcall" "then" "to" "trait" "try" "type"
2273                       "upcast" "use"
2274                       "val" "virtual" "void" "volatile"
2275                       "when" "while" "with"
2276                       "yield"))
2277
2278         (fsharp-builtins
2279          (mdw-regexps "asr" "land" "lor" "lsl" "lsr" "lxor" "mod"
2280                       "base" "false" "null" "true"))
2281
2282         (bang-keywords
2283          (mdw-regexps "do" "let" "return" "use" "yield"))
2284
2285         (preprocessor-keywords
2286          (mdw-regexps "if" "indent" "else" "endif")))
2287
2288     (setq font-lock-keywords
2289           (list (list (concat "\\(^\\|[^\"]\\)"
2290                               "\\(" "(\\*"
2291                                     "[^*]*\\*+"
2292                                     "\\(" "[^)*]" "[^*]*" "\\*+" "\\)*"
2293                                     ")"
2294                               "\\|"
2295                                     "//.*"
2296                               "\\)")
2297                       '(2 font-lock-comment-face))
2298
2299                 (list (concat "'" "\\("
2300                                     "\\\\"
2301                                     "\\(" "[ntbr'\\]"
2302                                     "\\|" "[0-9][0-9][0-9]"
2303                                     "\\|" "u" "[0-9a-fA-F]\\{4\\}"
2304                                     "\\|" "U" "[0-9a-fA-F]\\{8\\}"
2305                                     "\\)"
2306                                   "\\|"
2307                                   "." "\\)" "'"
2308                               "\\|"
2309                               "\"" "[^\"\\]*"
2310                                     "\\(" "\\\\" "\\(.\\|\n\\)"
2311                                           "[^\"\\]*" "\\)*"
2312                               "\\(\"\\|\\'\\)")
2313                       '(0 font-lock-string-face))
2314
2315                 (list (concat "\\_<\\(" bang-keywords "\\)!" "\\|"
2316                               "^#[ \t]*\\(" preprocessor-keywords "\\)\\_>"
2317                               "\\|"
2318                               "\\_<\\(" fsharp-keywords "\\)\\_>")
2319                       '(0 font-lock-keyword-face))
2320                 (list (concat "\\<\\(" fsharp-builtins "\\)\\_>")
2321                       '(0 font-lock-variable-name-face))
2322
2323                 (list (concat "\\_<"
2324                               "\\(" "0[bB][01]+" "\\|"
2325                                     "0[oO][0-7]+" "\\|"
2326                                     "0[xX][0-9a-fA-F]+" "\\)"
2327                               "\\(" "lf\\|LF" "\\|"
2328                                     "[uU]?[ysnlL]?" "\\)"
2329                               "\\|"
2330                               "\\_<"
2331                               "[0-9]+" "\\("
2332                                 "[mMQRZING]"
2333                                 "\\|"
2334                                 "\\(\\.[0-9]*\\)?"
2335                                 "\\([eE][-+]?[0-9]+\\)?"
2336                                 "[fFmM]?"
2337                                 "\\|"
2338                                 "[uU]?[ysnlL]?"
2339                               "\\)")
2340                       '(0 mdw-number-face))
2341
2342                 (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2343                       '(0 mdw-punct-face))))))
2344
2345 (defun mdw-fontify-inferior-fsharp ()
2346   (mdw-fontify-fsharp)
2347   (setq font-lock-keywords
2348         (append (list (list "^[#-]" '(0 font-lock-comment-face))
2349                       (list "^>" '(0 font-lock-keyword-face)))
2350                 font-lock-keywords)))
2351
2352 ;;;--------------------------------------------------------------------------
2353 ;;; Go programming configuration.
2354
2355 (defun mdw-fontify-go ()
2356
2357   (make-local-variable 'font-lock-keywords)
2358   (let ((go-keywords
2359          (mdw-regexps "break" "case" "chan" "const" "continue"
2360                       "default" "defer" "else" "fallthrough" "for"
2361                       "func" "go" "goto" "if" "import"
2362                       "interface" "map" "package" "range" "return"
2363                       "select" "struct" "switch" "type" "var"))
2364         (go-intrinsics
2365          (mdw-regexps "bool" "byte" "complex64" "complex128" "error"
2366                       "float32" "float64" "int" "uint8" "int16" "int32"
2367                       "int64" "rune" "string" "uint" "uint8" "uint16"
2368                       "uint32" "uint64" "uintptr" "void"
2369                       "false" "iota" "nil" "true"
2370                       "init" "main"
2371                       "append" "cap" "copy" "delete" "imag" "len" "make"
2372                       "new" "panic" "real" "recover")))
2373
2374     (setq font-lock-keywords
2375           (list
2376
2377            ;; Handle the keywords defined above.
2378            (list (concat "\\<\\(" go-keywords "\\)\\>")
2379                  '(0 font-lock-keyword-face))
2380            (list (concat "\\<\\(" go-intrinsics "\\)\\>")
2381                  '(0 font-lock-variable-name-face))
2382
2383            ;; Strings and characters.
2384            (list (concat "'"
2385                          "\\(" "[^\\']" "\\|"
2386                                "\\\\"
2387                                "\\(" "[abfnrtv\\'\"]" "\\|"
2388                                      "[0-7]\\{3\\}" "\\|"
2389                                      "x" "[0-9A-Fa-f]\\{2\\}" "\\|"
2390                                      "u" "[0-9A-Fa-f]\\{4\\}" "\\|"
2391                                      "U" "[0-9A-Fa-f]\\{8\\}" "\\)" "\\)"
2392                          "'"
2393                          "\\|"
2394                          "\""
2395                          "\\(" "[^\n\\\"]+" "\\|" "\\\\." "\\)*"
2396                          "\\(\"\\|$\\)"
2397                          "\\|"
2398                          "`" "[^`]+" "`")
2399                  '(0 font-lock-string-face))
2400
2401            ;; Handle numbers too.
2402            ;;
2403            ;; The following isn't quite right, but it's close enough.
2404            (list (concat "\\<\\("
2405                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
2406                          "[0-9]+\\(\\.[0-9]*\\|\\)"
2407                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)")
2408                  '(0 mdw-number-face))
2409
2410            ;; And anything else is punctuation.
2411            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2412                  '(0 mdw-punct-face))))))
2413
2414 ;;;--------------------------------------------------------------------------
2415 ;;; Rust programming configuration.
2416
2417 (setq-default rust-indent-offset 2)
2418
2419 (defun mdw-self-insert-and-indent (count)
2420   (interactive "p")
2421   (self-insert-command count)
2422   (indent-according-to-mode))
2423
2424 (defun mdw-fontify-rust ()
2425
2426   ;; Hack syntax categories.
2427   (modify-syntax-entry ?= ".")
2428
2429   ;; Fontify keywords and things.
2430   (make-local-variable 'font-lock-keywords)
2431   (let ((rust-keywords
2432          (mdw-regexps "abstract" "alignof" "as"
2433                       "become" "box" "break"
2434                       "const" "continue" "create"
2435                       "do"
2436                       "else" "enum" "extern"
2437                       "false" "final" "fn" "for"
2438                       "if" "impl" "in"
2439                       "let" "loop"
2440                       "macro" "match" "mod" "move" "mut"
2441                       "offsetof" "override"
2442                       "priv" "pub" "pure"
2443                       "ref" "return"
2444                       "self" "sizeof" "static" "struct" "super"
2445                       "true" "trait" "type" "typeof"
2446                       "unsafe" "unsized" "use"
2447                       "virtual"
2448                       "where" "while"
2449                       "yield"))
2450         (rust-builtins
2451          (mdw-regexps "array" "pointer" "slice" "tuple"
2452                       "bool" "true" "false"
2453                       "f32" "f64"
2454                       "i8" "i16" "i32" "i64" "isize"
2455                       "u8" "u16" "u32" "u64" "usize"
2456                       "char" "str")))
2457     (setq font-lock-keywords
2458           (list
2459
2460            ;; Handle the keywords defined above.
2461            (list (concat "\\_<\\(" rust-keywords "\\)\\_>")
2462                  '(0 font-lock-keyword-face))
2463            (list (concat "\\_<\\(" rust-builtins "\\)\\_>")
2464                  '(0 font-lock-variable-name-face))
2465
2466            ;; Handle numbers too.
2467            (list (concat "\\_<\\("
2468                                "[0-9][0-9_]*"
2469                                "\\(" "\\(\\.[0-9_]+\\)?[eE][-+]?[0-9_]+"
2470                                "\\|" "\\.[0-9_]+"
2471                                "\\)"
2472                                "\\(f32\\|f64\\)?"
2473                          "\\|" "\\(" "[0-9][0-9_]*"
2474                                "\\|" "0x[0-9a-fA-F_]+"
2475                                "\\|" "0o[0-7_]+"
2476                                "\\|" "0b[01_]+"
2477                                "\\)"
2478                                "\\([ui]\\(8\\|16\\|32\\|64\\|s\\|size\\)\\)?"
2479                          "\\)\\_>")
2480                  '(0 mdw-number-face))
2481
2482            ;; And anything else is punctuation.
2483            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2484                  '(0 mdw-punct-face)))))
2485
2486   ;; Hack key bindings.
2487   (local-set-key [?{] 'mdw-self-insert-and-indent)
2488   (local-set-key [?}] 'mdw-self-insert-and-indent))
2489
2490 ;;;--------------------------------------------------------------------------
2491 ;;; Awk programming configuration.
2492
2493 ;; Make Awk indentation nice.
2494
2495 (mdw-define-c-style mdw-awk
2496   (c-basic-offset . 2)
2497   (c-offsets-alist (substatement-open . 0)
2498                    (c-backslash-column . 72)
2499                    (statement-cont . 0)
2500                    (statement-case-intro . +)))
2501 (mdw-set-default-c-style 'awk-mode 'mdw-awk)
2502
2503 ;; Declare Awk fontification style.
2504
2505 (defun mdw-fontify-awk ()
2506
2507   ;; Miscellaneous fiddling.
2508   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
2509
2510   ;; Now define things to be fontified.
2511   (make-local-variable 'font-lock-keywords)
2512   (let ((c-keywords
2513          (mdw-regexps "BEGIN" "END" "ARGC" "ARGIND" "ARGV" "CONVFMT"
2514                       "ENVIRON" "ERRNO" "FIELDWIDTHS" "FILENAME" "FNR"
2515                       "FS" "IGNORECASE" "NF" "NR" "OFMT" "OFS" "ORS" "RS"
2516                       "RSTART" "RLENGTH" "RT"   "SUBSEP"
2517                       "atan2" "break" "close" "continue" "cos" "delete"
2518                       "do" "else" "exit" "exp" "fflush" "file" "for" "func"
2519                       "function" "gensub" "getline" "gsub" "if" "in"
2520                       "index" "int" "length" "log" "match" "next" "rand"
2521                       "return" "print" "printf" "sin" "split" "sprintf"
2522                       "sqrt" "srand" "strftime" "sub" "substr" "system"
2523                       "systime" "tolower" "toupper" "while")))
2524
2525     (setq font-lock-keywords
2526           (list
2527
2528            ;; Handle the keywords defined above.
2529            (list (concat "\\<\\(" c-keywords "\\)\\>")
2530                  '(0 font-lock-keyword-face))
2531
2532            ;; Handle numbers too.
2533            ;;
2534            ;; The following isn't quite right, but it's close enough.
2535            (list (concat "\\<\\("
2536                          "0\\([xX][0-9a-fA-F]+\\|[0-7]+\\)\\|"
2537                          "[0-9]+\\(\\.[0-9]*\\|\\)"
2538                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)\\)"
2539                          "[uUlL]*")
2540                  '(0 mdw-number-face))
2541
2542            ;; And anything else is punctuation.
2543            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2544                  '(0 mdw-punct-face))))))
2545
2546 ;;;--------------------------------------------------------------------------
2547 ;;; Perl programming style.
2548
2549 ;; Perl indentation style.
2550
2551 (setq perl-indent-level 2)
2552
2553 (setq cperl-indent-level 2)
2554 (setq cperl-continued-statement-offset 2)
2555 (setq cperl-continued-brace-offset 0)
2556 (setq cperl-brace-offset -2)
2557 (setq cperl-brace-imaginary-offset 0)
2558 (setq cperl-label-offset 0)
2559
2560 ;; Define perl fontification style.
2561
2562 (defun mdw-fontify-perl ()
2563
2564   ;; Miscellaneous fiddling.
2565   (modify-syntax-entry ?$ "\\")
2566   (modify-syntax-entry ?$ "\\" font-lock-syntax-table)
2567   (modify-syntax-entry ?: "." font-lock-syntax-table)
2568   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
2569
2570   ;; Now define fontification things.
2571   (make-local-variable 'font-lock-keywords)
2572   (let ((perl-keywords
2573          (mdw-regexps "and"
2574                       "break"
2575                       "cmp" "continue"
2576                       "default" "do"
2577                       "else" "elsif" "eq"
2578                       "for" "foreach"
2579                       "ge" "given" "gt" "goto"
2580                       "if"
2581                       "last" "le" "local" "lt"
2582                       "my"
2583                       "ne" "next"
2584                       "or" "our"
2585                       "package"
2586                       "redo" "require" "return"
2587                       "sub"
2588                       "undef" "unless" "until" "use"
2589                       "when" "while")))
2590
2591     (setq font-lock-keywords
2592           (list
2593
2594            ;; Set up the keywords defined above.
2595            (list (concat "\\<\\(" perl-keywords "\\)\\>")
2596                  '(0 font-lock-keyword-face))
2597
2598            ;; At least numbers are simpler than C.
2599            (list (concat "\\<0\\([xX][0-9a-fA-F_]+\\|[0-7_]+\\)\\|"
2600                          "\\<[0-9][0-9_]*\\(\\.[0-9_]*\\|\\)"
2601                          "\\([eE]\\([-+]\\|\\)[0-9_]+\\|\\)")
2602                  '(0 mdw-number-face))
2603
2604            ;; And anything else is punctuation.
2605            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2606                  '(0 mdw-punct-face))))))
2607
2608 (defun perl-number-tests (&optional arg)
2609   "Assign consecutive numbers to lines containing `#t'.  With ARG,
2610 strip numbers instead."
2611   (interactive "P")
2612   (save-excursion
2613     (goto-char (point-min))
2614     (let ((i 0) (fmt (if arg "" " %4d")))
2615       (while (search-forward "#t" nil t)
2616         (delete-region (point) (line-end-position))
2617         (setq i (1+ i))
2618         (insert (format fmt i)))
2619       (goto-char (point-min))
2620       (if (re-search-forward "\\(tests\\s-*=>\\s-*\\)\\w*" nil t)
2621           (replace-match (format "\\1%d" i))))))
2622
2623 ;;;--------------------------------------------------------------------------
2624 ;;; Python programming style.
2625
2626 (defun mdw-fontify-pythonic (keywords)
2627
2628   ;; Miscellaneous fiddling.
2629   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
2630   (setq indent-tabs-mode nil)
2631
2632   ;; Now define fontification things.
2633   (make-local-variable 'font-lock-keywords)
2634   (setq font-lock-keywords
2635         (list
2636
2637          ;; Set up the keywords defined above.
2638          (list (concat "\\_<\\(" keywords "\\)\\_>")
2639                '(0 font-lock-keyword-face))
2640
2641          ;; At least numbers are simpler than C.
2642          (list (concat "\\_<0\\([xX][0-9a-fA-F_]+\\|[0-7_]+\\)\\|"
2643                        "\\_<[0-9][0-9_]*\\(\\.[0-9_]*\\|\\)"
2644                        "\\([eE]\\([-+]\\|\\)[0-9_]+\\|[lL]\\|\\)")
2645                '(0 mdw-number-face))
2646
2647          ;; And anything else is punctuation.
2648          (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2649                '(0 mdw-punct-face)))))
2650
2651 ;; Define Python fontification styles.
2652
2653 (defun mdw-fontify-python ()
2654   (mdw-fontify-pythonic
2655    (mdw-regexps "and" "as" "assert" "break" "class" "continue" "def"
2656                 "del" "elif" "else" "except" "exec" "finally" "for"
2657                 "from" "global" "if" "import" "in" "is" "lambda"
2658                 "not" "or" "pass" "print" "raise" "return" "try"
2659                 "while" "with" "yield")))
2660
2661 (defun mdw-fontify-pyrex ()
2662   (mdw-fontify-pythonic
2663    (mdw-regexps "and" "as" "assert" "break" "cdef" "class" "continue"
2664                 "ctypedef" "def" "del" "elif" "else" "enum" "except" "exec"
2665                 "extern" "finally" "for" "from" "global" "if"
2666                 "import" "in" "is" "lambda" "not" "or" "pass" "print"
2667                 "property" "raise" "return" "struct" "try" "while" "with"
2668                 "yield")))
2669
2670 (define-derived-mode pyrex-mode python-mode "Pyrex"
2671   "Major mode for editing Pyrex source code")
2672 (setq auto-mode-alist
2673       (append '(("\\.pyx$" . pyrex-mode)
2674                 ("\\.pxd$" . pyrex-mode)
2675                 ("\\.pxi$" . pyrex-mode))
2676               auto-mode-alist))
2677
2678 ;;;--------------------------------------------------------------------------
2679 ;;; Lua programming style.
2680
2681 (setq lua-indent-level 2)
2682
2683 (defun mdw-fontify-lua ()
2684
2685   ;; Miscellaneous fiddling.
2686   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
2687
2688   ;; Now define fontification things.
2689   (make-local-variable 'font-lock-keywords)
2690   (let ((lua-keywords
2691          (mdw-regexps "and" "break" "do" "else" "elseif" "end"
2692                       "false" "for" "function" "goto" "if" "in" "local"
2693                       "nil" "not" "or" "repeat" "return" "then" "true"
2694                       "until" "while")))
2695     (setq font-lock-keywords
2696           (list
2697
2698            ;; Set up the keywords defined above.
2699            (list (concat "\\_<\\(" lua-keywords "\\)\\_>")
2700                  '(0 font-lock-keyword-face))
2701
2702            ;; At least numbers are simpler than C.
2703            (list (concat "\\_<\\(" "0[xX]"
2704                                    "\\(" "[0-9a-fA-F]+"
2705                                          "\\(\\.[0-9a-fA-F]*\\)?"
2706                                    "\\|" "\\.[0-9a-fA-F]+"
2707                                    "\\)"
2708                                    "\\([pP][-+]?[0-9]+\\)?"
2709                              "\\|" "\\(" "[0-9]+"
2710                                          "\\(\\.[0-9]*\\)?"
2711                                    "\\|" "\\.[0-9]+"
2712                                    "\\)"
2713                                    "\\([eE][-+]?[0-9]+\\)?"
2714                              "\\)")
2715                  '(0 mdw-number-face))
2716
2717            ;; And anything else is punctuation.
2718            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2719                  '(0 mdw-punct-face))))))
2720
2721 ;;;--------------------------------------------------------------------------
2722 ;;; Icon programming style.
2723
2724 ;; Icon indentation style.
2725
2726 (setq icon-brace-offset 0
2727       icon-continued-brace-offset 0
2728       icon-continued-statement-offset 2
2729       icon-indent-level 2)
2730
2731 ;; Define Icon fontification style.
2732
2733 (defun mdw-fontify-icon ()
2734
2735   ;; Miscellaneous fiddling.
2736   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
2737
2738   ;; Now define fontification things.
2739   (make-local-variable 'font-lock-keywords)
2740   (let ((icon-keywords
2741          (mdw-regexps "break" "by" "case" "create" "default" "do" "else"
2742                       "end" "every" "fail" "global" "if" "initial"
2743                       "invocable" "link" "local" "next" "not" "of"
2744                       "procedure" "record" "repeat" "return" "static"
2745                       "suspend" "then" "to" "until" "while"))
2746         (preprocessor-keywords
2747          (mdw-regexps "define" "else" "endif" "error" "ifdef" "ifndef"
2748                       "include" "line" "undef")))
2749     (setq font-lock-keywords
2750           (list
2751
2752            ;; Set up the keywords defined above.
2753            (list (concat "\\<\\(" icon-keywords "\\)\\>")
2754                  '(0 font-lock-keyword-face))
2755
2756            ;; The things that Icon calls keywords.
2757            (list "&\\sw+\\>" '(0 font-lock-variable-name-face))
2758
2759            ;; At least numbers are simpler than C.
2760            (list (concat "\\<[0-9]+"
2761                          "\\([rR][0-9a-zA-Z]+\\|"
2762                          "\\.[0-9]+\\([eE][+-]?[0-9]+\\)?\\)\\>\\|"
2763                          "\\.[0-9]+\\([eE][+-]?[0-9]+\\)?\\>")
2764                  '(0 mdw-number-face))
2765
2766            ;; Preprocessor.
2767            (list (concat "^[ \t]*$[ \t]*\\<\\("
2768                          preprocessor-keywords
2769                          "\\)\\>")
2770                  '(0 font-lock-keyword-face))
2771
2772            ;; And anything else is punctuation.
2773            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2774                  '(0 mdw-punct-face))))))
2775
2776 ;;;--------------------------------------------------------------------------
2777 ;;; Assembler mode.
2778
2779 (defun mdw-fontify-asm ()
2780   (modify-syntax-entry ?' "\"")
2781   (modify-syntax-entry ?. "w")
2782   (modify-syntax-entry ?\n ">")
2783   (setf fill-prefix nil)
2784   (local-set-key ";" 'self-insert-command)
2785   (mdw-standard-fill-prefix "\\([ \t]*;+[ \t]*\\)"))
2786
2787 (defun mdw-asm-set-comment ()
2788   (modify-syntax-entry ?; "."
2789                        )
2790   (modify-syntax-entry asm-comment-char "<b")
2791   (setq comment-start (string asm-comment-char ? )))
2792 (add-hook 'asm-mode-local-variables-hook 'mdw-asm-set-comment)
2793 (put 'asm-comment-char 'safe-local-variable 'characterp)
2794
2795 ;;;--------------------------------------------------------------------------
2796 ;;; TCL configuration.
2797
2798 (defun mdw-fontify-tcl ()
2799   (mapcar #'(lambda (ch) (modify-syntax-entry ch ".")) '(?$))
2800   (mdw-standard-fill-prefix "\\([ \t]*#+[ \t]*\\)")
2801   (make-local-variable 'font-lock-keywords)
2802   (setq font-lock-keywords
2803         (list
2804          (list (concat "\\<0\\([xX][0-9a-fA-F_]+\\|[0-7_]+\\)\\|"
2805                        "\\<[0-9][0-9_]*\\(\\.[0-9_]*\\|\\)"
2806                        "\\([eE]\\([-+]\\|\\)[0-9_]+\\|\\)")
2807                '(0 mdw-number-face))
2808          (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2809                '(0 mdw-punct-face)))))
2810
2811 ;;;--------------------------------------------------------------------------
2812 ;;; Dylan programming configuration.
2813
2814 (defun mdw-fontify-dylan ()
2815
2816   (make-local-variable 'font-lock-keywords)
2817
2818   ;; Horrors.  `dylan-mode' sets the `major-mode' name after calling this
2819   ;; hook, which undoes all of our configuration.
2820   (setq major-mode 'dylan-mode)
2821   (font-lock-set-defaults)
2822
2823   (let* ((word "[-_a-zA-Z!*@<>$%]+")
2824          (dylan-keywords (mdw-regexps
2825
2826                           "C-address" "C-callable-wrapper" "C-function"
2827                           "C-mapped-subtype" "C-pointer-type" "C-struct"
2828                           "C-subtype" "C-union" "C-variable"
2829
2830                           "above" "abstract" "afterwards" "all"
2831                           "begin" "below" "block" "by"
2832                           "case" "class" "cleanup" "constant" "create"
2833                           "define" "domain"
2834                           "else" "elseif" "end" "exception" "export"
2835                           "finally" "for" "from" "function"
2836                           "generic"
2837                           "handler"
2838                           "if" "in" "instance" "interface" "iterate"
2839                           "keyed-by"
2840                           "let" "library" "local"
2841                           "macro" "method" "module"
2842                           "otherwise"
2843                           "profiling"
2844                           "select" "slot" "subclass"
2845                           "table" "then" "to"
2846                           "unless" "until" "use"
2847                           "variable" "virtual"
2848                           "when" "while"))
2849          (sharp-keywords (mdw-regexps
2850                           "all-keys" "key" "next" "rest" "include"
2851                           "t" "f")))
2852     (setq font-lock-keywords
2853           (list (list (concat "\\<\\(" dylan-keywords
2854                               "\\|" "with\\(out\\)?-" word
2855                               "\\)\\>")
2856                       '(0 font-lock-keyword-face))
2857                 (list (concat "\\<" word ":" "\\|"
2858                               "#\\(" sharp-keywords "\\)\\>")
2859                       '(0 font-lock-variable-name-face))
2860                 (list (concat "\\("
2861                               "\\([-+]\\|\\<\\)[0-9]+" "\\("
2862                                 "\\(\\.[0-9]+\\)?" "\\([eE][-+][0-9]+\\)?"
2863                                 "\\|" "/[0-9]+"
2864                               "\\)"
2865                               "\\|" "\\.[0-9]+" "\\([eE][-+][0-9]+\\)?"
2866                               "\\|" "#b[01]+"
2867                               "\\|" "#o[0-7]+"
2868                               "\\|" "#x[0-9a-zA-Z]+"
2869                               "\\)\\>")
2870                       '(0 mdw-number-face))
2871                 (list (concat "\\("
2872                               "\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\|"
2873                               "\\_<[-+*/=<>:&|]+\\_>"
2874                               "\\)")
2875                       '(0 mdw-punct-face))))))
2876
2877 ;;;--------------------------------------------------------------------------
2878 ;;; Algol 68 configuration.
2879
2880 (setq a68-indent-step 2)
2881
2882 (defun mdw-fontify-algol-68 ()
2883
2884   ;; Fix up the syntax table.
2885   (modify-syntax-entry ?# "!" a68-mode-syntax-table)
2886   (dolist (ch '(?- ?+ ?= ?< ?> ?* ?/ ?| ?&))
2887     (modify-syntax-entry ch "." a68-mode-syntax-table))
2888
2889   (make-local-variable 'font-lock-keywords)
2890
2891   (let ((not-comment
2892          (let ((word "COMMENT"))
2893            (do ((regexp (concat "[^" (substring word 0 1) "]+")
2894                         (concat regexp "\\|"
2895                                 (substring word 0 i)
2896                                 "[^" (substring word i (1+ i)) "]"))
2897                 (i 1 (1+ i)))
2898                ((>= i (length word)) regexp)))))
2899     (setq font-lock-keywords
2900           (list (list (concat "\\<COMMENT\\>"
2901                               "\\(" not-comment "\\)\\{0,5\\}"
2902                               "\\(\\'\\|\\<COMMENT\\>\\)")
2903                       '(0 font-lock-comment-face))
2904                 (list (concat "\\<CO\\>"
2905                               "\\([^C]+\\|C[^O]\\)\\{0,5\\}"
2906                               "\\($\\|\\<CO\\>\\)")
2907                       '(0 font-lock-comment-face))
2908                 (list "\\<[A-Z_]+\\>"
2909                       '(0 font-lock-keyword-face))
2910                 (list (concat "\\<"
2911                               "[0-9]+"
2912                               "\\(\\.[0-9]+\\)?"
2913                               "\\([eE][-+]?[0-9]+\\)?"
2914                               "\\>")
2915                       '(0 mdw-number-face))
2916                 (list "\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/"
2917                       '(0 mdw-punct-face))))))
2918
2919 ;;;--------------------------------------------------------------------------
2920 ;;; REXX configuration.
2921
2922 (defun mdw-rexx-electric-* ()
2923   (interactive)
2924   (insert ?*)
2925   (rexx-indent-line))
2926
2927 (defun mdw-rexx-indent-newline-indent ()
2928   (interactive)
2929   (rexx-indent-line)
2930   (if abbrev-mode (expand-abbrev))
2931   (newline-and-indent))
2932
2933 (defun mdw-fontify-rexx ()
2934
2935   ;; Various bits of fiddling.
2936   (setq mdw-auto-indent nil)
2937   (local-set-key [?\C-m] 'mdw-rexx-indent-newline-indent)
2938   (local-set-key [?*] 'mdw-rexx-electric-*)
2939   (mapcar #'(lambda (ch) (modify-syntax-entry ch "w"))
2940           '(?! ?? ?# ?@ ?$))
2941   (mdw-standard-fill-prefix "\\([ \t]*/?\*[ \t]*\\)")
2942
2943   ;; Set up keywords and things for fontification.
2944   (make-local-variable 'font-lock-keywords-case-fold-search)
2945   (setq font-lock-keywords-case-fold-search t)
2946
2947   (setq rexx-indent 2)
2948   (setq rexx-end-indent rexx-indent)
2949   (setq rexx-cont-indent rexx-indent)
2950
2951   (make-local-variable 'font-lock-keywords)
2952   (let ((rexx-keywords
2953          (mdw-regexps "address" "arg" "by" "call" "digits" "do" "drop"
2954                       "else" "end" "engineering" "exit" "expose" "for"
2955                       "forever" "form" "fuzz" "if" "interpret" "iterate"
2956                       "leave" "linein" "name" "nop" "numeric" "off" "on"
2957                       "options" "otherwise" "parse" "procedure" "pull"
2958                       "push" "queue" "return" "say" "select" "signal"
2959                       "scientific" "source" "then" "trace" "to" "until"
2960                       "upper" "value" "var" "version" "when" "while"
2961                       "with"
2962
2963                       "abbrev" "abs" "bitand" "bitor" "bitxor" "b2x"
2964                       "center" "center" "charin" "charout" "chars"
2965                       "compare" "condition" "copies" "c2d" "c2x"
2966                       "datatype" "date" "delstr" "delword" "d2c" "d2x"
2967                       "errortext" "format" "fuzz" "insert" "lastpos"
2968                       "left" "length" "lineout" "lines" "max" "min"
2969                       "overlay" "pos" "queued" "random" "reverse" "right"
2970                       "sign" "sourceline" "space" "stream" "strip"
2971                       "substr" "subword" "symbol" "time" "translate"
2972                       "trunc" "value" "verify" "word" "wordindex"
2973                       "wordlength" "wordpos" "words" "xrange" "x2b" "x2c"
2974                       "x2d")))
2975
2976     (setq font-lock-keywords
2977           (list
2978
2979            ;; Set up the keywords defined above.
2980            (list (concat "\\<\\(" rexx-keywords "\\)\\>")
2981                  '(0 font-lock-keyword-face))
2982
2983            ;; Fontify all symbols the same way.
2984            (list (concat "\\<\\([0-9.][A-Za-z0-9.!?_#@$]*[Ee][+-]?[0-9]+\\|"
2985                          "[A-Za-z0-9.!?_#@$]+\\)")
2986                  '(0 font-lock-variable-name-face))
2987
2988            ;; And everything else is punctuation.
2989            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
2990                  '(0 mdw-punct-face))))))
2991
2992 ;;;--------------------------------------------------------------------------
2993 ;;; Standard ML programming style.
2994
2995 (defun mdw-fontify-sml ()
2996
2997   ;; Make underscore an honorary letter.
2998   (modify-syntax-entry ?' "w")
2999
3000   ;; Set fill prefix.
3001   (mdw-standard-fill-prefix "\\([ \t]*(\*[ \t]*\\)")
3002
3003   ;; Now define fontification things.
3004   (make-local-variable 'font-lock-keywords)
3005   (let ((sml-keywords
3006          (mdw-regexps "abstype" "and" "andalso" "as"
3007                       "case"
3008                       "datatype" "do"
3009                       "else" "end" "eqtype" "exception"
3010                       "fn" "fun" "functor"
3011                       "handle"
3012                       "if" "in" "include" "infix" "infixr"
3013                       "let" "local"
3014                       "nonfix"
3015                       "of" "op" "open" "orelse"
3016                       "raise" "rec"
3017                       "sharing" "sig" "signature" "struct" "structure"
3018                       "then" "type"
3019                       "val"
3020                       "where" "while" "with" "withtype")))
3021
3022     (setq font-lock-keywords
3023           (list
3024
3025            ;; Set up the keywords defined above.
3026            (list (concat "\\<\\(" sml-keywords "\\)\\>")
3027                  '(0 font-lock-keyword-face))
3028
3029            ;; At least numbers are simpler than C.
3030            (list (concat "\\<\\(\\~\\|\\)"
3031                             "\\(0\\(\\([wW]\\|\\)[xX][0-9a-fA-F]+\\|"
3032                                    "[wW][0-9]+\\)\\|"
3033                                 "\\([0-9]+\\(\\.[0-9]+\\|\\)"
3034                                          "\\([eE]\\(\\~\\|\\)"
3035                                                 "[0-9]+\\|\\)\\)\\)")
3036                  '(0 mdw-number-face))
3037
3038            ;; And anything else is punctuation.
3039            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3040                  '(0 mdw-punct-face))))))
3041
3042 ;;;--------------------------------------------------------------------------
3043 ;;; Haskell configuration.
3044
3045 (defun mdw-fontify-haskell ()
3046
3047   ;; Fiddle with syntax table to get comments right.
3048   (modify-syntax-entry ?' "_")
3049   (modify-syntax-entry ?- ". 12")
3050   (modify-syntax-entry ?\n ">")
3051
3052   ;; Make punctuation be punctuation
3053   (let ((punct "=<>+-*/|&%!@?$.^:#`"))
3054     (do ((i 0 (1+ i)))
3055         ((>= i (length punct)))
3056       (modify-syntax-entry (aref punct i) ".")))
3057
3058   ;; Set fill prefix.
3059   (mdw-standard-fill-prefix "\\([ \t]*{?--?[ \t]*\\)")
3060
3061   ;; Fiddle with fontification.
3062   (make-local-variable 'font-lock-keywords)
3063   (let ((haskell-keywords
3064          (mdw-regexps "as"
3065                       "case" "ccall" "class"
3066                       "data" "default" "deriving" "do"
3067                       "else" "exists"
3068                       "forall" "foreign"
3069                       "hiding"
3070                       "if" "import" "in" "infix" "infixl" "infixr" "instance"
3071                       "let"
3072                       "mdo" "module"
3073                       "newtype"
3074                       "of"
3075                       "proc"
3076                       "qualified"
3077                       "rec"
3078                       "safe" "stdcall"
3079                       "then" "type"
3080                       "unsafe"
3081                       "where"))
3082         (control-sequences
3083          (mdw-regexps "ACK" "BEL" "BS" "CAN" "CR" "DC1" "DC2" "DC3" "DC4"
3084                       "DEL" "DLE" "EM" "ENQ" "EOT" "ESC" "ETB" "ETX" "FF"
3085                       "FS" "GS" "HT" "LF" "NAK" "NUL" "RS" "SI" "SO" "SOH"
3086                       "SP" "STX" "SUB" "SYN" "US" "VT")))
3087
3088     (setq font-lock-keywords
3089           (list
3090            (list (concat "{-" "[^-]*" "\\(-+[^-}][^-]*\\)*"
3091                               "\\(-+}\\|-*\\'\\)"
3092                          "\\|"
3093                          "--.*$")
3094                  '(0 font-lock-comment-face))
3095            (list (concat "\\_<\\(" haskell-keywords "\\)\\_>")
3096                  '(0 font-lock-keyword-face))
3097            (list (concat "'\\("
3098                          "[^\\]"
3099                          "\\|"
3100                          "\\\\"
3101                          "\\(" "[abfnrtv\\\"']" "\\|"
3102                                "^" "\\(" control-sequences "\\|"
3103                                          "[]A-Z@[\\^_]" "\\)" "\\|"
3104                                "\\|"
3105                                "[0-9]+" "\\|"
3106                                "[oO][0-7]+" "\\|"
3107                                "[xX][0-9A-Fa-f]+"
3108                          "\\)"
3109                          "\\)'")
3110                  '(0 font-lock-string-face))
3111            (list "\\_<[A-Z]\\(\\sw+\\|\\s_+\\)*\\_>"
3112                  '(0 font-lock-variable-name-face))
3113            (list (concat "\\_<0\\([xX][0-9a-fA-F]+\\|[oO][0-7]+\\)\\|"
3114                          "\\_<[0-9]+\\(\\.[0-9]*\\|\\)"
3115                          "\\([eE]\\([-+]\\|\\)[0-9]+\\|\\)")
3116                  '(0 mdw-number-face))
3117            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3118                  '(0 mdw-punct-face))))))
3119
3120 ;;;--------------------------------------------------------------------------
3121 ;;; Erlang configuration.
3122
3123 (setq erlang-electric-commands nil)
3124
3125 (defun mdw-fontify-erlang ()
3126
3127   ;; Set fill prefix.
3128   (mdw-standard-fill-prefix "\\([ \t]*{?%*[ \t]*\\)")
3129
3130   ;; Fiddle with fontification.
3131   (make-local-variable 'font-lock-keywords)
3132   (let ((erlang-keywords
3133          (mdw-regexps "after" "and" "andalso"
3134                       "band" "begin" "bnot" "bor" "bsl" "bsr" "bxor"
3135                       "case" "catch" "cond"
3136                       "div" "end" "fun" "if" "let" "not"
3137                       "of" "or" "orelse"
3138                       "query" "receive" "rem" "try" "when" "xor")))
3139
3140     (setq font-lock-keywords
3141           (list
3142            (list "%.*$"
3143                  '(0 font-lock-comment-face))
3144            (list (concat "\\<\\(" erlang-keywords "\\)\\>")
3145                  '(0 font-lock-keyword-face))
3146            (list (concat "^-\\sw+\\>")
3147                  '(0 font-lock-keyword-face))
3148            (list "\\<[0-9]+\\(\\|#[0-9a-zA-Z]+\\|[eE][+-]?[0-9]+\\)\\>"
3149                  '(0 mdw-number-face))
3150            (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3151                  '(0 mdw-punct-face))))))
3152
3153 ;;;--------------------------------------------------------------------------
3154 ;;; Texinfo configuration.
3155
3156 (defun mdw-fontify-texinfo ()
3157
3158   ;; Set fill prefix.
3159   (mdw-standard-fill-prefix "\\([ \t]*@c[ \t]+\\)")
3160
3161   ;; Real fontification things.
3162   (make-local-variable 'font-lock-keywords)
3163   (setq font-lock-keywords
3164         (list
3165
3166          ;; Environment names are keywords.
3167          (list "@\\(end\\)  *\\([a-zA-Z]*\\)?"
3168                '(2 font-lock-keyword-face))
3169
3170          ;; Unmark escaped magic characters.
3171          (list "\\(@\\)\\([@{}]\\)"
3172                '(1 font-lock-keyword-face)
3173                '(2 font-lock-variable-name-face))
3174
3175          ;; Make sure we get comments properly.
3176          (list "@c\\(\\|omment\\)\\( .*\\)?$"
3177                '(0 font-lock-comment-face))
3178
3179          ;; Command names are keywords.
3180          (list "@\\([^a-zA-Z@]\\|[a-zA-Z@]*\\)"
3181                '(0 font-lock-keyword-face))
3182
3183          ;; Fontify TeX special characters as punctuation.
3184          (list "[{}]+"
3185                '(0 mdw-punct-face)))))
3186
3187 ;;;--------------------------------------------------------------------------
3188 ;;; TeX and LaTeX configuration.
3189
3190 (defun mdw-fontify-tex ()
3191   (setq ispell-parser 'tex)
3192   (turn-on-reftex)
3193
3194   ;; Don't make maths into a string.
3195   (modify-syntax-entry ?$ ".")
3196   (modify-syntax-entry ?$ "." font-lock-syntax-table)
3197   (local-set-key [?$] 'self-insert-command)
3198
3199   ;; Make `tab' be useful, given that tab stops in TeX don't work well.
3200   (local-set-key "\C-\M-i" 'indent-relative)
3201   (setq indent-tabs-mode nil)
3202
3203   ;; Set fill prefix.
3204   (mdw-standard-fill-prefix "\\([ \t]*%+[ \t]*\\)")
3205
3206   ;; Real fontification things.
3207   (make-local-variable 'font-lock-keywords)
3208   (setq font-lock-keywords
3209         (list
3210
3211          ;; Environment names are keywords.
3212          (list (concat "\\\\\\(begin\\|end\\|newenvironment\\)"
3213                        "{\\([^}\n]*\\)}")
3214                '(2 font-lock-keyword-face))
3215
3216          ;; Suspended environment names are keywords too.
3217          (list (concat "\\\\\\(suspend\\|resume\\)\\(\\[[^]]*\\]\\)?"
3218                        "{\\([^}\n]*\\)}")
3219                '(3 font-lock-keyword-face))
3220
3221          ;; Command names are keywords.
3222          (list "\\\\\\([^a-zA-Z@]\\|[a-zA-Z@]*\\)"
3223                '(0 font-lock-keyword-face))
3224
3225          ;; Handle @/.../ for italics.
3226          ;; (list "\\(@/\\)\\([^/]*\\)\\(/\\)"
3227          ;;       '(1 font-lock-keyword-face)
3228          ;;       '(3 font-lock-keyword-face))
3229
3230          ;; Handle @*...* for boldness.
3231          ;; (list "\\(@\\*\\)\\([^*]*\\)\\(\\*\\)"
3232          ;;       '(1 font-lock-keyword-face)
3233          ;;       '(3 font-lock-keyword-face))
3234
3235          ;; Handle @`...' for literal syntax things.
3236          ;; (list "\\(@`\\)\\([^']*\\)\\('\\)"
3237          ;;       '(1 font-lock-keyword-face)
3238          ;;       '(3 font-lock-keyword-face))
3239
3240          ;; Handle @<...> for nonterminals.
3241          ;; (list "\\(@<\\)\\([^>]*\\)\\(>\\)"
3242          ;;       '(1 font-lock-keyword-face)
3243          ;;       '(3 font-lock-keyword-face))
3244
3245          ;; Handle other @-commands.
3246          ;; (list "@\\([^a-zA-Z]\\|[a-zA-Z]*\\)"
3247          ;;       '(0 font-lock-keyword-face))
3248
3249          ;; Make sure we get comments properly.
3250          (list "%.*"
3251                '(0 font-lock-comment-face))
3252
3253          ;; Fontify TeX special characters as punctuation.
3254          (list "[$^_{}#&]"
3255                '(0 mdw-punct-face)))))
3256
3257 (eval-after-load 'font-latex
3258   '(defun font-latex-jit-lock-force-redisplay (buf start end)
3259      "Compatibility for Emacsen not offering `jit-lock-force-redisplay'."
3260      ;; The following block is an expansion of `jit-lock-force-redisplay'
3261      ;; and involved macros taken from CVS Emacs on 2007-04-28.
3262      (with-current-buffer buf
3263        (let ((modified (buffer-modified-p)))
3264          (unwind-protect
3265              (let ((buffer-undo-list t)
3266                    (inhibit-read-only t)
3267                    (inhibit-point-motion-hooks t)
3268                    (inhibit-modification-hooks t)
3269                    deactivate-mark
3270                    buffer-file-name
3271                    buffer-file-truename)
3272                (put-text-property start end 'fontified t))
3273            (unless modified
3274              (restore-buffer-modified-p nil)))))))
3275
3276 ;;;--------------------------------------------------------------------------
3277 ;;; SGML hacking.
3278
3279 (defun mdw-sgml-mode ()
3280   (interactive)
3281   (sgml-mode)
3282   (mdw-standard-fill-prefix "")
3283   (make-local-variable 'sgml-delimiters)
3284   (setq sgml-delimiters
3285         '("AND" "&" "COM" "--" "CRO" "&#" "DSC" "]" "DSO" "[" "DTGC" "]"
3286           "DTGO" "[" "ERO" "&" "ETAGO" ":e" "GRPC" ")" "GRPO" "(" "LIT" "\""
3287           "LITA" "'" "MDC" ">" "MDO" "<!" "MINUS" "-" "MSC" "]]" "NESTC" "{"
3288           "NET" "}" "OPT" "?" "OR" "|" "PERO" "%" "PIC" ">" "PIO" "<?"
3289           "PLUS" "+" "REFC" "." "REP" "*" "RNI" "#" "SEQ" "," "STAGO" ":"
3290           "TAGC" "." "VI" "=" "MS-START" "<![" "MS-END" "]]>"
3291           "XML-ECOM" "-->" "XML-PIC" "?>" "XML-SCOM" "<!--" "XML-TAGCE" "/>"
3292           "NULL" ""))
3293   (setq major-mode 'mdw-sgml-mode)
3294   (setq mode-name "[mdw] SGML")
3295   (run-hooks 'mdw-sgml-mode-hook))
3296
3297 ;;;--------------------------------------------------------------------------
3298 ;;; Configuration files.
3299
3300 (defvar mdw-conf-quote-normal nil
3301   "*Control syntax category of quote characters `\"' and `''.
3302 If this is `t', consider quote characters to be normal
3303 punctuation, as for `conf-quote-normal'.  If this is `nil' then
3304 leave quote characters as quotes.  If this is a list, then
3305 consider the quote characters in the list to be normal
3306 punctuation.  If this is a single quote character, then consider
3307 that character only to be normal punctuation.")
3308 (defun mdw-conf-quote-normal-acceptable-value-p (value)
3309   "Is the VALUE is an acceptable value for `mdw-conf-quote-normal'?"
3310   (or (booleanp value)
3311       (every (lambda (v) (memq v '(?\" ?')))
3312              (if (listp value) value (list value)))))
3313 (put 'mdw-conf-quote-normal 'safe-local-variable
3314      'mdw-conf-quote-normal-acceptable-value-p)
3315
3316 (defun mdw-fix-up-quote ()
3317   "Apply the setting of `mdw-conf-quote-normal'."
3318   (let ((flag mdw-conf-quote-normal))
3319     (cond ((eq flag t)
3320            (conf-quote-normal t))
3321           ((not flag)
3322            nil)
3323           (t
3324            (let ((table (copy-syntax-table (syntax-table))))
3325              (mapc (lambda (ch) (modify-syntax-entry ch "." table))
3326                    (if (listp flag) flag (list flag)))
3327              (set-syntax-table table)
3328              (and font-lock-mode (font-lock-fontify-buffer)))))))
3329 (add-hook 'conf-mode-local-variables-hook 'mdw-fix-up-quote t t)
3330
3331 ;;;--------------------------------------------------------------------------
3332 ;;; Shell scripts.
3333
3334 (defun mdw-setup-sh-script-mode ()
3335
3336   ;; Fetch the shell interpreter's name.
3337   (let ((shell-name sh-shell-file))
3338
3339     ;; Try reading the hash-bang line.
3340     (save-excursion
3341       (goto-char (point-min))
3342       (if (looking-at "#![ \t]*\\([^ \t\n]*\\)")
3343           (setq shell-name (match-string 1))))
3344
3345     ;; Now try to set the shell.
3346     ;;
3347     ;; Don't let `sh-set-shell' bugger up my script.
3348     (let ((executable-set-magic #'(lambda (s &rest r) s)))
3349       (sh-set-shell shell-name)))
3350
3351   ;; Don't insert here-document scaffolding automatically.
3352   (local-set-key "<" 'self-insert-command)
3353
3354   ;; Now enable my keys and the fontification.
3355   (mdw-misc-mode-config)
3356
3357   ;; Set the indentation level correctly.
3358   (setq sh-indentation 2)
3359   (setq sh-basic-offset 2))
3360
3361 (setq sh-shell-file "/bin/sh")
3362
3363 ;; Awful hacking to override the shell detection for particular scripts.
3364 (defmacro define-custom-shell-mode (name shell)
3365   `(defun ,name ()
3366      (interactive)
3367      (set (make-local-variable 'sh-shell-file) ,shell)
3368      (sh-mode)))
3369 (define-custom-shell-mode bash-mode "/bin/bash")
3370 (define-custom-shell-mode rc-mode "/usr/bin/rc")
3371 (put 'sh-shell-file 'permanent-local t)
3372
3373 ;; Hack the rc syntax table.  Backquotes aren't paired in rc.
3374 (eval-after-load "sh-script"
3375   '(or (assq 'rc sh-mode-syntax-table-input)
3376        (let ((frag '(nil
3377                      ?# "<"
3378                      ?\n ">#"
3379                      ?\" "\"\""
3380                      ?\' "\"\'"
3381                      ?$ "'"
3382                      ?\` "."
3383                      ?! "_"
3384                      ?% "_"
3385                      ?. "_"
3386                      ?^ "_"
3387                      ?~ "_"
3388                      ?, "_"
3389                      ?= "."
3390                      ?< "."
3391                      ?> "."))
3392              (assoc (assq 'rc sh-mode-syntax-table-input)))
3393          (if assoc
3394              (rplacd assoc frag)
3395            (setq sh-mode-syntax-table-input
3396                  (cons (cons 'rc frag)
3397                        sh-mode-syntax-table-input))))))
3398
3399 ;;;--------------------------------------------------------------------------
3400 ;;; Emacs shell mode.
3401
3402 (defun mdw-eshell-prompt ()
3403   (let ((left "[") (right "]"))
3404     (when (= (user-uid) 0)
3405       (setq left "«" right "»"))
3406     (concat left
3407             (save-match-data
3408               (replace-regexp-in-string "\\..*$" "" (system-name)))
3409             " "
3410             (let* ((pwd (eshell/pwd)) (npwd (length pwd))
3411                    (home (expand-file-name "~")) (nhome (length home)))
3412               (if (and (>= npwd nhome)
3413                        (or (= nhome npwd)
3414                            (= (elt pwd nhome) ?/))
3415                        (string= (substring pwd 0 nhome) home))
3416                   (concat "~" (substring pwd (length home)))
3417                 pwd))
3418             right)))
3419 (setq eshell-prompt-function 'mdw-eshell-prompt)
3420 (setq eshell-prompt-regexp "^\\[[^]>]+\\(\\]\\|>>?\\)")
3421
3422 (defun eshell/e (file) (find-file file) nil)
3423 (defun eshell/ee (file) (find-file-other-window file) nil)
3424 (defun eshell/w3m (url) (w3m-goto-url url) nil)
3425
3426 (mdw-define-face eshell-prompt (t :weight bold))
3427 (mdw-define-face eshell-ls-archive (t :weight bold :foreground "red"))
3428 (mdw-define-face eshell-ls-backup (t :foreground "lightgrey" :slant italic))
3429 (mdw-define-face eshell-ls-product (t :foreground "lightgrey" :slant italic))
3430 (mdw-define-face eshell-ls-clutter (t :foreground "lightgrey" :slant italic))
3431 (mdw-define-face eshell-ls-executable (t :weight bold))
3432 (mdw-define-face eshell-ls-directory (t :foreground "cyan" :weight bold))
3433 (mdw-define-face eshell-ls-readonly (t nil))
3434 (mdw-define-face eshell-ls-symlink (t :foreground "cyan"))
3435
3436 ;;;--------------------------------------------------------------------------
3437 ;;; Messages-file mode.
3438
3439 (defun messages-mode-guts ()
3440   (setq messages-mode-syntax-table (make-syntax-table))
3441   (set-syntax-table messages-mode-syntax-table)
3442   (modify-syntax-entry ?0 "w" messages-mode-syntax-table)
3443   (modify-syntax-entry ?1 "w" messages-mode-syntax-table)
3444   (modify-syntax-entry ?2 "w" messages-mode-syntax-table)
3445   (modify-syntax-entry ?3 "w" messages-mode-syntax-table)
3446   (modify-syntax-entry ?4 "w" messages-mode-syntax-table)
3447   (modify-syntax-entry ?5 "w" messages-mode-syntax-table)
3448   (modify-syntax-entry ?6 "w" messages-mode-syntax-table)
3449   (modify-syntax-entry ?7 "w" messages-mode-syntax-table)
3450   (modify-syntax-entry ?8 "w" messages-mode-syntax-table)
3451   (modify-syntax-entry ?9 "w" messages-mode-syntax-table)
3452   (make-local-variable 'comment-start)
3453   (make-local-variable 'comment-end)
3454   (make-local-variable 'indent-line-function)
3455   (setq indent-line-function 'indent-relative)
3456   (mdw-standard-fill-prefix "\\([ \t]*\\(;\\|/?\\*\\)+[ \t]*\\)")
3457   (make-local-variable 'font-lock-defaults)
3458   (make-local-variable 'messages-mode-keywords)
3459   (let ((keywords
3460          (mdw-regexps "array" "bitmap" "callback" "docs[ \t]+enum"
3461                       "export" "enum" "fixed-octetstring" "flags"
3462                       "harmless" "map" "nested" "optional"
3463                       "optional-tagged" "package" "primitive"
3464                       "primitive-nullfree" "relaxed[ \t]+enum"
3465                       "set" "table" "tagged-optional"   "union"
3466                       "variadic" "vector" "version" "version-tag")))
3467     (setq messages-mode-keywords
3468           (list
3469            (list (concat "\\<\\(" keywords "\\)\\>:")
3470                  '(0 font-lock-keyword-face))
3471            '("\\([-a-zA-Z0-9]+:\\)" (0 font-lock-warning-face))
3472            '("\\(\\<[a-z][-_a-zA-Z0-9]*\\)"
3473              (0 font-lock-variable-name-face))
3474            '("\\<\\([0-9]+\\)\\>" (0 mdw-number-face))
3475            '("\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3476              (0 mdw-punct-face)))))
3477   (setq font-lock-defaults
3478         '(messages-mode-keywords nil nil nil nil))
3479   (run-hooks 'messages-file-hook))
3480
3481 (defun messages-mode ()
3482   (interactive)
3483   (fundamental-mode)
3484   (setq major-mode 'messages-mode)
3485   (setq mode-name "Messages")
3486   (messages-mode-guts)
3487   (modify-syntax-entry ?# "<" messages-mode-syntax-table)
3488   (modify-syntax-entry ?\n ">" messages-mode-syntax-table)
3489   (setq comment-start "# ")
3490   (setq comment-end "")
3491   (run-hooks 'messages-mode-hook))
3492
3493 (defun cpp-messages-mode ()
3494   (interactive)
3495   (fundamental-mode)
3496   (setq major-mode 'cpp-messages-mode)
3497   (setq mode-name "CPP Messages")
3498   (messages-mode-guts)
3499   (modify-syntax-entry ?* ". 23" messages-mode-syntax-table)
3500   (modify-syntax-entry ?/ ". 14" messages-mode-syntax-table)
3501   (setq comment-start "/* ")
3502   (setq comment-end " */")
3503   (let ((preprocessor-keywords
3504          (mdw-regexps "assert" "define" "elif" "else" "endif" "error"
3505                       "ident" "if" "ifdef" "ifndef" "import" "include"
3506                       "line" "pragma" "unassert" "undef" "warning")))
3507     (setq messages-mode-keywords
3508           (append (list (list (concat "^[ \t]*\\#[ \t]*"
3509                                       "\\(include\\|import\\)"
3510                                       "[ \t]*\\(<[^>]+\\(>\\|\\)\\)")
3511                               '(2 font-lock-string-face))
3512                         (list (concat "^\\([ \t]*#[ \t]*\\(\\("
3513                                       preprocessor-keywords
3514                                       "\\)\\>\\|[0-9]+\\|$\\)\\)")
3515                               '(1 font-lock-keyword-face)))
3516                   messages-mode-keywords)))
3517   (run-hooks 'cpp-messages-mode-hook))
3518
3519 (add-hook 'messages-mode-hook 'mdw-misc-mode-config t)
3520 (add-hook 'cpp-messages-mode-hook 'mdw-misc-mode-config t)
3521 ; (add-hook 'messages-file-hook 'mdw-fontify-messages t)
3522
3523 ;;;--------------------------------------------------------------------------
3524 ;;; Messages-file mode.
3525
3526 (defvar mallow-driver-substitution-face 'mallow-driver-substitution-face
3527   "Face to use for subsittution directives.")
3528 (make-face 'mallow-driver-substitution-face)
3529 (defvar mallow-driver-text-face 'mallow-driver-text-face
3530   "Face to use for body text.")
3531 (make-face 'mallow-driver-text-face)
3532
3533 (defun mallow-driver-mode ()
3534   (interactive)
3535   (fundamental-mode)
3536   (setq major-mode 'mallow-driver-mode)
3537   (setq mode-name "Mallow driver")
3538   (setq mallow-driver-mode-syntax-table (make-syntax-table))
3539   (set-syntax-table mallow-driver-mode-syntax-table)
3540   (make-local-variable 'comment-start)
3541   (make-local-variable 'comment-end)
3542   (make-local-variable 'indent-line-function)
3543   (setq indent-line-function 'indent-relative)
3544   (mdw-standard-fill-prefix "\\([ \t]*\\(;\\|/?\\*\\)+[ \t]*\\)")
3545   (make-local-variable 'font-lock-defaults)
3546   (make-local-variable 'mallow-driver-mode-keywords)
3547   (let ((keywords
3548          (mdw-regexps "each" "divert" "file" "if"
3549                       "perl" "set" "string" "type" "write")))
3550     (setq mallow-driver-mode-keywords
3551           (list
3552            (list (concat "^%\\s *\\(}\\|\\(" keywords "\\)\\>\\).*$")
3553                  '(0 font-lock-keyword-face))
3554            (list "^%\\s *\\(#.*\\|\\)$"
3555                  '(0 font-lock-comment-face))
3556            (list "^%"
3557                  '(0 font-lock-keyword-face))
3558            (list "^|?\\(.+\\)$" '(1 mallow-driver-text-face))
3559            (list "\\${[^}]*}"
3560                  '(0 mallow-driver-substitution-face t)))))
3561   (setq font-lock-defaults
3562         '(mallow-driver-mode-keywords nil nil nil nil))
3563   (modify-syntax-entry ?\" "_" mallow-driver-mode-syntax-table)
3564   (modify-syntax-entry ?\n ">" mallow-driver-mode-syntax-table)
3565   (setq comment-start "%# ")
3566   (setq comment-end "")
3567   (run-hooks 'mallow-driver-mode-hook))
3568
3569 (add-hook 'mallow-driver-hook 'mdw-misc-mode-config t)
3570
3571 ;;;--------------------------------------------------------------------------
3572 ;;; NFast debugs.
3573
3574 (defun nfast-debug-mode ()
3575   (interactive)
3576   (fundamental-mode)
3577   (setq major-mode 'nfast-debug-mode)
3578   (setq mode-name "NFast debug")
3579   (setq messages-mode-syntax-table (make-syntax-table))
3580   (set-syntax-table messages-mode-syntax-table)
3581   (make-local-variable 'font-lock-defaults)
3582   (make-local-variable 'nfast-debug-mode-keywords)
3583   (setq truncate-lines t)
3584   (setq nfast-debug-mode-keywords
3585         (list
3586          '("^\\(NFast_\\(Connect\\|Disconnect\\|Submit\\|Wait\\)\\)"
3587            (0 font-lock-keyword-face))
3588          (list (concat "^[ \t]+\\(\\("
3589                        "[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]"
3590                        "[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]"
3591                        "[ \t]+\\)*"
3592                        "[0-9a-fA-F]+\\)[ \t]*$")
3593            '(0 mdw-number-face))
3594          '("^[ \t]+\.status=[ \t]+\\<\\(OK\\)\\>"
3595            (1 font-lock-keyword-face))
3596          '("^[ \t]+\.status=[ \t]+\\<\\([a-zA-Z][0-9a-zA-Z]*\\)\\>"
3597            (1 font-lock-warning-face))
3598          '("^[ \t]+\.status[ \t]+\\<\\(zero\\)\\>"
3599            (1 nil))
3600          (list (concat "^[ \t]+\\.cmd=[ \t]+"
3601                        "\\<\\([a-zA-Z][0-9a-zA-Z]*\\)\\>")
3602            '(1 font-lock-keyword-face))
3603          '("-?\\<\\([0-9]+\\|0x[0-9a-fA-F]+\\)\\>" (0 mdw-number-face))
3604          '("^\\([ \t]+[a-z0-9.]+\\)" (0 font-lock-variable-name-face))
3605          '("\\<\\([a-z][a-z0-9.]+\\)\\>=" (1 font-lock-variable-name-face))
3606          '("\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)" (0 mdw-punct-face))))
3607   (setq font-lock-defaults
3608         '(nfast-debug-mode-keywords nil nil nil nil))
3609   (run-hooks 'nfast-debug-mode-hook))
3610
3611 ;;;--------------------------------------------------------------------------
3612 ;;; Other languages.
3613
3614 ;; Smalltalk.
3615
3616 (defun mdw-setup-smalltalk ()
3617   (and mdw-auto-indent
3618        (local-set-key "\C-m" 'smalltalk-newline-and-indent))
3619   (make-local-variable 'mdw-auto-indent)
3620   (setq mdw-auto-indent nil)
3621   (local-set-key "\C-i" 'smalltalk-reindent))
3622
3623 (defun mdw-fontify-smalltalk ()
3624   (make-local-variable 'font-lock-keywords)
3625   (setq font-lock-keywords
3626         (list
3627          (list "\\<[A-Z][a-zA-Z0-9]*\\>"
3628                '(0 font-lock-keyword-face))
3629          (list (concat "\\<0\\([xX][0-9a-fA-F_]+\\|[0-7_]+\\)\\|"
3630                        "[0-9][0-9_]*\\(\\.[0-9_]*\\|\\)"
3631                        "\\([eE]\\([-+]\\|\\)[0-9_]+\\|\\)")
3632                '(0 mdw-number-face))
3633          (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3634                '(0 mdw-punct-face)))))
3635
3636 ;; Lispy languages.
3637
3638 ;; Unpleasant bodge.
3639 (unless (boundp 'slime-repl-mode-map)
3640   (setq slime-repl-mode-map (make-sparse-keymap)))
3641
3642 (defun mdw-indent-newline-and-indent ()
3643   (interactive)
3644   (indent-for-tab-command)
3645   (newline-and-indent))
3646
3647 (eval-after-load "cl-indent"
3648   '(progn
3649      (mapc #'(lambda (pair)
3650                (put (car pair)
3651                     'common-lisp-indent-function
3652                     (cdr pair)))
3653       '((destructuring-bind . ((&whole 4 &rest 1) 4 &body))
3654         (multiple-value-bind . ((&whole 4 &rest 1) 4 &body))))))
3655
3656 (defun mdw-common-lisp-indent ()
3657   (make-local-variable 'lisp-indent-function)
3658   (setq lisp-indent-function 'common-lisp-indent-function))
3659
3660 (setq lisp-simple-loop-indentation 2
3661       lisp-loop-keyword-indentation 6
3662       lisp-loop-forms-indentation 6)
3663
3664 (defun mdw-fontify-lispy ()
3665
3666   ;; Set fill prefix.
3667   (mdw-standard-fill-prefix "\\([ \t]*;+[ \t]*\\)")
3668
3669   ;; Not much fontification needed.
3670   (make-local-variable 'font-lock-keywords)
3671   (setq font-lock-keywords
3672         (list (list (concat "\\("
3673                             "\\_<[-+]?"
3674                             "\\(" "[0-9]+/[0-9]+"
3675                             "\\|" "\\(" "[0-9]+" "\\(\\.[0-9]*\\)?" "\\|"
3676                                         "\\.[0-9]+" "\\)"
3677                                   "\\([dDeEfFlLsS][-+]?[0-9]+\\)?"
3678                             "\\)"
3679                             "\\|"
3680                             "#"
3681                             "\\(" "x" "[-+]?"
3682                                   "[0-9A-Fa-f]+" "\\(/[0-9A-Fa-f]+\\)?"
3683                             "\\|" "o" "[-+]?" "[0-7]+" "\\(/[0-7]+\\)?"
3684                             "\\|" "b" "[-+]?" "[01]+" "\\(/[01]+\\)?"
3685                             "\\|" "[0-9]+" "r" "[-+]?"
3686                                   "[0-9a-zA-Z]+" "\\(/[0-9a-zA-Z]+\\)?"
3687                             "\\)"
3688                             "\\)\\_>")
3689                     '(0 mdw-number-face))
3690               (list "\\(\\s.\\|\\s(\\|\\s)\\|\\s\\\\|\\s/\\)"
3691                     '(0 mdw-punct-face)))))
3692
3693 (defun comint-send-and-indent ()
3694   (interactive)
3695   (comint-send-input)
3696   (and mdw-auto-indent
3697        (indent-for-tab-command)))
3698
3699 (defun mdw-setup-m4 ()
3700
3701   ;; Inexplicably, Emacs doesn't match braces in m4 mode.  This is very
3702   ;; annoying: fix it.
3703   (modify-syntax-entry ?{ "(")
3704   (modify-syntax-entry ?} ")")
3705
3706   ;; Fill prefix.
3707   (mdw-standard-fill-prefix "\\([ \t]*\\(?:#+\\|\\<dnl\\>\\)[ \t]*\\)"))
3708
3709 ;;;--------------------------------------------------------------------------
3710 ;;; Text mode.
3711
3712 (defun mdw-text-mode ()
3713   (setq fill-column 72)
3714   (flyspell-mode t)
3715   (mdw-standard-fill-prefix
3716    "\\([ \t]*\\([>#|:] ?\\)*[ \t]*\\)" 3)
3717   (auto-fill-mode 1))
3718
3719 (eval-after-load "flyspell"
3720   '(define-key flyspell-mode-map "\C-\M-i" nil))
3721
3722 ;;;--------------------------------------------------------------------------
3723 ;;; Outline and hide/show modes.
3724
3725 (defun mdw-outline-collapse-all ()
3726   "Completely collapse everything in the entire buffer."
3727   (interactive)
3728   (save-excursion
3729     (goto-char (point-min))
3730     (while (< (point) (point-max))
3731       (hide-subtree)
3732       (forward-line))))
3733
3734 (setq hs-hide-comments-when-hiding-all nil)
3735
3736 (defadvice hs-hide-all (after hide-first-comment activate)
3737   (save-excursion (hs-hide-initial-comment-block)))
3738
3739 ;;;--------------------------------------------------------------------------
3740 ;;; Shell mode.
3741
3742 (defun mdw-sh-mode-setup ()
3743   (local-set-key [?\C-a] 'comint-bol)
3744   (add-hook 'comint-output-filter-functions
3745             'comint-watch-for-password-prompt))
3746
3747 (defun mdw-term-mode-setup ()
3748   (setq term-prompt-regexp shell-prompt-pattern)
3749   (make-local-variable 'mouse-yank-at-point)
3750   (make-local-variable 'transient-mark-mode)
3751   (setq mouse-yank-at-point t)
3752   (auto-fill-mode -1)
3753   (setq tab-width 8))
3754
3755 (defun term-send-meta-right () (interactive) (term-send-raw-string "\e\e[C"))
3756 (defun term-send-meta-left  () (interactive) (term-send-raw-string "\e\e[D"))
3757 (defun term-send-ctrl-uscore () (interactive) (term-send-raw-string "\C-_"))
3758 (defun term-send-meta-meta-something ()
3759   (interactive)
3760   (term-send-raw-string "\e\e")
3761   (term-send-raw))
3762 (eval-after-load 'term
3763   '(progn
3764      (define-key term-raw-map [?\e ?\e] nil)
3765      (define-key term-raw-map [?\e ?\e t] 'term-send-meta-meta-something)
3766      (define-key term-raw-map [?\C-/] 'term-send-ctrl-uscore)
3767      (define-key term-raw-map [M-right] 'term-send-meta-right)
3768      (define-key term-raw-map [?\e ?\M-O ?C] 'term-send-meta-right)
3769      (define-key term-raw-map [M-left] 'term-send-meta-left)
3770      (define-key term-raw-map [?\e ?\M-O ?D] 'term-send-meta-left)))
3771
3772 (defadvice term-exec (before program-args-list compile activate)
3773   "If the PROGRAM argument is a list, interpret it as (PROGRAM . SWITCHES).
3774 This allows you to pass a list of arguments through `ansi-term'."
3775   (let ((program (ad-get-arg 2)))
3776     (if (listp program)
3777         (progn
3778           (ad-set-arg 2 (car program))
3779           (ad-set-arg 4 (cdr program))))))
3780
3781 (defun ssh (host)
3782   "Open a terminal containing an ssh session to the HOST."
3783   (interactive "sHost: ")
3784   (ansi-term (list "ssh" host) (format "ssh@%s" host)))
3785
3786 (defvar git-grep-command
3787   "env PAGER=cat git grep --no-color -nH -e "
3788   "*The default command for \\[git-grep].")
3789
3790 (defvar git-grep-history nil)
3791
3792 (defun git-grep (command-args)
3793   "Run `git grep' with user-specified args and collect output in a buffer."
3794   (interactive
3795    (list (read-shell-command "Run git grep (like this): "
3796                              git-grep-command 'git-grep-history)))
3797   (grep command-args))
3798
3799 ;;;--------------------------------------------------------------------------
3800 ;;; Magit configuration.
3801
3802 (setq magit-diff-refine-hunk 'all
3803       magit-view-git-manual-method 'man
3804       magit-log-margin '(nil age magit-log-margin-width t 18)
3805       magit-wip-after-save-local-mode-lighter ""
3806       magit-wip-after-apply-mode-lighter ""
3807       magit-wip-before-change-mode-lighter "")
3808 (eval-after-load "magit"
3809   '(progn (global-magit-file-mode 1)
3810           (magit-wip-after-save-mode 1)
3811           (magit-wip-after-apply-mode 1)
3812           (magit-wip-before-change-mode 1)
3813           (add-to-list 'magit-no-confirm 'safe-with-wip)
3814           (push '(:eval (if (or magit-wip-after-save-local-mode
3815                                 magit-wip-after-apply-mode
3816                                 magit-wip-before-change-mode)
3817                             (format " wip:%s%s%s"
3818                                     (if magit-wip-after-apply-mode "A" "")
3819                                     (if magit-wip-before-change-mode "C" "")
3820                                     (if magit-wip-after-save-local-mode "S" ""))))
3821                 minor-mode-alist)
3822           (dolist (popup '(magit-diff-popup
3823                            magit-diff-refresh-popup
3824                            magit-diff-mode-refresh-popup
3825                            magit-revision-mode-refresh-popup))
3826             (magit-define-popup-switch popup ?R "Reverse diff" "-R"))))
3827
3828 (setq magit-repolist-columns
3829       '(("Name" 16 magit-repolist-column-ident nil)
3830         ("Version" 18 magit-repolist-column-version nil)
3831         ("St" 2 magit-repolist-column-dirty nil)
3832         ("L<U" 3 mdw-repolist-column-unpulled-from-upstream nil)
3833         ("L>U" 3 mdw-repolist-column-unpushed-to-upstream nil)
3834         ("Path" 32 magit-repolist-column-path nil)))
3835
3836 (setq magit-repository-directories '(("~/etc/profile" . 0)
3837                                      ("~/src/" . 1)))
3838
3839 (defadvice magit-list-repos (around mdw-dirname () activate compile)
3840   "Make sure the returned names are directory names.
3841 Otherwise child processes get started in the wrong directory and
3842 there is sadness."
3843   (setq ad-return-value (mapcar #'file-name-as-directory ad-do-it)))
3844
3845 (defun mdw-repolist-column-unpulled-from-upstream (_id)
3846   "Insert number of upstream commits not in the current branch."
3847   (let ((upstream (magit-get-upstream-branch (magit-get-current-branch) t)))
3848     (and upstream
3849          (let ((n (cadr (magit-rev-diff-count "HEAD" upstream))))
3850            (propertize (number-to-string n) 'face
3851                        (if (> n 0) 'bold 'shadow))))))
3852
3853 (defun mdw-repolist-column-unpushed-to-upstream (_id)
3854   "Insert number of commits in the current branch but not its upstream."
3855   (let ((upstream (magit-get-upstream-branch (magit-get-current-branch) t)))
3856     (and upstream
3857          (let ((n (car (magit-rev-diff-count "HEAD" upstream))))
3858            (propertize (number-to-string n) 'face
3859                        (if (> n 0) 'bold 'shadow))))))
3860
3861 ;;;--------------------------------------------------------------------------
3862 ;;; MPC configuration.
3863
3864 (eval-when-compile (trap (require 'mpc)))
3865
3866 (setq mpc-browser-tags '(Artist|Composer|Performer Album|Playlist))
3867
3868 (defun mdw-mpc-now-playing ()
3869   (interactive)
3870   (require 'mpc)
3871   (save-excursion
3872     (set-buffer (mpc-proc-cmd (mpc-proc-cmd-list '("status" "currentsong"))))
3873     (mpc--status-callback))
3874   (let ((state (cdr (assq 'state mpc-status))))
3875     (cond ((member state '("stop"))
3876            (message "mpd stopped."))
3877           ((member state '("play" "pause"))
3878            (let* ((artist (cdr (assq 'Artist mpc-status)))
3879                   (album (cdr (assq 'Album mpc-status)))
3880                   (title (cdr (assq 'Title mpc-status)))
3881                   (file (cdr (assq 'file mpc-status)))
3882                   (duration-string (cdr (assq 'Time mpc-status)))
3883                   (time-string (cdr (assq 'time mpc-status)))
3884                   (time (and time-string
3885                              (string-to-number
3886                               (if (string-match ":" time-string)
3887                                   (substring time-string
3888                                              0 (match-beginning 0))
3889                                 (time-string)))))
3890                   (duration (and duration-string
3891                                  (string-to-number duration-string)))
3892                   (pos (and time duration
3893                             (format " [%d:%02d/%d:%02d]"
3894                                     (/ time 60) (mod time 60)
3895                                     (/ duration 60) (mod duration 60))))
3896                   (fmt (cond ((and artist title)
3897                               (format "`%s' by %s%s" title artist
3898                                       (if album (format ", from `%s'" album)
3899                                         "")))
3900                              (file
3901                               (format "`%s' (no tags)" file))
3902                              (t
3903                               "(no idea what's playing!)"))))
3904              (if (string= state "play")
3905                  (message "mpd playing %s%s" fmt (or pos ""))
3906                (message "mpd paused in %s%s" fmt (or pos "")))))
3907           (t
3908            (message "mpd in unknown state `%s'" state)))))
3909
3910 (defmacro mdw-define-mpc-wrapper (func bvl interactive &rest body)
3911   `(defun ,func ,bvl
3912      (interactive ,@interactive)
3913      (require 'mpc)
3914      ,@body
3915      (mdw-mpc-now-playing)))
3916
3917 (mdw-define-mpc-wrapper mdw-mpc-play-or-pause () nil
3918   (if (member (cdr (assq 'state (mpc-cmd-status))) '("play"))
3919       (mpc-pause)
3920     (mpc-play)))
3921
3922 (mdw-define-mpc-wrapper mdw-mpc-next () nil (mpc-next))
3923 (mdw-define-mpc-wrapper mdw-mpc-prev () nil (mpc-prev))
3924 (mdw-define-mpc-wrapper mdw-mpc-stop () nil (mpc-stop))
3925
3926 (defun mdw-mpc-louder (step)
3927   (interactive (list (if current-prefix-arg
3928                          (prefix-numeric-value current-prefix-arg)
3929                        +10)))
3930   (mpc-proc-cmd (format "volume %+d" step)))
3931
3932 (defun mdw-mpc-quieter (step)
3933   (interactive (list (if current-prefix-arg
3934                          (prefix-numeric-value current-prefix-arg)
3935                        +10)))
3936   (mpc-proc-cmd (format "volume %+d" (- step))))
3937
3938 (defun mdw-mpc-hack-lines (arg interactivep func)
3939   (if (and interactivep (use-region-p))
3940       (let ((from (region-beginning)) (to (region-end)))
3941         (goto-char from)
3942         (beginning-of-line)
3943         (funcall func)
3944         (forward-line)
3945         (while (< (point) to)
3946           (funcall func)
3947           (forward-line)))
3948     (let ((n (prefix-numeric-value arg)))
3949       (cond ((minusp n)
3950              (unless (bolp)
3951                (beginning-of-line)
3952                (funcall func)
3953                (incf n))
3954              (while (minusp n)
3955                (forward-line -1)
3956                (funcall func)
3957                (incf n)))
3958             (t
3959              (beginning-of-line)
3960              (while (plusp n)
3961                (funcall func)
3962                (forward-line)
3963                (decf n)))))))
3964
3965 (defun mdw-mpc-select-one ()
3966   (when (and (get-char-property (point) 'mpc-file)
3967              (not (get-char-property (point) 'mpc-select)))
3968     (mpc-select-toggle)))
3969
3970 (defun mdw-mpc-unselect-one ()
3971   (when (get-char-property (point) 'mpc-select)
3972     (mpc-select-toggle)))
3973
3974 (defun mdw-mpc-select (&optional arg interactivep)
3975   (interactive (list current-prefix-arg t))
3976   (mdw-mpc-hack-lines arg interactivep 'mdw-mpc-select-one))
3977
3978 (defun mdw-mpc-unselect (&optional arg interactivep)
3979   (interactive (list current-prefix-arg t))
3980   (mdw-mpc-hack-lines arg interactivep 'mdw-mpc-unselect-one))
3981
3982 (defun mdw-mpc-unselect-backwards (arg)
3983   (interactive "p")
3984   (mdw-mpc-hack-lines (- arg) t 'mdw-mpc-unselect-one))
3985
3986 (defun mdw-mpc-unselect-all ()
3987   (interactive)
3988   (setq mpc-select nil)
3989   (mpc-selection-refresh))
3990
3991 (defun mdw-mpc-next-line (arg)
3992   (interactive "p")
3993   (beginning-of-line)
3994   (forward-line arg))
3995
3996 (defun mdw-mpc-previous-line (arg)
3997   (interactive "p")
3998   (beginning-of-line)
3999   (forward-line (- arg)))
4000
4001 (defun mdw-mpc-playlist-add (&optional arg interactivep)
4002   (interactive (list current-prefix-arg t))
4003   (let ((mpc-select mpc-select))
4004     (when (or arg (and interactivep (use-region-p)))
4005       (setq mpc-select nil)
4006       (mdw-mpc-hack-lines arg interactivep 'mdw-mpc-select-one))
4007     (setq mpc-select (reverse mpc-select))
4008     (mpc-playlist-add)))
4009
4010 (defun mdw-mpc-playlist-delete (&optional arg interactivep)
4011   (interactive (list current-prefix-arg t))
4012   (setq mpc-select (nreverse mpc-select))
4013   (mpc-select-save
4014     (when (or arg (and interactivep (use-region-p)))
4015       (setq mpc-select nil)
4016       (mpc-selection-refresh)
4017       (mdw-mpc-hack-lines arg interactivep 'mdw-mpc-select-one))
4018       (mpc-playlist-delete)))
4019
4020 (defun mdw-mpc-hack-tagbrowsers ()
4021   (setq-local mode-line-format
4022               '("%e"
4023                 mode-line-frame-identification
4024                 mode-line-buffer-identification)))
4025 (add-hook 'mpc-tagbrowser-mode-hook 'mdw-mpc-hack-tagbrowsers)
4026
4027 (defun mdw-mpc-hack-songs ()
4028   (setq-local header-line-format
4029               ;; '("MPC " mpc-volume " " mpc-current-song)
4030               (list (propertize " " 'display '(space :align-to 0))
4031                     ;; 'mpc-songs-format-description
4032                     '(:eval
4033                       (let ((deactivate-mark) (hscroll (window-hscroll)))
4034                         (with-temp-buffer
4035                           (mpc-format mpc-songs-format 'self hscroll)
4036                           ;; That would be simpler than the hscroll handling in
4037                           ;; mpc-format, but currently move-to-column does not
4038                           ;; recognize :space display properties.
4039                           ;; (move-to-column hscroll)
4040                           ;; (delete-region (point-min) (point))
4041                           (buffer-string)))))))
4042 (add-hook 'mpc-songs-mode-hook 'mdw-mpc-hack-songs)
4043
4044 (eval-after-load "mpc"
4045   '(progn
4046      (define-key mpc-mode-map "m" 'mdw-mpc-select)
4047      (define-key mpc-mode-map "u" 'mdw-mpc-unselect)
4048      (define-key mpc-mode-map "\177" 'mdw-mpc-unselect-backwards)
4049      (define-key mpc-mode-map "\e\177" 'mdw-mpc-unselect-all)
4050      (define-key mpc-mode-map "n" 'mdw-mpc-next-line)
4051      (define-key mpc-mode-map "p" 'mdw-mpc-previous-line)
4052      (define-key mpc-mode-map "/" 'mpc-songs-search)
4053      (setq mpc-songs-mode-map (make-sparse-keymap))
4054      (set-keymap-parent mpc-songs-mode-map mpc-mode-map)
4055      (define-key mpc-songs-mode-map "l" 'mpc-playlist)
4056      (define-key mpc-songs-mode-map "+" 'mdw-mpc-playlist-add)
4057      (define-key mpc-songs-mode-map "-" 'mdw-mpc-playlist-delete)
4058      (define-key mpc-songs-mode-map "\r" 'mpc-songs-jump-to)))
4059
4060 ;;;--------------------------------------------------------------------------
4061 ;;; Inferior Emacs Lisp.
4062
4063 (setq comint-prompt-read-only t)
4064
4065 (eval-after-load "comint"
4066   '(progn
4067      (define-key comint-mode-map "\C-w" 'comint-kill-region)
4068      (define-key comint-mode-map [C-S-backspace] 'comint-kill-whole-line)))
4069
4070 (eval-after-load "ielm"
4071   '(progn
4072      (define-key ielm-map "\C-w" 'comint-kill-region)
4073      (define-key ielm-map [C-S-backspace] 'comint-kill-whole-line)))
4074
4075 ;;;----- That's all, folks --------------------------------------------------
4076
4077 (provide 'dot-emacs)