Update.
[elisp.git] / emacs.el
1 ;; -*- mode: Emacs-Lisp; mode: rainbow; -*-
2
3 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4 ;; This program is free software; you can redistribute it and/or         ;;
5 ;; modify it under the terms of the GNU General Public License as        ;;
6 ;; published by the Free Software Foundation; either version 3, or (at   ;;
7 ;; your option) any later version.                                       ;;
8 ;;                                                                       ;;
9 ;; This program is distributed in the hope that it will be useful, but   ;;
10 ;; WITHOUT ANY WARRANTY; without even the implied warranty of            ;;
11 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      ;;
12 ;; General Public License for more details.                              ;;
13 ;;                                                                       ;;
14 ;; You should have received a copy of the GNU General Public License     ;;
15 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.  ;;
16 ;;                                                                       ;;
17 ;; Written by and Copyright (C) Francois Fleuret                         ;;
18 ;; Contact <francois@fleuret.org> for comments & bug reports             ;;
19 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
20
21 ;; It's better to set the preferences in the .Xresources so that the
22 ;; window is not first displayed with the wrong options
23
24 ;; Emacs.menuBar:            off
25 ;; Emacs.verticalScrollBars: off
26 ;; Emacs.toolBar:            off
27 ;; Emacs.internalBorder:     1
28 ;; Emacs.FontBackend: xft
29 ;; Xft.dpi: 96
30 ;; Xft.hinting: true
31 ;; Xft.antialias: true
32 ;; Xft.rgba: rgb
33
34 ;; Give the focus to the emacs window if we are under a windowing
35 ;; system
36
37 (when window-system
38   ;; (x-focus-frame nil)
39   (set-mouse-pixel-position (selected-frame) 4 4))
40
41 ;; Where I keep my own scripts
42
43 (add-to-list 'load-path "~/sources/gpl/elisp")
44 (add-to-list 'load-path "~/sources/elisp")
45 (add-to-list 'load-path "~/local/elisp")
46
47 ;; No, I do not like menus
48 (menu-bar-mode -1)
49
50 ;; Nor fringes
51 ;; (when (functionp 'fringe-mode) (fringe-mode '(0 . 0)))
52 ;; (when (functionp 'fringe-mode) (fringe-mode '(0 . 1)))
53
54 ;; And I do not like scrollbar neither
55 (when (functionp 'scroll-bar-mode) (scroll-bar-mode -1))
56
57 ;; Make all "yes or no" prompts be "y or n" instead
58 (fset 'yes-or-no-p 'y-or-n-p)
59
60 ;; Show the matching parenthesis and do it immediately, we are in a
61 ;; hurry
62 (setq show-paren-delay 0)
63 (show-paren-mode t)
64
65 ;; use colorization for all modes
66 (global-font-lock-mode t)
67
68 (setq font-lock-maximum-decoration 3
69       ;;'((latex-mode . 2) (t . 2))
70       )
71
72 ;; Activate the dynamic completion of buffer names
73 (iswitchb-mode 1)
74
75 ;; Save the minibuffer history
76 (setq savehist-file "~/private/emacs/savehist")
77 (when (functionp 'savehist-mode) (savehist-mode 1))
78
79 ;; And allow minibuffer recursion
80 (setq enable-recursive-minibuffers t)
81 (minibuffer-depth-indicate-mode 1)
82
83 ;; I do not like tooltips
84 (when (functionp 'tooltip-mode) (tooltip-mode nil))
85
86 ;; Activate the dynamic completion in the mini-buffer
87 (icomplete-mode 1)
88
89 ;; (setq highlight-current-line-globally t
90 ;; highlight-current-line-ignore-regexp "Faces\\|Colors\\| \\*Mini\\|\\*media\\|INBOX")
91
92 ;; (highlight-current-line-minor-mode 1)
93 ;; (highlight-current-line-set-bg-color "gray75")
94
95 (defun ff/compile-when-needed (name)
96   "Compiles the given file only if needed. Adds .el if required, and
97 uses `load-path' to find it."
98   (if (not (string-match "\.el$" name))
99       (ff/compile-when-needed (concat name ".el"))
100     (mapc (lambda (dir)
101             (let* ((src (concat dir "/" name)))
102               (when (file-newer-than-file-p src (concat src "c"))
103                 (if (let ((byte-compile-verbose nil))
104                       (condition-case nil
105                           (byte-compile-file src)
106                         (error nil)))
107                     (message (format "Compiled %s" src ))
108                   (message (format "Failed compilation of %s" src))))))
109           load-path)))
110
111 ;; This is useful when using the same .emacs in many places
112
113 (defun ff/load-or-alert (name &optional compile-when-needed)
114   "Tries to load the specified file and insert a warning message in a
115 load-warning buffer in case of failure."
116
117   (when compile-when-needed (ff/compile-when-needed name))
118
119   (if (load name t nil) t
120     (let ((buf (get-buffer-create "*loading warnings*")))
121       (display-buffer buf)
122       (set-buffer buf)
123       (insert (propertize "Warning:" 'face 'font-lock-warning-face) " could not load '" name "'\n")
124       (fit-window-to-buffer (get-buffer-window buf))
125       (set-buffer-modified-p nil))
126     nil))
127
128 ;; This is the default in emacs 22.1 and later
129 ;; (auto-compression-mode 1)
130
131 ;; make emacs use the clipboard so that copy/paste works for other
132 ;; x-programs. I have no clue how all that clipboard thing works.
133
134 ;; (setq x-select-enable-clipboard t)
135 ;; (setq interprogram-paste-function 'x-cut-buffer-or-selection-value)
136 ;; (setq x-select-enable-primary t)
137 ;; (setq x-select-enable-clipboard t)
138 ;; (global-set-key "\C-y" 'clipboard-yank)
139
140 (setq
141
142  message-log-max 1000
143
144  ;; avoid GC as much as possible
145  gc-cons-threshold 2500000
146
147  ;; no startup message
148  inhibit-startup-screen t
149
150  ;; no message in the scratch buffer
151  initial-scratch-message nil
152
153  ;; do not fill my buffers, you fool
154  next-line-add-newlines nil
155
156  ;; keep the window focused on the messages during compilation
157  compilation-scroll-output t
158
159  ;; Keep the highlight on the compilation error
160  next-error-highlight t
161
162  ;; blink the screen instead of beeping
163  ;; visible-bell t
164
165  ;; take the CR when killing a line
166  kill-whole-line t
167
168  ;; I prefer to move between lines as defined in the buffer, not
169  ;; visually
170  line-move-visual nil
171
172  ;; I comment empty lines, too (does not seem to work, though)
173  comment-empty-lines t
174
175  ;; We want long lines to be truncated instead of displayed on several lines
176  ;; truncate-lines t
177  ;; Show all lines, even if the window is not as large as the frame
178  ;; truncate-partial-width-windows nil
179  ;; truncate-partial-width-windows t
180
181  ;; Do not keep tracks of the autosaved files
182  auto-save-list-file-prefix nil
183
184  ;; Show me empty lines at the end of the buffer
185  default-indicate-empty-lines t
186
187  ;; Show me the region until I do something on it
188  transient-mark-mode t
189
190  ;; Do not color stuff which are clickable when hovering over it
191  mouse-highlight nil
192
193  ;; Don't bother me with questions even if "unsafe" local variables
194  ;; are set
195  enable-local-variables :all
196
197  ;; I have no problem with small windows
198  window-min-height 1
199
200  ;; I am not a fan of develock
201  develock-auto-enable nil
202
203  ;; I do not like women to open windows
204  woman-use-own-frame nil
205
206  ;; I am not that paranoid, contrary to what you think
207  epa-file-cache-passphrase-for-symmetric-encryption t
208  ;; And I like ascii files
209  epa-armor t
210
211  tramp-default-method "ssh"
212
213  ;; I have no problem with files having their own local variables
214  enable-local-eval t
215
216  mail-from-style 'angles
217  browse-url-mozilla-program "firefox"
218  mc-encrypt-for-me t
219  mc-use-default-recipients t
220
221  ;; browse-url-new-window-flag t
222  )
223
224 ;; The backups
225
226 (setq
227  temporary-file-directory "/tmp/"
228  vc-make-backup-files t
229  backup-directory-alist '((".*" . "~/misc/emacs.backups/"))
230  version-control t ;; Use backup files with numbers
231  kept-new-versions 10
232  kept-old-versions 2
233  delete-old-versions t
234  backup-by-copying-when-linked t
235  )
236
237 (setq tramp-backup-directory-alist backup-directory-alist)
238
239 (setq user-emacs-directory "~/misc/emacs.d/")
240
241 (setq
242  abbrev-file-name (concat user-emacs-directory "abbrev_defs")
243  server-auth-dir (concat user-emacs-directory "server/")
244  custom-theme-directory user-emacs-directory
245  )
246
247 ;; Stop this crazy blinking cursor
248 (blink-cursor-mode 0)
249
250 ;; (setq blink-cursor-delay 0.25
251 ;; blink-cursor-interval 0.25)
252
253 ;; (set-terminal-coding-system 'utf-8)
254
255 ;; (unless window-system
256 ;; (xterm-mouse-mode 1)
257 ;;   (if (string= (getenv "TERM") "xterm-256color")
258 ;;       (ff/load-or-alert "xterm-256color" t))
259 ;; )
260
261 (setq-default
262
263  ;; Show white spaces at the end of lines
264  show-trailing-whitespace t
265
266  ;; Do not show the cursor in non-active window
267  cursor-in-non-selected-windows nil
268
269  use-dialog-box nil
270  use-file-dialog nil
271
272  ;; when on a TAB, the cursor has the TAB length
273  x-stretch-cursor t
274
275  ;; This is the default coding system when toggle-input-method is
276  ;; invoked (C-\)
277  default-input-method "latin-1-prefix"
278  ;; do not put tabs when indenting
279  indent-tabs-mode nil
280  ;; And yes, we have a fast display / connection / whatever
281  baud-rate 524288
282  ;; baud-rate 10
283
284  ;; To keep the cursor always visible when it moves (thanks
285  ;; snogglethrop!)
286  redisplay-dont-pause t
287
288  ;; I want to see the keys I type instantaneously
289  echo-keystrokes 0.1
290  )
291
292 ;; Show the column number
293 (column-number-mode 1)
294
295 ;; What modes for what file extentions
296 (add-to-list 'auto-mode-alist '("\\.h\\'" . c++-mode))
297
298 (require 'org-table)
299
300 (add-to-list 'auto-mode-alist '("\\.txt\\'" . (lambda()
301                                                 (text-mode)
302                                                 (orgtbl-mode)
303                                                 (auto-fill-mode)
304                                                 (flyspell-mode))))
305
306 (add-hook 'c++-mode-hook 'flyspell-prog-mode)
307 (add-hook 'log-edit-mode-hook 'flyspell-mode)
308
309 ;; I am a power-user
310
311 (put 'narrow-to-region 'disabled nil)
312 (put 'upcase-region 'disabled nil)
313 (put 'downcase-region 'disabled nil)
314 ;; (put 'scroll-left 'disabled nil)
315 ;; (put 'scroll-right 'disabled nil)
316
317 ;; My selector is clearer than that
318 ;; (when (load "ido" t) (ido-mode t))
319
320 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
321
322 ;; Makes buffer names more explicit then <2>, <3> etc. when there are
323 ;; several identical filenames
324
325 (when (load "uniquify" t)
326   (setq uniquify-buffer-name-style 'post-forward-angle-brackets))
327
328 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
329 ;; Appearance
330 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
331
332 (when (boundp 'x-display-name)
333
334   (setq-default
335
336    ;; If the display is :0.0, we make the assumption that we are
337    ;; running the emacs locally, and we do not show the
338    ;; hostname. Otherwise, show @host.
339
340    frame-title-format (concat "emacs" ;;invocation-name
341                               (unless (string= x-display-name ":0.0")
342                                 (concat "@" system-name))
343                               " (%b)")
344
345    ;; Use the same for the icone
346
347    icon-title-format frame-title-format
348    ))
349
350 ;; "tool" bar? Are you kidding?
351 (when (fboundp 'tool-bar-mode) (tool-bar-mode -1))
352
353 ;; ;; If my own letter icon is here, use it and change its color
354 ;; (when (file-exists-p "~/local/share/emacs/letter.xbm")
355 ;; (setq-default display-time-mail-icon
356 ;; (find-image
357 ;; '((:type xbm
358 ;; :file "~/local/share/emacs/letter.xbm"
359 ;; :ascent center)))))
360
361 ;; My funky setting of face colors. Basically, we switch to a sober
362 ;; look and darken a bit the colors which need to (because of the
363 ;; darker background)
364
365 (defun ff/configure-faces (fl)
366   "Set face attributes and create faces when necessary"
367   (mapc (lambda (f)
368           (unless (boundp (car f)) (make-empty-face (car f)))
369           (eval `(set-face-attribute (car f) nil ,@(cdr f))))
370         fl))
371
372 ;; Not the same in xterm (which is gray in my case) and in
373 ;; X-window
374
375 (unless window-system
376   ;;     (xterm-mouse-mode 1)
377   (ff/configure-faces
378    '((italic :underline nil)
379      (info-title-2 :foreground "green")
380      (cperl-array-face :background "gray90" :foreground "blue" :weight 'bold)
381      (cperl-hash-face :background "gray90" :foreground "purple" :weight 'bold)
382      (diff-added :background "gray90" :foreground "green4" :weight 'bold)
383      (diff-removed :background "gray90" :foreground "red2" :weight 'bold)
384      (diff-changed :background "gray90" :foreground "blue" :weight 'bold)
385      (diff-file-header-face :background "white" :foreground "black"
386                             :weight 'bold)
387      (diff-header-face :background "white" :foreground "black")
388      (diff-hunk-header-face :background "white" :foreground "black")
389      (diff-indicator-removed :foreground "red" :weight 'bold)
390      (diff-removed :foreground "red" :weight 'bold)
391      (diff-indicator-added :foreground "blue" :weight 'bold)
392      (diff-added :foreground "blue" :weight 'bold)
393      (font-lock-string-face :foreground "green")
394      (font-lock-variable-name-face :foreground "blue")
395      (font-lock-constant-face :foreground "blue")
396      (font-lock-function-name-face :foreground "blue")
397      (font-lock-preprocessor-face :foreground "green")
398      (font-lock-function-name-face :foreground "cyan")
399      (flyspell-incorrect-face :foreground "red2")
400      (flyspell-duplicate-face :foreground "OrangeRed2")
401      (hl-line :background "white")
402      (sh-heredoc :foreground "black" :background "#fff0f0")
403      (sh-heredoc-face :foreground "black" :background "#fff0f0")
404      (font-lock-keyword-face :foreground "blue")
405      (highlight :background "darkseagreen3")
406      (isearch :background "orange" :foreground "black")
407      (isearch-lazy-highlight-face' :background "yellow" :foreground "black")
408      ;; (display-time-mail-face :background "white")
409      (show-paren-match-face :background "gold" :foreground "black")
410      (show-paren-mismatch-face :background "red" :foreground "black")
411      (trailing-whitespace :background "white")
412      (mode-line :background "cornflowerblue" :foreground "black" :box nil
413                 :inverse-video nil)
414      (header-line :background "cornflowerblue" :foreground "black" :box nil
415                   :inverse-video nil)
416      (mode-line-inactive :background "gray60" :foreground "black" :box nil
417                          :inverse-video nil)
418      (region :background "springgreen2")
419      (ff/date-info-face :foreground "white" :weight 'bold)
420      (ff/mail-alarm-face :foreground "red" :weight 'bold)
421      (gui-button-face :background "green" :foreground "white")
422      (enotes/information-face :foreground "cyan")
423      ))
424   )
425
426 ;; (list-colors-display (mapcar 'car color-name-rgb-alist))
427
428 ;; (ff/configure-faces '((default :background "black" :foreground "gray80")))
429 ;; (ff/configure-faces '((default :background "gray80" :foreground "black")))
430
431 (when window-system
432   ;; (setq
433   ;; display-time-use-mail-icon t)
434
435   (ff/configure-faces
436    '(
437      ;; (escape-glyph :foreground "#c0c0c0" :weight 'bold)
438
439      (escape-glyph :foreground "green3" :weight 'bold)
440      (default :background "gray90" :foreground "black")
441      (cperl-array-face :background "gray90" :foreground "blue" :weight 'bold)
442      (cperl-hash-face :background "gray90" :foreground "purple" :weight 'bold)
443      (message-cited-text :foreground "red4")
444      (diff-mode :background "gray90" :weight 'bold)
445      (diff-added :background "gray90" :foreground "green4" :weight 'bold)
446      (diff-removed :background "gray90" :foreground "red2" :weight 'bold)
447      (diff-changed :background "gray90" :foreground "blue" :weight 'bold)
448      (diff-file-header :background "white" :foreground "black"
449                        :weight 'bold)
450      (diff-header :background "white" :foreground "black")
451      (diff-hunk-header :background "white" :foreground "black")
452      (font-lock-builtin-face :foreground "deeppink3")
453      (font-lock-string-face :foreground "dark olive green")
454      (font-lock-variable-name-face :foreground "sienna")
455      (font-lock-function-name-face :foreground "blue4" :weight 'bold)
456      ;; (font-lock-comment-delimiter-face :foreground "dark violet")
457      ;; (font-lock-comment-face :foreground "dark violet")
458      (flyspell-incorrect-face :foreground "red2")
459      (flyspell-duplicate-face :foreground "OrangeRed2")
460      (hl-line :background "white")
461      (sh-heredoc :foreground "black" :background "#fff0f0")
462      (sh-heredoc-face :foreground "black" :background "#fff0f0")
463      (header-line :background "gray65")
464      (highlight :background "turquoise")
465      (message-cited-text-face :foreground "firebrick")
466      (isearch :background "yellow" :foreground "black")
467      (isearch-lazy-highlight-face' :background "yellow3" :foreground "black")
468      (region :background "#b8b8e0" :foreground "black")
469      ;; (region :background "plum" :foreground "black")
470      (show-paren-match-face :background "gold" :foreground "black")
471      (show-paren-mismatch-face :background "red" :foreground "black")
472      (trailing-whitespace :background "gray65")
473      (cursor :inverse-video t)
474      (enotes/list-title-face :foreground "blue" :weight 'bold)
475      (mode-line :background "#b0b0ff" :foreground "black" :box nil
476                 :inverse-video nil)
477      (header-line :background "cornflowerblue" :foreground "black" :box nil
478                   :inverse-video nil)
479      (mode-line-inactive :background "#b0b0b0" :foreground "black" :box nil
480                          :inverse-video nil)
481      ;; (fringe :background "black" :foreground "gray90")
482      (fringe :background "gray75")
483      (ff/date-info-face :foreground "white" :weight 'bold)
484      (ff/mail-alarm-face :foreground "white" :background "red2")
485      ;; (alarm-vc-face :foreground "black" :background "yellow" :weight 'normal)
486     ))
487   )
488
489 ;; When we are root, put the modeline in red
490
491 (when (string= (user-real-login-name) "root")
492   (ff/configure-faces
493    '((mode-line :background "red3" :foreground "black" :box nil
494                 :inverse-video nil))
495    ))
496
497 ;; Why should I have to do this?
498 (add-hook 'sh-mode-hook
499           (lambda ()
500             (set-face-attribute 'sh-heredoc nil
501                                 :foreground "#604000"
502                                 :background "white"
503                                 :italic t)
504             (set-face-attribute 'sh-heredoc-face nil
505                                 :foreground "#604000"
506                                 :background "white"
507                                 :italic t)
508             ))
509
510 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
511 ;; Move the window on the buffer without moving the cursor
512 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
513
514 (defun ff/scroll-down ()
515   "Scroll the buffer down one line and keep the cursor at the same location."
516   (interactive)
517   (condition-case nil
518       (scroll-down 1)
519     (error nil)))
520
521 (defun ff/scroll-up ()
522   "Scroll the buffer up one line and keep the cursor at the same location."
523   (interactive)
524   (condition-case nil
525       (scroll-up 1)
526     (error nil)))
527
528 (defun ff/scroll-left ()
529   "Scroll the buffer left one column and keep the cursor at the same location."
530   (interactive)
531   (condition-case nil
532       (scroll-left 2)
533     (error nil)))
534
535 (defun ff/scroll-right ()
536   "Scroll the buffer right one column and keep the cursor at the same location."
537   (interactive)
538   (condition-case nil
539       (scroll-right 2)
540     (error nil)))
541
542 (define-key global-map [(meta up)] 'ff/scroll-down)
543 (define-key global-map [(meta down)] 'ff/scroll-up)
544 (define-key global-map [(meta p)] 'ff/scroll-down)
545 (define-key global-map [(meta n)] 'ff/scroll-up)
546 (define-key global-map [(meta right)] 'ff/scroll-left)
547 (define-key global-map [(meta left)] 'ff/scroll-right)
548
549 (defun ff/delete-trailing-whitespaces-and-indent ()
550   (interactive)
551   (delete-trailing-whitespace)
552   (indent-region (point-min) (point-max) nil))
553
554 (define-key global-map [(control c) (control q)] 'ff/delete-trailing-whitespaces-and-indent)
555
556 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
557 ;; Playing sounds
558 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
559
560 ;; (defun ff/esd-sound (file)
561 ;;   "Plays a sound with the Enlighted sound daemon."
562 ;;   (interactive)
563 ;;   (process-kill-without-query (start-process-shell-command "esdplay"
564 ;;                                                            nil
565 ;;                                                            "esdplay" file)))
566
567 (defun ff/alsa-sound (file)
568   "Plays a sound with ALSA."
569   (interactive)
570   (process-kill-without-query (start-process-shell-command "aplay"
571                                                            nil
572                                                            "aplay" "-q" file)))
573
574 (if (and (boundp 'x-display-name) (string= x-display-name ":0.0"))
575     (defalias 'ff/play-sound-async 'ff/alsa-sound)
576   (defalias 'ff/play-sound-async 'ding))
577
578 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
579 ;; I comment stuff often, let's be efficient. shift + down comments
580 ;; the current line and goes down, and shift + up uncomments the line
581 ;; and goes up (they are not the dual of each other, but moving and
582 ;; then uncommenting would be very counter-intuitive).
583 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
584
585 (defun ff/comment-and-go-down (arg)
586   "Comments and goes down ARG lines."
587   (interactive "p")
588   (condition-case nil
589       (comment-region (point-at-bol) (point-at-eol)) (error nil))
590   (next-line 1)
591   (if (> arg 1) (ff/comment-and-go-down (1- arg))))
592
593 (defun ff/uncomment-and-go-up (arg)
594   "Uncomments and goes up ARG lines."
595   (interactive "p")
596   (condition-case nil
597       (uncomment-region (point-at-bol) (point-at-eol)) (error nil))
598   (next-line -1)
599   (if (> arg 1) (ff/uncomment-and-go-up (1- arg))))
600
601 (define-key global-map [(shift down)] 'ff/comment-and-go-down)
602 (define-key global-map [(shift up)] 'ff/uncomment-and-go-up)
603
604 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
605 ;; Counting various entities in text
606 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
607
608 (defun ff/count-char ()
609   "Prints the number of characters between the first previous \"--\"
610 and the firt next \"--\"."
611   (interactive)
612   (let ((from (save-excursion (re-search-backward "^--$\\|BEGIN_COUNT" nil t)))
613         (to (save-excursion (re-search-forward "^--$\\|END_COUNT" nil t))))
614     (if (and to from) (message "%d character(s)" (- to from 6))
615       (error "Can not find the -- delimiters"))))
616
617 (defun ff/count-words ()
618   "Print number of words between the first previous \"--\" and the
619 firt next \"--\"."
620   (interactive)
621   (let ((from (save-excursion (re-search-backward "^--$" nil t)))
622         (to (save-excursion (re-search-forward "^--$" nil t))))
623     (if (and to from)
624         (save-excursion
625           (goto-char from)
626           (let ((count 0))
627             (while (< (point) to)
628               (re-search-forward "\\w+\\W+")
629               (setq count (1+ count)))
630             (message "%d word(s)" count)))
631       (error "Can not find the -- delimiters"))))
632
633 (defun ff/word-occurences ()
634   "Display in a new buffer the list of words sorted by number of
635 occurrences "
636   (interactive)
637
638   (let ((buf (get-buffer-create "*word counting*"))
639         (map (make-sparse-keymap))
640         (nb (make-hash-table))
641         (st (make-hash-table))
642         (result nil))
643
644     ;; Collects all words in a hash table
645
646     (save-excursion
647       (goto-char (point-min))
648       (while (re-search-forward "\\([\\-a-zA-Z\\\\]+\\)" nil t)
649         (let* ((s (downcase (match-string-no-properties 1)))
650                (k (sxhash s)))
651           (puthash k s st)
652           (puthash k (1+ (gethash k nb 0)) nb))))
653
654     ;; Creates the result buffer
655
656     (define-key map "q" 'kill-this-buffer)
657     (display-buffer buf)
658     (set-buffer buf)
659     (setq show-trailing-whitespace nil)
660     (erase-buffer)
661
662     ;; Builds a list from the hash table
663
664     (maphash
665      (lambda (key value)
666        (setq result (cons (cons value (gethash key st)) result)))
667      nb)
668
669     ;; Sort and display it
670
671     (mapc (lambda (x)
672             (if (and (> (car x) 3)
673                      ;; No leading backslash and at least four characters
674                      (string-match "^[^\\]\\{4,\\}" (cdr x))
675                      )
676                 (insert (number-to-string (car x)) " " (cdr x) "\n")))
677           (sort result (lambda (a b) (> (car a) (car b)))))
678
679     ;; Adjust the window size and stuff
680
681     (fit-window-to-buffer (get-buffer-window buf))
682     (use-local-map map)
683     (set-buffer-modified-p nil))
684   )
685
686 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
687 ;; Printing
688 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
689
690 (load "ps-print")
691
692 (setq ps-print-color-p nil
693       ps-paper-type 'letter
694       ;; ps-paper-type 'a4
695       ;; ps-top-margin (* 1.75 56.692)
696       ;; ps-left-margin 56.692
697       ;; ps-bottom-margin 56.692
698       ;; ps-right-margin 56.692
699
700       ;; Simple header. Remove that silly frame shadow.
701       ps-print-header nil
702       ps-print-header-frame nil
703       ps-header-line-pad 0.3
704       ps-header-font-family 'Courier
705       ps-header-title-font-size '(8.5 . 10)
706       ps-header-font-size '(6 . 7)
707       ps-font-size '(7 . 8)
708       )
709
710 (ps-put 'ps-header-frame-alist 'back-color 1.0)
711 (ps-put 'ps-header-frame-alist 'shadow-color 1.0)
712 (ps-put 'ps-header-frame-alist 'border-color 0.0)
713 (ps-put 'ps-header-frame-alist 'border-width 0.0)
714
715 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
716
717 ;; http://blog.tuxicity.se/elisp/emacs/2010/03/26/rename-file-and-buffer-in-emacs.htm
718
719 (defun rename-file-and-buffer ()
720   "Renames current buffer and file it is visiting."
721   (interactive)
722   (let ((name (buffer-name))
723         (filename (buffer-file-name)))
724     (if (not (and filename (file-exists-p filename)))
725         (message "Buffer '%s' is not visiting a file!" name)
726       (let ((new-name (read-file-name "New name: " filename)))
727         (cond ((get-buffer new-name)
728                (message "A buffer named '%s' already exists!" new-name))
729               (t
730                (rename-file name new-name 1)
731                (rename-buffer new-name)
732                (set-visited-file-name new-name)
733                (set-buffer-modified-p nil)))))))
734
735 (global-set-key (kbd "C-c r") 'rename-file-and-buffer)
736
737 (defun ff/non-existing-filename (dir prefix suffix)
738   "Returns a filename of the form DIR/PREFIX[.n].SUFFIX whose file does
739 not exist"
740   (let ((n 0)
741         (f (concat prefix suffix)))
742     (while (file-exists-p (concat dir "/" f))
743       (setq n (1+ n)
744             f (concat prefix "." (prin1-to-string n) suffix)))
745     f))
746
747 (defun ff/print-buffer-or-region-with-faces (&optional file)
748
749   ;; I am fed up with spell checking highlights
750   (when (and flyspell-mode
751              ;; (or ispell-minor-mode flyspell-mode)
752              (not (y-or-n-p "The spell checking is on, still print ? ")))
753     (error "Printing cancelled, the spell-checking is on"))
754
755   (unless
756       (condition-case nil
757           (ps-print-region-with-faces (region-beginning) (region-end) file)
758         (error nil))
759     (ps-print-buffer-with-faces file)))
760
761 (defun ff/print-to-file (file)
762   "Prints the region if selected or the whole buffer in postscript
763 into FILE."
764   (interactive
765    (list
766     (read-file-name
767      "PS file: " "/tmp/" nil nil
768      (ff/non-existing-filename
769       "/tmp"
770       (replace-regexp-in-string "[^a-zA-Z0-9_.-]" "_" (file-name-nondirectory
771                                                        (buffer-name)))
772       ".ps"))
773     ))
774   (ff/print-buffer-or-region-with-faces file))
775
776 (defun ff/print-to-printer ()
777   "Prints the region if selected or the whole buffer to a postscript
778 printer."
779   (interactive)
780   (message "Printing to '%s'" (getenv "PRINTER"))
781   (ff/print-buffer-or-region-with-faces))
782
783 ;; Can you believe it? There is a "print" key on PC keyboards ...
784
785 (define-key global-map [(print)] 'ff/print-to-file)
786 (define-key global-map [(shift print)] 'ff/print-to-printer)
787
788 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
789 ;; Dealing with the laptop battery
790 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
791
792 (defcustom ff/battery-dir "/sys/class/power_supply/BAT0"
793   "*Where to gather the battery information")
794
795 (defcustom ff/temperature-file "/sys/class/thermal/thermal_zone0/temp"
796   "*Where to gather the thermal information")
797
798 (defun ff/file-first-line (file)
799   (with-temp-buffer
800     (insert-file-contents-literally file)
801     (buffer-substring (point-at-bol) (point-at-eol))))
802
803 (defun ff/battery-percent (prefix)
804   (condition-case nil
805       (/ (* 100 (string-to-number (ff/file-first-line (format "%s/%s_now" ff/battery-dir prefix))))
806          (string-to-number (ff/file-first-line (format "%s/%s_full"  ff/battery-dir prefix))))
807     (error -1))
808   )
809
810 (defun ff/laptop-info-string () (interactive)
811   (condition-case nil
812       (concat
813
814        ;; The temperature
815
816        (let ((temp (/ (string-to-number (ff/file-first-line ff/temperature-file)) 1000)))
817          (if (> temp 50)
818              (concat
819               (let ((s (format "%dC " temp)))
820                 (if (> temp 65) (propertize s 'face
821                                             'font-lock-warning-face)
822                   s))
823               )
824            )
825          )
826
827        ;; The battery
828
829        (let ((battery-status (ff/file-first-line (concat ff/battery-dir "/status"))))
830
831          (cond
832           ((string= battery-status "Full") "L")
833
834           ((string= battery-status "Charging")
835            (format "L%d%%" (max (ff/battery-percent "charge")
836                                 (ff/battery-percent "energy"))))
837
838           ((string= battery-status "Discharging")
839            (let* ((c (max (ff/battery-percent "charge")
840                           (ff/battery-percent "energy")))
841                   (s (format "B%d%%" c)))
842              (if (>= c 20) s (propertize s 'face 'font-lock-warning-face))))
843
844           (t battery-status)
845
846           ))
847
848        )
849
850     (error nil))
851   )
852
853 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
854
855 (defun ff/system-info () (interactive)
856
857   (let ((buf (get-buffer-create "*system info*"))
858         (map (make-sparse-keymap)))
859
860     (define-key map "q" 'kill-this-buffer)
861     (display-buffer buf)
862     (set-buffer buf)
863     (setq show-trailing-whitespace nil)
864     (erase-buffer)
865
866     (let ((highlight nil))
867
868       (mapc (lambda (x)
869               (insert
870                (if (setq highlight (not highlight))
871                    (propertize
872                     (with-temp-buffer (apply 'call-process x)
873                                       (buffer-string))
874                     'face '(:background "#c0c0ff"))
875                  (with-temp-buffer (apply 'call-process x)
876                                    (buffer-string))
877                  ))
878               )
879
880             '(
881               ("hostname" nil t nil "-v")
882               ("acpi" nil t)
883               ("df" nil t nil "-h")
884               ;; ("mount" nil t)
885               ("ifconfig" nil t)
886               ("ssh-add" nil t nil "-l")
887               )))
888
889     (goto-char (point-min))
890     (while (re-search-forward "^$" nil t) (backward-delete-char 1))
891
892     (fit-window-to-buffer (get-buffer-window buf))
893     (use-local-map map)
894     (set-buffer-modified-p nil)
895     ))
896
897 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
898 ;; Make a sound when there is new mail
899 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
900
901 ;; I do not like sounds anymore
902
903 ;; (setq ff/already-boinged-for-mail nil)
904
905 ;; (defun ff/boing-if-new-mail ()
906 ;; (if mail (when (not ff/already-boinged-for-mail)
907 ;; ;; (ff/play-sound-async "~/local/sounds/boing1.wav")
908 ;; ;; (ff/show-unspooled-mails)
909 ;; (setq ff/already-boinged-for-mail t))
910 ;; (setq ff/already-boinged-for-mail nil))
911 ;; )
912
913 ;; (add-hook 'display-time-hook 'ff/boing-if-new-mail)
914
915 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
916 ;; Display time
917 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
918
919 (setq
920
921  display-time-interval 15 ;; Check every 15s
922
923  display-time-string-forms `(
924
925                              ;; (if mail
926                              ;;     (concat " "
927                              ;;             (propertize " mail "
928                              ;;                         'face 'ff/mail-alarm-face)
929                              ;;             " ")
930                              ;;   )
931
932                              (propertize (concat 24-hours ":" minutes
933                                                  " "
934                                                  dayname " "
935                                                  monthname " "
936                                                  day)
937                                          'face 'ff/date-info-face)
938
939                              load
940
941                              ,(if (ff/laptop-info-string)
942                                   '(concat " " (ff/laptop-info-string)))
943
944                              )
945
946  ;; display-time-format "%b %a %e %H:%M"
947  ;; display-time-mail-face nil
948  )
949
950 ;; Show the time, mail and stuff
951 (display-time)
952
953 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
954 ;; Moving through buffers
955 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
956
957 (defun ff/next-buffer ()
958   "Switches to the next buffer in cyclic order."
959   (interactive)
960   (let ((buffer (current-buffer)))
961     (switch-to-buffer (other-buffer buffer))
962     (bury-buffer buffer)))
963
964 (defun ff/prev-buffer ()
965   "Switches to the previous buffer in cyclic order."
966   (interactive)
967   (let ((list (nreverse (buffer-list)))
968         found)
969     (while (and (not found) list)
970       (let ((buffer (car list)))
971         (if (and (not (get-buffer-window buffer))
972                  (not (string-match "\\` " (buffer-name buffer))))
973             (setq found buffer)))
974       (setq list (cdr list)))
975     (switch-to-buffer found)))
976
977 (define-key global-map [?\C-x right] 'ff/next-buffer)
978 (define-key global-map [?\C-x left] 'ff/prev-buffer)
979
980 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
981 ;; There is actually a decent terminal emulator in emacs!
982 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
983
984 (load "term")
985
986 (defun ff/kill-associated-buffer (process str) (interactive)
987   (let ((buffer (process-buffer process)))
988     (kill-buffer buffer))
989   (message "Process finished (%s)" (replace-regexp-in-string "\n$" "" str)))
990
991 (defun ff/kill-associated-buffer-and-delete-windows (process str) (interactive)
992   (let ((buffer (process-buffer process)))
993     (delete-windows-on buffer)
994     (kill-buffer buffer))
995   (message "Process finished (%s)" (replace-regexp-in-string "\n$" "" str)))
996
997 (defun ff/shell-new-buffer (buffername program &rest param)
998   "Start a terminal-emulator in a new buffer with the shell PROGRAM,
999 optionally invoked with the parameters PARAM. The process associated
1000 to the shell can be killed without query."
1001
1002   (interactive)
1003
1004   (let ((n 1)
1005         (bn buffername))
1006
1007     (while (get-buffer (concat "*" bn "*"))
1008       (setq n (1+ n)
1009             bn (format "%s<%d>" buffername n)))
1010
1011     (set-buffer (apply 'make-term (append (list bn program nil) param)))
1012
1013     (setq show-trailing-whitespace nil)
1014     (term-char-mode)
1015     (message "C-c C-k term-char-mode, C-c C-j term-line-mode. \
1016 In line mode: M-p previous line, M-n next line.")
1017
1018     ;; A standard setup of the face above is not enough, I have to
1019     ;; force them here. Since I have a gray90 background, I like
1020     ;; darker colors.
1021
1022     (when window-system
1023       (ff/configure-faces
1024        '((term-green :foreground "green3")
1025          (term-cyan :foreground "cyan3")
1026          (term-default-fg-inv :foreground "gray90" :background "black")
1027          )))
1028
1029     (term-set-escape-char ?\C-x)
1030
1031     ;; I like the shell buffer and windows to be deleted when the
1032     ;; shell process terminates. It's a bit of a mess to acheive this.
1033
1034     (let ((process (get-buffer-process (current-buffer))))
1035       (process-kill-without-query process)
1036       (set-process-sentinel process
1037                             ;; 'ff/kill-associated-buffer-and-delete-windows
1038                             'ff/kill-associated-buffer
1039                             ))
1040
1041     ;; (switch-to-buffer-other-window (concat "*" bn "*"))
1042     (switch-to-buffer (concat "*" bn "*"))
1043     ))
1044
1045 (defcustom ff/default-bash-commands '("ssh")
1046   "*List of commands to be used for completion when invoking a new
1047 bash shell with `ff/bash-new-buffer'.")
1048
1049 (defun ff/bash-new-buffer (universal)
1050   "Starts a bash in a new buffer. When invoked with a universal
1051 argument, asks for a command to execute in that bash shell. The list
1052 of commands in `ff/default-bash-commands' is used for auto-completion"
1053   (interactive "P")
1054
1055   (if universal
1056       (let ((cmd (completing-read
1057                   "Command: "
1058                   (mapcar (lambda (x) (cons x t)) ff/default-bash-commands))))
1059         (ff/shell-new-buffer cmd "/bin/bash" "-c" cmd))
1060
1061     (ff/shell-new-buffer "bash" "/bin/bash")))
1062
1063 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1064 ;; vc stuff for CVS
1065 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1066
1067 (setq ;; Always follow links if the file is under version control
1068  vc-follow-symlinks t
1069  )
1070
1071 (when (load "vc-git" nil t)
1072   (add-to-list 'vc-handled-backends 'GIT))
1073
1074 ;; alarm-vc.el is one of my own scripts, check my web page
1075
1076 (when (ff/load-or-alert "alarm-vc" t)
1077   (setq alarm-vc-mode-exceptions "^VM"))
1078
1079 (when (ff/load-or-alert "git")
1080   (setq git-show-unknown nil)
1081   )
1082
1083 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1084 ;; Makes .sh and others files executable automagically
1085 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1086
1087 ;; Please consider the security-related consequences of using it
1088
1089 ;; (defun ff/make-shell-scripts-executable (&optional filename)
1090 ;; (setq filename (or filename (buffer-name)))
1091 ;; (when (and (string-match "\\.sh$\\|\\.pl$\\|\\.rb" filename)
1092 ;; (not (file-executable-p filename))
1093 ;; )
1094 ;; (set-file-modes filename 493)
1095 ;; (message "Made %s executable" filename)))
1096
1097 ;; (add-hook 'after-save-hook 'ff/make-shell-scripts-executable)
1098
1099 (add-hook 'after-save-hook
1100           'executable-make-buffer-file-executable-if-script-p)
1101
1102 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1103 ;; Cool stuff to navigate in emacs-lisp sources
1104 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1105
1106 (load "find-func")
1107
1108 (defun ff/goto-function-definition (&optional goback)
1109   "Go directly to the definition of the function at point. With
1110 goback argument, go back where we were."
1111   (interactive "P")
1112   (if goback
1113       (if (not (and (boundp 'goto-function-history) goto-function-history))
1114           (error "We were nowhere, buddy")
1115         (message "Come back")
1116         (switch-to-buffer (car (car goto-function-history)))
1117         (goto-char (cdr (car goto-function-history)))
1118         (setq goto-function-history (cdr goto-function-history)))
1119
1120     (let ((function (function-called-at-point)))
1121       (when function
1122         (let ((location (find-function-search-for-symbol
1123                          function nil
1124                          (symbol-file function))))
1125           (setq goto-function-history
1126                 (cons (cons (current-buffer) (point))
1127                       (and (boundp 'goto-function-history)
1128                            goto-function-history)))
1129           (pop-to-buffer (car location))
1130           (goto-char (cdr location)))))))
1131
1132 (define-key global-map [(meta g)] 'ff/goto-function-definition)
1133 (define-key global-map [(meta G)] (lambda () (interactive)
1134                                     (ff/goto-function-definition t)))
1135
1136 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1137 ;; The big stuff (bbdb, mailcrypt, etc.)
1138 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1139
1140 ;; Failsafe version if we can't load bbdb
1141 (defun ff/explicit-name (email) email)
1142
1143 (load "vc-git")
1144
1145 (when (ff/load-or-alert "bbdb")
1146
1147   (setq
1148    ;; Stop asking (if not t or nil, will not ask)
1149    bbdb-offer-save 'never
1150    ;; I hate when bbdb decides to mess up my windows
1151    bbdb-use-pop-up nil
1152    ;; I have no problem with bbdb asking me if the sender email
1153    ;; does not match exactly the address we have in the database
1154    bbdb-quiet-about-name-mismatches 0
1155    ;; I have european friends, too
1156    bbdb-north-american-phone-numbers-p nil
1157    ;; To cycle through all possible addresses
1158    bbdb-complete-name-allow-cycling t
1159    ;; Cycle with full names only, not through all net-addresses alone too
1160    bbdb-dwim-net-address-allow-redundancy t
1161    ;; Do not add new addresses automatically
1162    bbdb-always-add-addresses nil
1163    )
1164
1165   (defface ff/known-address-face
1166     '((t (:foreground "blue2")))
1167     "The face to display known mail identities.")
1168
1169   (defface ff/unknown-address-face
1170     '((t (:foreground "gray50")))
1171     "The face to display unknown mail identities.")
1172
1173   (defun ff/explicit-name (email)
1174     "Returns a string identity for the first address in EMAIL. The
1175 identity is taken from bbdb if possible or from the address itself
1176 with mail-extract-address-components. The suffix \"& al.\" is added if
1177 there are more than one address.
1178
1179 If no bbdb record is found, the name is propertized with the face
1180 ff/unknown-address-face. If a record is found and contains a note
1181 'face, the associated face is used, otherwise
1182 ff/known-address-face is used."
1183
1184     (and email
1185          (let* ((data (mail-extract-address-components email))
1186                 (name (car data))
1187                 (net (cadr data))
1188                 (record (bbdb-search-simple nil net)))
1189
1190            (concat
1191
1192             (condition-case nil
1193                 (propertize (bbdb-record-name record)
1194                             'face
1195                             (or (cdr (assoc 'face
1196                                             (bbdb-record-raw-notes record)))
1197                                 'ff/known-address-face))
1198               (error
1199                (propertize (or (and data (concat "<" net ">"))
1200                                "*undefined*")
1201                            'face 'ff/unknown-address-face)
1202                ))
1203             (if (string-match "," (mail-strip-quoted-names email)) " & al.")
1204             )))
1205     )
1206
1207   (ff/configure-faces '((ff/robot-address-face :foreground "green4")
1208                         (ff/personal-address-face :foreground "dark magenta"
1209                                                   :weight 'bold)
1210                         (ff/important-address-face :foreground "blue2"
1211                                                    ;; :underline t
1212                                                    ;; :background "white"
1213                                                    ;; :foreground "green4"
1214                                                    :weight 'bold
1215                                                    ;; :slant 'italic
1216                                                    )))
1217
1218   )
1219
1220 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1221 ;; An encrypted file to put secure stuff (passwords, ...)
1222 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1223
1224 (when (ff/load-or-alert "mailcrypt")
1225   (mc-setversion "gpg")
1226   ;; Keep the passphrase for 10min
1227   (setq mc-passwd-timeout 600
1228         ff/secure-note-file "~/private/secure-notes.gpg")
1229   )
1230
1231 (defface ff/secure-date
1232   '((t (:background "white" :weight bold)))
1233   "The face to display the dates in the modeline.")
1234
1235 (defun ff/secure-note-add () (interactive)
1236   (find-file ff/secure-note-file)
1237
1238   ;; Adds a new entry (i.e. date and a bunch of empty lines)
1239
1240   (goto-char (point-min))
1241   (insert "-- "
1242           (format-time-string "%Y %b %d %H:%M:%S" (current-time))
1243           " --\n\n")
1244   (previous-line 1)
1245
1246   ;; Colorizes the dates
1247
1248   (save-excursion
1249     (goto-char (point-min))
1250     (while (re-search-forward
1251             "^-- [0-9]+ [a-z]+ [0-9]+ [0-9]+:[0-9]+:[0-9]+ -+$"
1252             nil t)
1253       (add-text-properties
1254        (match-beginning 0) (1+ (match-end 0))
1255        '(face ff/secure-date rear-nonsticky t))))
1256
1257   (set-buffer-modified-p nil)
1258   (setq buffer-undo-list nil)
1259   )
1260
1261 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1262 ;; Spelling
1263 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1264
1265 (setq ;; For french, aspell is far better than ispell
1266  ispell-program-name "aspell"
1267  ;; To avoid ispell errors in figure filenames, labels, references.
1268  ;;       ispell-tex-skip-alists
1269  ;;       (list
1270  ;;        (append (car ispell-tex-skip-alists)
1271  ;;                '(("\\\\citep"           ispell-tex-arg-end) ;; JMLR
1272  ;;                  ("\\\\cite"            ispell-tex-arg-end)
1273  ;;                  ("\\\\nocite"          ispell-tex-arg-end)
1274  ;;                  ("\\\\includegraphics" ispell-tex-arg-end)
1275  ;;                  ("\\\\author"          ispell-tex-arg-end)
1276  ;;                  ("\\\\ref"             ispell-tex-arg-end)
1277  ;;                  ("\\\\label"           ispell-tex-arg-end)
1278  ;;                  ))
1279  ;;        (cadr ispell-tex-skip-alists))
1280
1281  ;; So that reftex follows the text when moving in the summary
1282  reftex-toc-follow-mode nil
1283  ;; So that reftex visits files to follow
1284  reftex-revisit-to-follow t
1285  )
1286
1287 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1288 ;; Used in a \includegraphics runs xfig with the corresponding .fig
1289 ;; file or gimp with the corresponding bitmap picture
1290 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1291
1292 (defun ff/run-eps-edition (prefix rules &optional force)
1293   (if rules
1294       (let ((filename (concat prefix (car (car rules)))))
1295         (if (or force (file-exists-p filename))
1296             (start-process "latex-eps-editor" nil (cdr (car rules)) filename)
1297           (ff/run-eps-edition prefix (cdr rules) force)))
1298     (message "No original file found for %seps" prefix)))
1299
1300 (defcustom ff/xdvi-for-latex-options nil
1301   "*Options to pass to xdvi when invoking `ff/run-viewer'")
1302
1303 (defun ff/run-viewer (universal)
1304
1305   "Starts an editor for the .eps at point (either xfig or gimp,
1306 depending with the original file it can find), or starts xdvi for
1307 the current .tex if no .eps is found at point. When run with a
1308 universal argument starts xfig even if the .fig does not exist"
1309
1310   (interactive "P")
1311
1312   (if (and (save-excursion
1313              (and (re-search-backward "{" (point-at-bol) t)
1314                   (or (re-search-forward "{\\([^{}]*.\\)eps}" (point-at-eol) t)
1315                       (re-search-forward "{\\([^{}]*.\\)pdf}" (point-at-eol) t)
1316                       (re-search-forward "{\\([^{}]*.\\)pdf_t}" (point-at-eol) t)
1317                       (re-search-forward "{\\([^{}]*.\\)png}" (point-at-eol) t)
1318                       (re-search-forward "{\\([^{}]*.\\)jpg}" (point-at-eol) t)
1319                       )))
1320            (and (<= (match-beginning 1) (point))
1321                 (>= (match-end 1) (- (point) 2))))
1322
1323       (ff/run-eps-edition (match-string-no-properties 1)
1324                           '(("fig" . "xfig")
1325                             ("jpg" . "gimp" )
1326                             ("png" . "gimp") ("pgm" . "gimp") ("ppm" . "gimp")
1327                             ("jpg" . "xv"))
1328                           universal)
1329
1330     (if (not (and (buffer-file-name) (string-match "\\(.*\\)\.tex$"
1331                                                    (buffer-file-name))))
1332         (message "Not a latex file!")
1333       (condition-case nil (kill-process xdvi-process) (error nil))
1334       (let ((dvi-name (concat (match-string 1 (buffer-file-name)) ".dvi")))
1335         (if (not (file-exists-p dvi-name)) (error "Can not find %s !" dvi-name)
1336           (message "Starting xdvi with %s" dvi-name)
1337           (setq xdvi-process (apply 'start-process
1338                                     (append '("xdvi-for-latex" nil "xdvi")
1339                                             ff/xdvi-for-latex-options
1340                                             (list dvi-name))))
1341           (process-kill-without-query xdvi-process))))
1342     ))
1343
1344 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1345 ;; Tex mode
1346
1347 ;; When working on a tex file with other people, I can just change
1348 ;; ff/tex-command in the -*- part of the file so that I don't mess up
1349 ;; other's people configuration.
1350
1351 (defadvice tex-file (around ff/set-my-own-tex-command () activate)
1352   (let ((tex-command
1353          (or (and (boundp 'ff/tex-command)
1354                   ff/tex-command)
1355              tex-command)))
1356     ad-do-it))
1357
1358 ;; This is a bit hardcore, but really I can't bear the superscripts in
1359 ;; my emacs window and could not find another way to deactivate them.
1360
1361 (load "tex-mode")
1362 (defun tex-font-lock-suscript (pos) ())
1363
1364 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1365 ;; Prevents many errors from beeping and makes the others play a nifty
1366 ;; sound
1367 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1368
1369 (defun ff/ring-bell ()
1370   (unless (memq this-command
1371                 '(isearch-abort
1372                   abort-recursive-edit
1373                   exit-minibuffer
1374                   keyboard-quit
1375                   backward-delete-char-untabify
1376                   delete-backward-char
1377                   minibuffer-complete-and-exit
1378                   previous-line next-line
1379                   backward-char forward-char
1380                   scroll-up scroll-down
1381                   enlarge-window-horizontally shrink-window-horizontally
1382                   enlarge-window shrink-window
1383                   minibuffer-complete
1384                   ))
1385     ;; (message "command [%s]" (prin1-to-string this-command))
1386     ;; (ff/play-sound-async "~/local/sounds/short_la.wav")
1387     ))
1388
1389 (setq ring-bell-function 'ff/ring-bell)
1390
1391 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1392 ;; Past the content of the url currently in the kill-ring with
1393 ;; shift-click 2
1394 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1395
1396 (defun ff/insert-url (&optional url)
1397   "Downloads an URL with lynx and inserts it after the point."
1398   (interactive "MUrl: ")
1399   (when url
1400     (message "Inserting %s" url)
1401     (insert (concat "from: " url "\n\n"))
1402     ;; (call-process "lynx" nil t nil "-nolist" "-dump" url))
1403     (call-process "w3m" nil t nil "-dump" url))
1404   )
1405
1406 (define-key global-map [(shift mouse-2)]
1407   (lambda () (interactive) (ff/insert-url (current-kill 0))))
1408
1409 ;; lookup-dict is one of my own scripts, check my web page
1410
1411 (when (ff/load-or-alert "lookup-dict" t)
1412   (define-key global-map [(control \?)] 'lookup-dict))
1413
1414 ;; (defun ff/generate-password () (interactive)
1415 ;; (let ((c "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"))
1416 ;; (nth (random (length c)) c))
1417
1418 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1419 ;; Automatization of things I do often
1420 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1421
1422 (defun ff/snip () (interactive)
1423   (let ((start (condition-case nil (region-beginning) (error (point))))
1424         (end (condition-case nil (region-end) (error (point)))))
1425     (goto-char end)
1426     (insert "---------------------------- snip snip -------------------------------\n")
1427     (goto-char start)
1428     (insert "---------------------------- snip snip -------------------------------\n")
1429     ))
1430
1431 (defun ff/start-latex ()
1432   "Adds all that stuff to start a new LaTeX document."
1433   (interactive)
1434   (goto-char (point-min))
1435   (insert "%% -*- mode: latex; mode: reftex; mode: flyspell; coding: utf-8; tex-command: \"pdflatex.sh\" -*-
1436
1437 \\documentclass[12pt]{article}
1438 \\usepackage[a4paper,top=2.5cm,bottom=2cm,left=2.5cm,right=2.5cm]{geometry}
1439 \\usepackage[utf8]{inputenc}
1440 \\usepackage{amsmath}
1441 \\usepackage{amssymb}
1442 \\usepackage[pdftex]{graphicx}
1443 \\usepackage{microtype}
1444 \\usepackage[colorlinks=true,linkcolor=blue,urlcolor=blue,citecolor=blue]{hyperref}
1445
1446 \\setlength{\\parindent}{0cm}
1447 \\setlength{\\parskip}{12pt}
1448 \\renewcommand{\\baselinestretch}{1.3}
1449
1450 \\def\\argmax{\\operatornamewithlimits{argmax}}
1451 \\def\\argmin{\\operatornamewithlimits{argmin}}
1452
1453 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1454 %% Sans serif fonts
1455 %% \\usepackage[T1]{fontenc}
1456 %% \\usepackage[scaled]{helvet}
1457 %% \\usepackage[cm]{sfmath}
1458 %% \\renewcommand{\\ttdefault}{pcr}
1459 %% \\renewcommand*\\familydefault{\\sfdefault}
1460 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1461 %% The \\todo command
1462 \\newcounter{nbdrafts}
1463 \\setcounter{nbdrafts}{0}
1464 \\makeatletter
1465 \\newcommand{\\checknbdrafts}{
1466 \\ifnum \\thenbdrafts > 0
1467 \\@latex@warning@no@line{*WARNING* The document contains \\thenbdrafts \\space draft note(s)}
1468 \\fi}
1469 \\newcommand{\\todo}[1]{\\addtocounter{nbdrafts}{1}{\\color{red} #1}}
1470 \\makeatother
1471 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1472
1473 \\begin{document}
1474
1475 ")
1476   (save-excursion
1477     (goto-char (point-max))
1478     (insert "
1479
1480 \\end{document}
1481 "))
1482   (latex-mode))
1483
1484 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1485
1486 (defun ff/add-copyrights ()
1487   "Adds two lines for the (C) at the beginning of current buffer."
1488   (interactive)
1489
1490   (let ((comment-style 'plain))
1491
1492     (goto-char (point-min))
1493
1494     ;; If this is a script, put the copyrights after the first line
1495
1496     (when (re-search-forward "^#!" nil t)
1497       (beginning-of-line)
1498       (next-line 1))
1499
1500     (let ((start (point))
1501           (comment-style 'box))
1502       (insert
1503        (concat
1504
1505         "\nSTART_IP_HEADER\n"
1506
1507         (when (boundp 'user-full-name)
1508           (concat "\nWritten by " user-full-name "\n"))
1509
1510         (when (boundp 'user-mail-address)
1511           (concat "Contact <" user-mail-address "> for comments & bug reports\n"))
1512
1513         "\nEND_IP_HEADER\n"
1514         ))
1515
1516       (comment-region start (point)))
1517
1518     ))
1519
1520 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1521
1522 (defun ff/remove-ip-header () (interactive)
1523   (save-excursion
1524     (goto-char (point-min))
1525     (when (and (re-search-forward "START_IP_HEADER" nil t)
1526                (re-search-forward "END_IP_HEADER" nil t))
1527       (message "yep"))
1528     ))
1529
1530 (defun ff/add-gpl ()
1531   "Adds the GPL statements at the beginning of current buffer."
1532   (interactive)
1533   (let ((comment-style 'box)
1534         (gpl
1535          (concat
1536
1537           ;;           "
1538           ;; This program is free software; you can redistribute it and/or
1539           ;; modify it under the terms of the GNU General Public License
1540           ;; version 2 as published by the Free Software Foundation.
1541
1542           ;; This program is distributed in the hope that it will be useful, but
1543           ;; WITHOUT ANY WARRANTY\; without even the implied warranty of
1544           ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1545           ;; General Public License for more details.
1546           ;; "
1547
1548           "
1549 START_IP_HEADER
1550
1551 This program is free software: you can redistribute it and/or modify
1552 it under the terms of the version 3 of the GNU General Public License
1553 as published by the Free Software Foundation.
1554
1555 This program is distributed in the hope that it will be useful, but
1556 WITHOUT ANY WARRANTY; without even the implied warranty of
1557 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1558 General Public License for more details.
1559
1560 You should have received a copy of the GNU General Public License
1561 along with this program. If not, see <http://www.gnu.org/licenses/>.
1562
1563 "
1564           (when (boundp 'user-full-name)
1565             (concat "Written by and Copyright (C) " user-full-name "\n"))
1566
1567           (when (boundp 'user-mail-address)
1568             (concat "Contact <" user-mail-address "> for comments & bug reports\n"))
1569
1570           "
1571 END_IP_HEADER
1572 "
1573
1574           )))
1575
1576     (goto-char (point-min))
1577
1578     ;; If this is a script, put the gpl after the first line
1579     (when (re-search-forward "^#!" nil t)
1580       (beginning-of-line)
1581       (next-line 1))
1582
1583     (let ((start (point)))
1584       (insert gpl)
1585       (comment-region start (point)))
1586     ))
1587
1588 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1589
1590 (defun ff/start-c ()
1591   "Adds the header to start a C program."
1592   (interactive)
1593   ;;   (beginning-of-buffer)
1594   (insert
1595    "
1596 #include <stdio.h>
1597 #include <stdlib.h>
1598
1599 int main(int argc, char **argv) {
1600   exit(EXIT_SUCCESS);
1601 }
1602 ")
1603   (previous-line 2)
1604   )
1605
1606 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1607
1608 (defun ff/start-c++ ()
1609   "Adds the header to start a C++ program."
1610   (interactive)
1611   ;;   (beginning-of-buffer)
1612   (insert
1613    "
1614 #include <iostream>
1615 #include <fstream>
1616 #include <cmath>
1617 #include <stdio.h>
1618 #include <stdlib.h>
1619
1620 using namespace std;
1621
1622 int main(int argc, char **argv) {
1623
1624 }
1625 ")
1626   (previous-line 2)
1627   )
1628
1629 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1630
1631 (defun ff/headerize ()
1632   "Adds the #define HEADER_H, etc."
1633   (interactive)
1634   (let ((flag-name (replace-regexp-in-string
1635                     "[\. \(\)]" "_"
1636                     (upcase (file-name-nondirectory (buffer-file-name))))))
1637     (goto-char (point-max))
1638     (insert "\n#endif\n")
1639     (goto-char (point-min))
1640     (insert (concat "#ifndef " flag-name "\n"))
1641     (insert (concat "#define " flag-name "\n"))
1642     )
1643   )
1644
1645 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1646
1647 (defun ff/start-html ()
1648   "Adds all that stuff to start a new HTML file."
1649   (interactive)
1650   (goto-char (point-min))
1651   (insert "<?xml version=\"1.0\" encoding=\"utf-8\"?>
1652 <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
1653
1654 <html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">
1655
1656 <head>
1657 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
1658 <title></title>
1659 </head>
1660
1661 <body>
1662 ")
1663   (goto-char (point-max))
1664   (insert "
1665 </body>
1666
1667 </html>
1668 ")
1669   (html-mode))
1670
1671 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1672
1673 ;; Insert a line showing all the variables written on the current line
1674 ;; and separated by commas
1675
1676 (defun ff/cout-var (arg)
1677   "Invoked on a line with a list of variables names,
1678 it inserts a line which displays their values in cout, or cerr if
1679 the function is invoked with a universal arg"
1680   (interactive "P")
1681   (let ((line (if arg "cerr" "cout")))
1682     (goto-char (point-at-bol))
1683     ;; Regexp syntax sucks moose balls, honnest. To match '[', just
1684     ;; put it as the first char in the [...] ... This leads to some
1685     ;; obvious things like the following
1686     (while (re-search-forward "\\([][a-zA-Z0-9_.:\(\)]+\\)" (point-at-eol) t)
1687       (setq line
1688             (concat line " << \" "
1689                     (match-string 1) " = \" << " (match-string 1))))
1690     (goto-char (point-at-bol))
1691     (kill-line)
1692     (insert line " << endl\;\n")
1693     (indent-region (point-at-bol 0) (point-at-eol 0) nil)
1694     ))
1695
1696 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1697
1698 (defun ff/clean-article ()
1699   "Cleans up an article by removing the leading blanks on each line
1700 and refilling all the paragraphs."
1701   (interactive)
1702   (let ((fill-column 92))
1703     (goto-char (point-min))
1704     (while (re-search-forward "^\\ +" nil t)
1705       (replace-match "" nil nil))
1706     (fill-individual-paragraphs (point-min) (point-max) t)))
1707
1708 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1709
1710 (defun ff/start-slide ()
1711   (interactive)
1712   (insert "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1713
1714 \\begin{frame}{")
1715
1716   (save-excursion (insert "}{}
1717
1718 \\end{frame}
1719
1720 "))
1721   )
1722
1723 (add-hook
1724  'latex-mode-hook
1725  (lambda ()
1726    (define-key latex-mode-map [(meta S)] 'ff/start-slide)
1727    (define-key latex-mode-map [(control c) (control a)] 'align-current)
1728    (define-key latex-mode-map [(control end)] 'tex-close-latex-block)
1729    (define-key latex-mode-map [(control tab)] 'ispell-complete-word)
1730    (copy-face 'default 'tex-verbatim)
1731    ;; (ff/configure-faces '((tex-verbatim :background "gray95")))
1732    ))
1733
1734 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1735
1736 (defun ff/start-test-code ()
1737   (interactive)
1738   (let ((start (point)))
1739     (insert "
1740 { // ******************************* START ***************************
1741 #warning Test code added on "
1742             (format-time-string "%04Y %b %02d %02H:%02M:%02S" (current-time))
1743             "
1744
1745 } // ******************************** END ****************************
1746
1747 ")
1748     (indent-region start (point) nil))
1749   (previous-line 3)
1750   (c-indent-command))
1751
1752 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1753
1754 (defun ff/code-to-html () (interactive)
1755   (save-restriction
1756     (narrow-to-region (region-beginning) (region-end))
1757     (replace-string "\"" "&quot;" nil (point-min) (point-max))
1758     (replace-string " " "&nbsp;" nil (point-min) (point-max))
1759     (replace-string ">" "&gt;" nil (point-min) (point-max))
1760     (replace-string "<" "&lt;" nil (point-min) (point-max))
1761     (replace-string "\e" "^[" nil (point-min) (point-max))
1762     (replace-string "\7f" "^?" nil (point-min) (point-max))
1763     (replace-string "\1f" "^_" nil (point-min) (point-max))
1764     (replace-regexp "$" "<br />" nil (point-min) (point-max))
1765     )
1766   )
1767
1768 (defun ff/downcase-html-tags () (interactive)
1769   (save-excursion
1770     (beginning-of-buffer)
1771     (while (re-search-forward "<\\([^>]+\\)>" nil t)
1772       (downcase-region (match-beginning 1) (match-end 1)))
1773     )
1774   )
1775
1776 ;; If we enter html mode and there is no makefile around, create a
1777 ;; compilation command with tidy (this is cool stuff)
1778
1779 (add-hook 'html-mode-hook
1780           (lambda ()
1781             (unless (or (not (buffer-file-name))
1782                         (file-exists-p "makefile")
1783                         (file-exists-p "Makefile"))
1784               (set (make-local-variable 'compile-command)
1785                    (let ((fn (file-name-nondirectory buffer-file-name)))
1786                      (format "tidy -utf8 %s > /tmp/%s" fn fn))))))
1787
1788 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1789
1790 (defun ff/count-words-region (beginning end)
1791   "Print number of words in the region.
1792 Words are defined as at least one word-constituent character
1793 followed by at least one character that is not a
1794 word-constituent.  The buffer's syntax table determines which
1795 characters these are."
1796
1797   (interactive "r")
1798   (message "Counting words in region ... ")
1799   (save-excursion
1800     (goto-char beginning)
1801     (let ((count 0))
1802       (while (< (point) end)
1803         (re-search-forward "\\w+\\W+")
1804         (setq count (1+ count)))
1805       (cond ((zerop count) (message "The region does NOT have any word."))
1806             ((= 1 count) (message "The region has 1 word."))
1807             (t (message "The region has %d words." count))))))
1808
1809 ;; (add-hook 'html-mode-hook 'flyspell-mode)
1810
1811 (defun ff/tidy-html ()
1812   "Run tidy in on the content of the current buffer, put the result in
1813 a file in /tmp"
1814   (interactive)
1815   (call-process-region (point-min) (point-max)
1816                        "/usr/bin/tidy"
1817                        nil
1818                        (list nil (make-temp-file "/tmp/tidy-html."))))
1819
1820 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1821
1822 ;; Create the adequate embryo of a file if it does not exist
1823
1824 (defun ff/start-file () (interactive)
1825   (let ((filename (buffer-file-name)))
1826     (when filename
1827
1828       (when (string-match "\\.sh$" filename)
1829         (sh-mode)
1830         (insert "#!/bin/bash\n\nset -e\nset -o pipefail\n\n")
1831         (save-excursion
1832           (ff/add-copyrights))
1833         )
1834
1835       (when (string-match "\\.html$" filename)
1836         (html-mode)
1837         (ff/start-html)
1838         (previous-line 4)
1839         )
1840
1841       (when (string-match "\\.h$" filename)
1842         (c++-mode)
1843         (ff/headerize)
1844         (save-excursion
1845           (ff/add-copyrights)
1846           (newline))
1847         (newline)
1848         (newline)
1849         (previous-line 1)
1850         )
1851
1852       (when (string-match "\\.c$" filename)
1853         (c-mode)
1854         (ff/add-copyrights)
1855         (ff/start-c))
1856
1857       (when (string-match "\.\\(cc\\|cpp\\)$" filename)
1858         (c++-mode)
1859         (ff/add-copyrights)
1860         (let ((headername  (replace-regexp-in-string "\\.\\(cc\\|cpp\\)$" ".h"
1861                                                      filename)))
1862           (if (file-exists-p headername)
1863               (insert (concat "\n#include \"" (file-name-nondirectory headername) "\"\n"))
1864             (ff/start-c++))
1865           ))
1866
1867       (when (string-match "\\.tex$" filename)
1868         (latex-mode)
1869         (ff/start-latex)
1870         ))
1871     )
1872   (set-buffer-modified-p nil)
1873   )
1874
1875 (if (>= emacs-major-version 22)
1876     (add-to-list 'find-file-not-found-functions 'ff/start-file)
1877   (add-to-list 'find-file-not-found-hooks 'ff/start-file))
1878
1879 (when (>= emacs-major-version 24)
1880   (define-obsolete-function-alias 'make-local-hook 'ignore "21.1")
1881   (setq send-mail-function 'sendmail-send-it) ;; emacs 24.x stuff
1882
1883   (custom-set-faces
1884    '(diff-added ((default (:background "gray90" :foreground "green4" :weight bold))))
1885    '(diff-removed ((default (:background "gray90" :foreground "red2" :weight bold))))
1886    '(diff-changed ((default (:background "gray90" :foreground "blue" :weight bold))))
1887    )
1888   )
1889
1890 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1891
1892 (define-key global-map [f8] 'ff-find-other-file)
1893 (define-key global-map [(shift f8)] (lambda () (interactive) (ff-find-other-file t)))
1894
1895 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1896 ;; Antiword, htmlize and boxquote
1897 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1898
1899 (autoload 'no-word "no-word")
1900 (add-to-list 'auto-mode-alist '("\\.doc\\'" . no-word))
1901 ;; (add-to-list 'auto-mode-alist '("\\.DOC\\'" . no-word))
1902
1903 (autoload 'htmlize-buffer "htmlize" nil t)
1904
1905 (setq boxquote-top-and-tail "------------------")
1906 (autoload 'boxquote-region "boxquote" nil t)
1907
1908 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1909 ;; The compilation hacks
1910 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1911
1912 ;; If we enter c++ mode and there is no makefile around, we create a
1913 ;; make command on the fly for the specific object file
1914
1915 (add-hook 'c++-mode-hook
1916           (lambda ()
1917             (unless (or (file-exists-p "makefile") (file-exists-p "Makefile"))
1918               (set (make-local-variable 'compile-command)
1919                    (concat
1920                     "make -k "
1921                     (file-name-sans-extension
1922                      (file-name-nondirectory buffer-file-name)))))))
1923
1924 ;; <f1> runs the compilation according to the compile-command (and
1925 ;; thus does not ask any confirmation), shows the compilation buffer
1926 ;; during compilation and delete all windows showing the compilation
1927 ;; buffer if the compilation ends with no error
1928
1929 ;; <shift-f1> asks for a compilation command and runs the compilation
1930 ;; but does not restore the window configuration (i.e. the compilation
1931 ;; buffer's window will still be visible, as usual)
1932
1933 ;; <f2> goes to the next compilation error (as C-x ` does on the
1934 ;; standard configuration)
1935
1936 (defun ff/restore-windows-if-no-error (buffer msg)
1937   "Delete the windows showing the compilation buffer if msg
1938   matches \"^finished\"."
1939
1940   (when (string-match "^finished" msg)
1941     ;;     (delete-windows-on buffer)
1942     (if (boundp 'ff/window-configuration-before-compilation)
1943         (set-window-configuration ff/window-configuration-before-compilation))
1944     )
1945   )
1946
1947 (add-to-list 'compilation-finish-functions 'ff/restore-windows-if-no-error)
1948
1949 (defun ff/fast-compile ()
1950   "Compiles without asking anything."
1951   (interactive)
1952   (let ((compilation-read-command nil))
1953     (setq ff/window-configuration-before-compilation (current-window-configuration))
1954     (compile compile-command)))
1955
1956 (setq compilation-read-command t
1957       compile-command "make -j -k"
1958       compile-history '("make clean" "make DEBUG=yes -j -k" "make -j -k")
1959       )
1960
1961 (defun ff/universal-compile () (interactive)
1962   (funcall (or (cdr (assoc major-mode
1963                            '(
1964                              (latex-mode . tex-file)
1965                              (html-mode . browse-url-of-buffer)
1966                              ;; Here you can add other mode -> compile command
1967                              )))
1968                'ff/fast-compile         ;; And this is the failsafe
1969                )))
1970
1971 (define-key global-map [f1] 'ff/universal-compile)
1972 (define-key global-map [(shift f1)] 'compile)
1973 (define-key global-map [f2] 'next-error)
1974
1975 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1976 ;; Related to mail
1977 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1978
1979 ;; (when (ff/load-or-alert "flyspell-timer" t)
1980 ;;   (add-hook 'flyspell-mode-hook 'flyspell-timer-ensure-idle-timer))
1981
1982 (defun ff/pick-dictionnary () (interactive)
1983   (when (and (boundp 'flyspell-mode) flyspell-mode)
1984     (if (and current-input-method (string-match "latin" current-input-method))
1985         (ispell-change-dictionary "francais")
1986       (ispell-change-dictionary "american"))
1987     ;;     (flyspell-buffer)
1988     )
1989   )
1990
1991 (defadvice toggle-input-method (after ff/switch-dictionnary nil activate)
1992   (ff/pick-dictionnary))
1993
1994 ;; (add-hook 'message-mode-hook 'auto-fill-mode)
1995 ;; (add-hook 'message-mode-hook 'flyspell-mode)
1996
1997 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1998 ;; Delete all windows which are in the same "column", which means
1999 ;; whose xmin and xmax are bounded by the xmin and xmax of the
2000 ;; currently selected column
2001 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2002
2003 ;; This is from emacs23 ! better than my old ff/delete-other-windows-in-column
2004
2005 (unless (fboundp 'delete-other-windows-vertically)
2006
2007   (defun delete-other-windows-vertically (&optional window)
2008     "Delete the windows in the same column with WINDOW, but not WINDOW itself.
2009 This may be a useful alternative binding for \\[delete-other-windows]
2010  if you often split windows horizontally."
2011     (interactive)
2012     (let* ((window (or window (selected-window)))
2013            (edges (window-edges window))
2014            (w window) delenda)
2015       (while (not (eq (setq w (next-window w 1)) window))
2016         (let ((e (window-edges w)))
2017           (when (and (= (car e) (car edges))
2018                      (= (caddr e) (caddr edges)))
2019             (push w delenda))))
2020       (mapc 'delete-window delenda)))
2021   )
2022
2023 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2024 ;; Misc things
2025 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2026
2027 ;; Entropy is cool
2028
2029 (defun ff/entropy (l)
2030   (apply '+
2031          (mapcar
2032           (lambda (x)
2033             (if (= x 0.0) 0.0
2034               (* (- x) (/ (log x) (log 2)))))
2035           l)
2036          )
2037   )
2038
2039 ;; Usefull to deal with results in latex files
2040
2041 (defun ff/round-floats-in-region () (interactive)
2042   (save-restriction
2043     (condition-case nil
2044         (narrow-to-region (region-beginning) (region-end))
2045       (error (thing-at-point 'word)))
2046     (save-excursion
2047       (goto-char (point-min))
2048       (while (re-search-forward "[0-9\.]+" nil t)
2049         (let ((value (string-to-number (buffer-substring (match-beginning 0) (match-end 0)))))
2050           (delete-region (match-beginning 0) (match-end 0))
2051           (insert (format "%0.2f" value)))))))
2052
2053 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2054 ;; Keymaping
2055 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2056
2057 (load "info" nil t)
2058
2059 (define-key global-map [(shift iso-lefttab)] 'ispell-complete-word)
2060 ;; shift-tab going backward is kind of standard
2061 (define-key Info-mode-map [(shift iso-lefttab)] 'Info-prev-reference)
2062
2063 ;; (define-key global-map [(control x) (control a)] 'auto-fill-mode)
2064
2065 ;; Put back my keys, you thief!
2066 (define-key global-map [(home)] 'beginning-of-buffer)
2067 (define-key global-map [(end)] 'end-of-buffer)
2068 ;; (define-key global-map [(insertchar)] 'overwrite-mode)
2069 (define-key global-map [(delete)] 'delete-char)
2070
2071 ;; Cool shortcuts to move to the end / beginning of block keen
2072 (define-key global-map [(control right)] 'forward-sexp)
2073 (define-key global-map [(control left)] 'backward-sexp)
2074
2075 ;; Wheel mouse moves up and down 2 lines (and DO NOT BEEP when we are
2076 ;; out of the buffer)
2077
2078 (define-key global-map [mouse-4]
2079   (lambda () (interactive) (condition-case nil (scroll-down 2) (error nil))))
2080 (define-key global-map [mouse-5]
2081   (lambda () (interactive) (condition-case nil (scroll-up 2) (error nil))))
2082
2083 ;; with shift it goes faster
2084 (define-key global-map [(shift mouse-4)]
2085   (lambda () (interactive) (condition-case nil (scroll-down 50) (error nil))))
2086 (define-key global-map [(shift mouse-5)]
2087   (lambda () (interactive) (condition-case nil (scroll-up 50) (error nil))))
2088
2089 ;; Meta-? shows the properties of the character at point
2090 (define-key global-map [(meta ??)]
2091   (lambda () (interactive)
2092     (message (prin1-to-string (text-properties-at (point))))))
2093
2094 ;; Compiles the latex file in the current buffer
2095
2096 (setq tex-start-commands "\\input")
2097 (define-key global-map [f3] 'tex-file)
2098 (define-key global-map [(shift f3)] 'tex-bibtex-file)
2099
2100 ;; To run xdvi on the dvi associated to the .tex in the current
2101 ;; buffer, and to edit the .fig or bitmap image used to generate the
2102 ;; .eps at point
2103
2104 (define-key global-map [f4] 'ff/run-viewer)
2105
2106 ;; Closes the current \begin{}
2107
2108 (when (ff/load-or-alert "longlines")
2109
2110   (setq longlines-show-hard-newlines t
2111         longlines-auto-wrap t
2112         ;; longlines-show-effect #("|\n" 0 2 (face escape-glyph))
2113         ;; longlines-show-effect #("∴\n" 0 2 (face escape-glyph))
2114         longlines-show-effect #("•\n" 0 2 (face escape-glyph))
2115         ;; longlines-show-effect #("↵\n" 0 2 (face escape-glyph))
2116         )
2117
2118   ;; (defun ff/auto-longlines ()
2119   ;; (when (save-excursion
2120   ;; (goto-char (point-min))
2121   ;; (re-search-forward "^.\\{81,\\}$" nil t))
2122   ;; (longlines-mode)
2123   ;; (message "Switched on the lonlines mode automatically")
2124   ;; ))
2125
2126   ;; (add-hook 'latex-mode-hook 'ff/auto-longlines)
2127
2128   )
2129
2130 ;; Meta-/ remaped (completion)
2131
2132 (define-key global-map [(shift right)] 'dabbrev-expand)
2133 (define-key global-map [(meta =)] 'dabbrev-expand)
2134
2135 ;; Change the current window.
2136
2137 (defun ff/next-same-frame-window () (interactive)
2138   (select-window (next-window (selected-window)
2139                               (> (minibuffer-depth) 0)
2140                               nil)))
2141
2142 (defun ff/previous-same-frame-window () (interactive)
2143   (select-window (previous-window (selected-window)
2144                                   (> (minibuffer-depth) 0)
2145                                   nil)))
2146
2147 (define-key global-map [(shift prior)] 'ff/next-same-frame-window)
2148 (define-key global-map [(shift next)] 'ff/previous-same-frame-window)
2149
2150 (define-key global-map [(control })] 'enlarge-window-horizontally)
2151 (define-key global-map [(control {)] 'shrink-window-horizontally)
2152 (define-key global-map [(control \")] 'enlarge-window)
2153 (define-key global-map [(control :)] 'shrink-window)
2154
2155 ;; (define-key global-map [(control shift prior)] 'next-multiframe-window)
2156 ;; (define-key global-map [(control shift next)] 'previous-multiframe-window)
2157
2158 ;; I have two screens sometime!
2159
2160 (define-key global-map [(meta next)] 'other-frame)
2161 (define-key global-map [(meta prior)] (lambda () (interactive) (other-frame -1)))
2162
2163 (define-key global-map [(shift home)] 'delete-other-windows-vertically)
2164
2165 ;; (define-key global-map [(control +)] 'enlarge-window)
2166 ;; (define-key global-map [(control -)] 'shrink-window)
2167
2168 ;; Goes to next/previous buffer
2169
2170 (define-key global-map [(control prior)] 'ff/next-buffer)
2171 (define-key global-map [(control next)] 'ff/prev-buffer)
2172
2173 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2174 ;; If M-. on a symbol, show where it is defined in another window
2175 ;; without giving focus, cycle if repeated.
2176 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2177
2178 (when (ff/load-or-alert "etags")
2179
2180   (defun ff/find-tag-nofocus () (interactive)
2181     "Show in another window the definition of the current tag"
2182     (let ((tag (find-tag-default)))
2183       (display-buffer (find-tag-noselect tag (string= tag last-tag)))
2184       (message "Tag %s" tag)
2185       )
2186     )
2187
2188   (define-key global-map [(meta .)] 'ff/find-tag-nofocus)
2189   )
2190
2191 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2192 ;; Destroys the current buffer and its window if it's not the only one
2193 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2194
2195 (defcustom ff/kill-this-buffer-and-delete-window-exceptions ""
2196   "*Regexp matching the buffer names which have to be kept when using
2197 `ff/kill-this-buffer-and-delete-window'.")
2198
2199 (defun ff/kill-this-buffer-and-delete-window (universal)
2200   "Unless its name matches
2201 `ff/kill-this-buffer-and-delete-window-exceptions', kills the
2202 current buffer and deletes the current window if it's not the
2203 only one in the frame. If the buffer has to be kept, go to the
2204 next one. With universal argument, kill all killable buffers."
2205   (interactive "P")
2206   (if universal
2207       (let ((nb-killed 0))
2208         (mapc (lambda (x)
2209                 (unless (string-match ff/kill-this-buffer-and-delete-window-exceptions
2210                                       (buffer-name x))
2211                   (kill-buffer x)
2212                   (setq nb-killed (1+ nb-killed))
2213                   ))
2214               (buffer-list))
2215         (message "Killed %d buffer%s" nb-killed (if (> nb-killed 1) "s" "")))
2216     (if (string-match ff/kill-this-buffer-and-delete-window-exceptions (buffer-name))
2217         (ff/next-buffer)
2218       (kill-this-buffer)))
2219   ;; (unless (one-window-p t) (delete-window))
2220   )
2221
2222 (define-key global-map [(control backspace)] 'ff/kill-this-buffer-and-delete-window)
2223 ;; (define-key calc-mode-map [(control backspace)] 'calc-quit)
2224
2225
2226 (setq ff/kill-this-buffer-and-delete-window-exceptions
2227       "^ \\|\\*Messages\\*\\|\\*scratch\\*\\|\\*Group\\*\\|\\*-jabber-\\*\\|\\*-jabber-process-\\*\\|\\*media\\*")
2228
2229 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2230 ;; Misc stuff
2231 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2232
2233 (defun ff/elisp-debug-on ()
2234   "Switches `debug-on-error' and `debug-on-quit'."
2235   (interactive)
2236   (if debug-on-error
2237       (setq debug-on-error nil
2238             debug-on-quit nil)
2239     (setq debug-on-error t
2240           debug-on-quit t))
2241   (if debug-on-error
2242       (message "elisp debug on")
2243     (message "elisp debug off")))
2244
2245 (defun ff/create-dummy-buffer (&optional universal) (interactive "P")
2246   (find-file (concat "/tmp/" (ff/non-existing-filename "/tmp/" "dummy" "")))
2247   (text-mode)
2248   (if universal (ff/insert-url (current-kill 0)))
2249   (message "New dummy text-mode buffer"))
2250
2251 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2252 ;; Recentf to keep a list of recently visited files. I use it
2253 ;; exclusively with my selector.el
2254 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2255
2256 (load "recentf")
2257
2258 ;; If we just check for file-symlink-p, everytime we start emacs it
2259 ;; will check all the remote files listed in recentf-list, so we check
2260 ;; that they are not remote first
2261 (defun ff/file-not-remote-but-symlink (filename)
2262   (and (not (file-remote-p filename)) (file-symlink-p filename)))
2263
2264 (setq recentf-exclude (append recentf-exclude
2265                               '(
2266                                 ff/file-not-remote-but-symlink
2267                                 "enotes$" "secure-notes$" "media-playlists$"
2268                                 "bbdb$"
2269                                 "svn-commit.tmp$" ".git/COMMIT_EDITMSG$"
2270                                 "\.bbl$" "\.aux$" "\.toc$"
2271                                 ))
2272       recentf-max-saved-items 1000
2273       recentf-save-file "~/private/emacs/recentf"
2274       )
2275
2276 (when (boundp 'recentf-keep) (add-to-list 'recentf-keep 'file-remote-p))
2277
2278 (recentf-mode 1)
2279
2280 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2281 ;; My front-end to mplayer
2282 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2283
2284 ;; (ff/compile-when-needed "media/mplayer")
2285 ;; (ff/compile-when-needed "media")
2286
2287 (when (ff/load-or-alert "media")
2288
2289   (unless window-system
2290     (ff/configure-faces
2291      '(
2292        (media/mode-string-face
2293         :foreground "blue4" :weight 'bold)
2294
2295        (media/current-tune-face
2296         :foreground "black" :background "yellow" :weight 'normal)
2297
2298        (media/instant-highlight-face
2299         :foreground "black" :background "orange" :weight 'normal)
2300        ))
2301     )
2302
2303   (define-key global-map [(meta \\)] 'media)
2304
2305   (setq media/expert t
2306         media/add-current-song-to-interrupted-when-killing t
2307         media/duration-to-history 30
2308         media/history-size 1000
2309         media/playlist-file "~/private/emacs/media-playlists"
2310         media/mplayer/args '(
2311                              "-framedrop"
2312                              "-zoom"
2313                              "-cache" "512"
2314                              "-subfont-osd-scale" "3"
2315                              ;; "-stop-xscreensaver"
2316                              ;; "-osdlevel" "3"
2317                              )
2318         media/mplayer/timing-request-period 5.0
2319         )
2320   )
2321
2322 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2323 ;; A dynamic search
2324 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2325
2326 ;; selector.el is one of my own scripts, check my web page
2327
2328 (when (ff/load-or-alert "selector" t)
2329   ;; (define-key global-map [(shift return)] 'selector/quick-move-in-buffer)
2330   (define-key global-map [(control x) (control b)] 'selector/switch-buffer)
2331
2332   (defun ff/visit-debpkg-file (&optional regexp)
2333     "This function lists all the files found with dpkg -S and
2334 proposes to visit them."
2335     (interactive "sPattern: ")
2336
2337     (selector/select
2338
2339      (mapcar
2340       (lambda (s)
2341         (cons (selector/filename-to-string s) s))
2342       (split-string
2343        (shell-command-to-string (concat "dpkg -S " regexp " | awk '{print $2}'"))))
2344
2345      'selector/find-file
2346      "*selector find-file*"
2347      ))
2348   )
2349
2350 (add-hook 'selector/mode-hook (lambda () (setq truncate-lines t)))
2351
2352 (defun ff/selector-insert-record-callback (r)
2353   (bbdb-display-records (list r))
2354   ;; Weird things will happen if you kill the buffer from which you
2355   ;; invoked ff/selector-mail-from-bbdb
2356   (insert (car (elt r 6)))
2357   )
2358
2359 (defun ff/selector-compose-mail-callback (r)
2360   (vm-compose-mail (car (elt r 6)))
2361   )
2362
2363 (defun ff/selector-mail-from-bbdb () (interactive)
2364   (selector/select
2365    (mapcar
2366     (lambda (r) (cons (concat (elt r 0)
2367                               " "
2368                               (elt r 1)
2369                               " ("
2370                               (car (elt r 6))
2371                               ")")
2372                       r))
2373     (bbdb-records))
2374    (if (string= mode-name "Mail")
2375        'ff/selector-insert-record-callback
2376      'ff/selector-compose-mail-callback)
2377    "*bbdb-search*"
2378    )
2379   )
2380
2381 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2382 ;; A function to remove temporary alarm windows
2383 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2384
2385 (defcustom ff/annoying-windows-regexp
2386   "\\*Messages\\*\\|\\*compilation\\*\\|\\*tex-shell\\*\\|\\*Help\\*\\|\\*info\\*\\|\\*Apropos\\*\\|\\*BBDB\\*\\|\\*.*-diff\\*"
2387   "The regexp matching the windows to be deleted by `ff/delete-annoying-windows'"
2388   )
2389
2390 (defun ff/delete-annoying-windows ()
2391   "Close all the windows showing buffers whose names match
2392 `ff/annoying-windows-regexp'."
2393   (interactive)
2394   (when ff/annoying-windows-regexp
2395     (mapc (lambda (w)
2396             (when (and (not (one-window-p w))
2397                        (string-match ff/annoying-windows-regexp
2398                                      (buffer-name (window-buffer w))))
2399               (delete-window w)))
2400           (window-list)
2401           )
2402     (message "Removed annoying windows")
2403     )
2404   )
2405
2406 (setq ff/annoying-windows-regexp
2407       (concat ff/annoying-windows-regexp
2408               "\\|\\*unspooled mails\\*\\|\\*enotes alarms\\*\\|\\*system info\\*"))
2409
2410 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2411 ;; Some handy functions
2412 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2413
2414 (defun ff/twin-horizontal-current-buffer () (interactive)
2415   (delete-other-windows)
2416   (split-window-horizontally)
2417   (balance-windows)
2418   )
2419
2420 (defun ff/twin-vertical-current-buffer () (interactive)
2421   (delete-other-windows)
2422   (split-window-vertically)
2423   (balance-windows)
2424   )
2425
2426 (defun ff/flyspell-mode (arg) (interactive "p")
2427   (if flyspell-mode (flyspell-mode -1)
2428     (flyspell-mode 1)
2429     (flyspell-buffer))
2430 )
2431
2432 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2433 ;; The fridge!
2434 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2435
2436 (defun ff/move-region-to-fridge () (interactive)
2437   "Cut the current region, paste it in a file called ./fridge
2438 with a time tag, and save this file"
2439   (unless (use-region-p) (error "No region selected"))
2440   (let ((bn (file-name-nondirectory (buffer-file-name))))
2441     (kill-region (region-beginning) (region-end))
2442     (with-current-buffer (find-file-noselect "fridge")
2443       (goto-char (point-max))
2444       (insert "\n")
2445       (insert "######################################################################\n")
2446       (insert "\n"
2447               (format-time-string "%Y %b %d %H:%M:%S" (current-time))
2448               " (from "
2449               bn
2450               ")\n\n")
2451       (yank)
2452       (save-buffer)
2453       (message "Region moved to fridge")
2454       )
2455     )
2456   )
2457
2458 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2459 ;; My own keymap
2460 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2461
2462 (setq ff/map (make-sparse-keymap))
2463 (define-key global-map [(control \`)] ff/map)
2464 ;;(define-key global-map [(control @)] ff/map)
2465
2466 (define-key esc-map "`" ff/map)
2467
2468 (defun ff/git-status (&optional dir) (interactive)
2469   (if (buffer-file-name)
2470       (git-status (file-name-directory (buffer-file-name)))
2471     (error "No file attached to this buffer")))
2472
2473 (defun ff/insert-date () (interactive)
2474   (insert (format-time-string "\n * %Y %b %d %H:%M:%S\n\n" (current-time)))
2475   )
2476
2477 (define-key ff/map [(control g)] 'ff/git-status)
2478 (define-key ff/map [(control w)] 'server-edit)
2479 (define-key ff/map [(control d)] 'ff/elisp-debug-on)
2480 ;; (define-key ff/map "d" 'diary)
2481 (define-key ff/map "d" 'ff/insert-date)
2482 (define-key ff/map [(control \`)] 'ff/bash-new-buffer)
2483 (define-key ff/map [(control n)] 'enotes/show-all-notes)
2484 (define-key ff/map [(control s)] 'ff/secure-note-add)
2485 (define-key ff/map [(control t)] 'ff/start-test-code)
2486 (define-key ff/map [(control q)] 'ff/create-dummy-buffer)
2487 (define-key ff/map [(control a)] 'auto-fill-mode)
2488 (define-key ff/map [(control i)] 'ff/system-info)
2489 (define-key ff/map "w" 'ff/word-occurences)
2490 (define-key ff/map [(control c)] 'calendar)
2491 ;; (define-key ff/map [(control c)] (lambda () (interactive) (save-excursion (calendar))))
2492 (define-key ff/map [(control l)] 'goto-line)
2493 (define-key ff/map "l" 'longlines-mode)
2494 (define-key ff/map [(control o)] 'selector/quick-pick-recent)
2495 (define-key ff/map "s" 'selector/quick-move-in-buffer)
2496 (define-key ff/map "S" 'selector/search-sentence)
2497 (define-key ff/map "t" (lambda () (interactive) (find-file "~/private/TODO.txt")))
2498 (define-key ff/map "h" 'ff/tidy-html)
2499 (define-key ff/map "c" 'ff/count-char)
2500 (define-key ff/map [(control p)] 'ff/print-to-file)
2501 (define-key ff/map "P" 'ff/print-to-printer)
2502 (define-key ff/map [(control b)] 'bbdb)
2503 (define-key ff/map "m" 'ff/selector-mail-from-bbdb)
2504 (define-key ff/map [(control m)] 'woman)
2505 (define-key ff/map "b" 'bookmark-jump)
2506 (define-key ff/map [(control =)] 'calc)
2507 (define-key ff/map [(control shift b)]
2508   (lambda () (interactive)
2509     (bookmark-set)
2510     (bookmark-save)))
2511 (define-key ff/map "f" 'ff/move-region-to-fridge)
2512 (define-key ff/map [(control f)] 'ff/flyspell-mode)
2513
2514 (define-key ff/map [?\C-0] 'ff/delete-annoying-windows)
2515 (define-key ff/map "1" 'delete-other-windows)
2516 (define-key ff/map [?\C-1] 'delete-other-windows)
2517 (define-key ff/map "2" 'ff/twin-vertical-current-buffer)
2518 (define-key ff/map [?\C-2] 'ff/twin-vertical-current-buffer)
2519 (define-key ff/map "3" 'ff/twin-horizontal-current-buffer)
2520 (define-key ff/map [?\C-3] 'ff/twin-horizontal-current-buffer)
2521
2522 (define-key ff/map " " 'delete-trailing-whitespace)
2523
2524 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2525 ;; Hacks so that all keys are functionnal in xterm and through ssh.
2526 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2527
2528 (unless window-system
2529
2530   ;; One day I will understand these clipboard business. Until then,
2531   ;; so that it works in xterm (yes), let's use xclip. This is a bit
2532   ;; ugly.
2533
2534   ;; (defun ff/yank-with-xclip (&optional arg)
2535   ;; "Paste the content of the X clipboard with the xclip
2536   ;; command. Without ARG converts some of the '\\uxxxx' characters."
2537   ;; (interactive "P")
2538   ;; (with-temp-buffer
2539   ;; (shell-command "xclip -o" t)
2540   ;; (unless arg
2541   ;; (mapc (lambda (x) (replace-string (concat "\\u" (car x)) (cdr x) nil (point-min) (point-max)))
2542   ;; '(("fffd" . "??")
2543   ;; ("2013" . "-")
2544   ;; ("2014" . "--")
2545   ;; ("2018" . "`")
2546   ;; ("2019" . "'")
2547   ;; ("201c" . "``")
2548   ;; ("201d" . "''")
2549   ;; ("2022" . "*")
2550   ;; ("2026" . "...")
2551   ;; ("20ac" . "EUR")
2552   ;; )))
2553   ;; (kill-ring-save (point-min) (point-max)))
2554
2555   ;; (yank))
2556
2557   ;; (define-key global-map [(meta y)] 'ff/yank-with-xclip)
2558
2559   ;;   (set-terminal-coding-system 'iso-latin-1)
2560   ;; (set-terminal-coding-system 'utf-8)
2561
2562   ;; I have in my .Xressource
2563
2564   ;; XTerm.VT100.translations: #override\n\
2565   ;;   <Btn4Down>,<Btn4Up>:scroll-back(2,line)\n\
2566   ;;   <Btn5Down>,<Btn5Up>:scroll-forw(2,line)\n\
2567   ;;   Ctrl<Btn4Down>,Ctrl<Btn4Up>:scroll-back(1,page)\n\
2568   ;;   Ctrl<Btn5Down>,Ctrl<Btn5Up>:scroll-forw(1,page)\n\
2569   ;;   Shift<Btn4Down>,Shift<Btn4Up>:scroll-back(1,halfpage)\n\
2570   ;;   Shift<Btn5Down>,Shift<Btn5Up>:scroll-forw(1,halfpage)\n\
2571   ;;   Alt<KeyPress>:insert-eight-bit()\n\
2572   ;;   !Shift<Key>BackSpace: string("\7f")\n\
2573   ;;   Ctrl<Key>BackSpace: string("\eOZ")\n\
2574   ;;   Shift<Key>Prior: string("\e[5;2~")\n\
2575   ;;   Shift<Key>Next: string("\e[6;2~")\n\
2576   ;;   Shift Ctrl<Key>]: string("\eO}")\n\
2577   ;;   Shift Ctrl<Key>[: string("\eO{")\n\
2578   ;;   Shift Ctrl<Key>/: string("\eO?")\n\
2579   ;;   Ctrl<Key>/: string("\eO/")\n\
2580   ;;   Shift Ctrl<Key>=: string("\eO+")\n\
2581   ;;   Ctrl<Key>=: string("\eO=")\n\
2582   ;;   Shift Ctrl<Key>;: string("\eO:")\n\
2583   ;;   Ctrl<Key>;: string("\eO;")\n\
2584   ;;   Shift Ctrl<Key>`: string("\eO~")\n\
2585   ;;   Ctrl<Key>`: string("\eO`")\n\
2586   ;;   Shift Ctrl<Key>': string("\eO\\\"")\n\
2587   ;;   Ctrl<Key>': string("\eO'")\n\
2588   ;;   Shift Ctrl<Key>.: string("\eO>")\n\
2589   ;;   Ctrl<Key>.: string("\eO.")\n\
2590   ;;   Shift Ctrl<Key>\\,: string("\eO<")\n\
2591   ;;   Ctrl<Key>\\,: string("\eO,")
2592
2593   (define-key function-key-map "\e[2~" [insert])
2594
2595   (define-key function-key-map "\e[Z" [S-iso-lefttab])
2596
2597   (define-key function-key-map "\e[1;2A" [S-up])
2598   (define-key function-key-map "\e[1;2B" [S-down])
2599   (define-key function-key-map "\e[1;2C" [S-right])
2600   (define-key function-key-map "\e[1;2D" [S-left])
2601   (define-key function-key-map "\e[1;2F" [S-end])
2602   (define-key function-key-map "\e[1;2H" [S-home])
2603
2604   (define-key function-key-map "\e[2;2~" [S-insert])
2605   (define-key function-key-map "\e[5;2~" [S-prior])
2606   (define-key function-key-map "\e[6;2~" [S-next])
2607
2608   (define-key function-key-map "\e[1;2P" [S-f1])
2609   (define-key function-key-map "\e[1;2Q" [S-f2])
2610   (define-key function-key-map "\e[1;2R" [S-f3])
2611   (define-key function-key-map "\e[1;2S" [S-f4])
2612   (define-key function-key-map "\e[15;2~" [S-f5])
2613   (define-key function-key-map "\e[17;2~" [S-f6])
2614   (define-key function-key-map "\e[18;2~" [S-f7])
2615   (define-key function-key-map "\e[19;2~" [S-f8])
2616   (define-key function-key-map "\e[20;2~" [S-f9])
2617   (define-key function-key-map "\e[21;2~" [S-f10])
2618
2619   (define-key function-key-map "\e[1;5A" [C-up])
2620   (define-key function-key-map "\e[1;5B" [C-down])
2621   (define-key function-key-map "\e[1;5C" [C-right])
2622   (define-key function-key-map "\e[1;5D" [C-left])
2623   (define-key function-key-map "\e[1;5F" [C-end])
2624   (define-key function-key-map "\e[1;5H" [C-home])
2625
2626   (define-key function-key-map "\e[2;5~" [C-insert])
2627   (define-key function-key-map "\e[5;5~" [C-prior])
2628   (define-key function-key-map "\e[6;5~" [C-next])
2629
2630   (define-key function-key-map "\e[1;9A" [M-up])
2631   (define-key function-key-map "\e[1;9B" [M-down])
2632   (define-key function-key-map "\e[1;9C" [M-right])
2633   (define-key function-key-map "\e[1;9D" [M-left])
2634   (define-key function-key-map "\e[1;9F" [M-end])
2635   (define-key function-key-map "\e[1;9H" [M-home])
2636
2637   (define-key function-key-map "\e[2;9~" [M-insert])
2638   (define-key function-key-map "\e[5;9~" [M-prior])
2639   (define-key function-key-map "\e[6;9~" [M-next])
2640
2641   ;; The following ones are not standard
2642
2643   (define-key function-key-map "\eO}" (kbd "C-}"))
2644   (define-key function-key-map "\eO{" (kbd "C-{"))
2645   (define-key function-key-map "\eO?" (kbd "C-?"))
2646   (define-key function-key-map "\eO/" (kbd "C-/"))
2647   (define-key function-key-map "\eO:" (kbd "C-:"))
2648   (define-key function-key-map "\eO;" (kbd "C-;"))
2649   (define-key function-key-map "\eO~" (kbd "C-~"))
2650   (define-key function-key-map "\eO`" (kbd "C-\`"))
2651   (define-key function-key-map "\eO\"" (kbd "C-\""))
2652   (define-key function-key-map "\eO|" (kbd "C-|"))
2653   (define-key function-key-map "\eO'" (kbd "C-'"))
2654   (define-key function-key-map "\eO>" (kbd "C->"))
2655   (define-key function-key-map "\eO." (kbd "C-."))
2656   (define-key function-key-map "\eO<" (kbd "C-<"))
2657   (define-key function-key-map "\eO," (kbd "C-,"))
2658   (define-key function-key-map "\eO-" (kbd "C--"))
2659   (define-key function-key-map "\eO=" (kbd "C-="))
2660   (define-key function-key-map "\eO+" (kbd "C-+"))
2661
2662   (define-key function-key-map "\eOZ" [C-backspace])
2663
2664   (define-key minibuffer-local-map "\10" 'previous-history-element)
2665   (define-key minibuffer-local-map "\ e" 'next-history-element)
2666
2667   ;; (define-key global-map [(alt prior)] 'ff/prev-buffer)
2668   ;; (define-key global-map [(alt next)] 'ff/next-buffer)
2669
2670   )
2671
2672 ;; I am fed up with Alt-Backspace in the minibuffer erasing the
2673 ;; content of the kill-ring
2674
2675 (defun ff/backward-delete-word (arg)
2676   "Delete characters forward until encountering the end of a word, but do not put them in the kill ring.
2677 With argument ARG, do this that many times."
2678   (interactive "p")
2679   (delete-region (point) (progn (forward-word (- arg)) (point))))
2680
2681 (define-key minibuffer-local-map
2682   [remap backward-kill-word] 'ff/backward-delete-word)
2683
2684 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2685 ;; Privacy
2686 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2687
2688 ;; Where to save the bookmarks and where is bbdb
2689
2690 (setq bookmark-default-file "~/private/emacs/bmk"
2691       bbdb-file "~/private/bbdb"
2692       custom-file "~/private/emacs/custom")
2693
2694 ;; enotes.el is one of my own scripts, check my web page
2695
2696 (when (ff/load-or-alert "enotes" t)
2697   (setq enotes/file "~/private/enotes"
2698         enotes/show-help nil
2699         enotes/full-display nil
2700         enotes/default-time-fields "9:30")
2701
2702   (enotes/init)
2703   ;; (add-hook 'enotes/alarm-hook
2704   ;;  (lambda () (ff/play-sound-async "~/local/sounds/three_notes2.wav")))
2705   )
2706
2707 ;; (when (ff/load-or-alert "goto-last-change.el")
2708 ;; (define-key global-map [(control x) (control a)] 'goto-last-change))
2709
2710 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2711 ;; My private stuff (email adresses, mail filters, etc.)
2712 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2713
2714 (ff/load-or-alert "~/private/emacs.perso.el" t)
2715
2716 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2717 ;; emacs server
2718 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2719
2720 ;; Runs in server mode, so that emacsclient works
2721 (server-start)
2722
2723 (defun ff/raise-frame-and-give-focus ()
2724   (when window-system
2725     (raise-frame)
2726     (x-focus-frame (selected-frame))
2727     (set-mouse-pixel-position (selected-frame) 4 4)
2728     ))
2729
2730 ;; Raises the window when the server is invoked
2731
2732 (add-hook 'server-switch-hook 'ff/raise-frame-and-give-focus)