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