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