Added the colorization of the counters.
[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/word-occurences ()
609   "Display in a new buffer the list of words sorted by number of
610 occurrences "
611   (interactive)
612
613   (let ((buf (get-buffer-create "*word counting*"))
614         (map (make-sparse-keymap))
615         (nb (make-hash-table))
616         (st (make-hash-table))
617         (result nil))
618
619     ;; Collects all words in a hash table
620
621     (save-excursion
622       (goto-char (point-min))
623       (while (re-search-forward "\\([\\-a-zA-Z\\\\]+\\)" nil t)
624         (let* ((s (downcase (match-string-no-properties 1)))
625                (k (sxhash s)))
626           (puthash k s st)
627           (puthash k (1+ (gethash k nb 0)) nb))))
628
629     ;; Creates the result buffer
630
631     (define-key map "q" 'kill-this-buffer)
632     (display-buffer buf)
633     (set-buffer buf)
634     (setq show-trailing-whitespace nil)
635     (erase-buffer)
636
637     ;; Builds a list from the hash table
638
639     (maphash
640      (lambda (key value)
641        (setq result (cons (cons value (gethash key st)) result)))
642      nb)
643
644     ;; Sort and display it
645
646     (mapc (lambda (x)
647             (if (and (> (car x) 3)
648                      ;; No leading backslash and at least four characters
649                      (string-match "^[^\\]\\{4,\\}" (cdr x))
650                      )
651                 (insert (number-to-string (car x)) " " (cdr x) "\n")))
652           (sort result (lambda (a b) (> (car a) (car b)))))
653
654     ;; Adjust the window size and stuff
655
656     (fit-window-to-buffer (get-buffer-window buf))
657     (use-local-map map)
658     (set-buffer-modified-p nil))
659   )
660
661 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
662 ;; Printing
663 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
664
665 (load "ps-print")
666
667 (setq ps-print-color-p nil
668       ps-paper-type 'letter
669       ;; ps-paper-type 'a4
670       ;; ps-top-margin (* 1.75 56.692)
671       ;; ps-left-margin 56.692
672       ;; ps-bottom-margin 56.692
673       ;; ps-right-margin 56.692
674
675       ;; Simple header. Remove that silly frame shadow.
676       ps-print-header nil
677       ps-print-header-frame nil
678       ps-header-line-pad 0.3
679       ps-header-font-family 'Courier
680       ps-header-title-font-size '(8.5 . 10)
681       ps-header-font-size '(6 . 7)
682       ps-font-size '(7 . 8)
683       )
684
685 (ps-put 'ps-header-frame-alist 'back-color 1.0)
686 (ps-put 'ps-header-frame-alist 'shadow-color 1.0)
687 (ps-put 'ps-header-frame-alist 'border-color 0.0)
688 (ps-put 'ps-header-frame-alist 'border-width 0.0)
689
690 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
691
692 ;; http://blog.tuxicity.se/elisp/emacs/2010/03/26/rename-file-and-buffer-in-emacs.htm
693
694 (defun rename-file-and-buffer ()
695   "Renames current buffer and file it is visiting."
696   (interactive)
697   (let ((name (buffer-name))
698         (filename (buffer-file-name)))
699     (if (not (and filename (file-exists-p filename)))
700         (message "Buffer '%s' is not visiting a file!" name)
701       (let ((new-name (read-file-name "New name: " filename)))
702         (cond ((get-buffer new-name)
703                (message "A buffer named '%s' already exists!" new-name))
704               (t
705                (rename-file name new-name 1)
706                (rename-buffer new-name)
707                (set-visited-file-name new-name)
708                (set-buffer-modified-p nil)))))))
709
710 (global-set-key (kbd "C-c r") 'rename-file-and-buffer)
711
712 (defun ff/non-existing-filename (dir prefix suffix)
713   "Returns a filename of the form DIR/PREFIX[.n].SUFFIX whose file does
714 not exist"
715   (let ((n 0)
716         (f (concat prefix suffix)))
717     (while (file-exists-p (concat dir "/" f))
718       (setq n (1+ n)
719             f (concat prefix "." (prin1-to-string n) suffix)))
720     f))
721
722 (defun ff/print-buffer-or-region-with-faces (&optional file)
723
724   ;; I am fed up with spell checking highlights
725   (when (and flyspell-mode
726              ;; (or ispell-minor-mode flyspell-mode)
727              (not (y-or-n-p "The spell checking is on, still print ? ")))
728     (error "Printing cancelled, the spell-checking is on"))
729
730   (unless
731       (condition-case nil
732           (ps-print-region-with-faces (region-beginning) (region-end) file)
733         (error nil))
734     (ps-print-buffer-with-faces file)))
735
736 (defun ff/print-to-file (file)
737   "Prints the region if selected or the whole buffer in postscript
738 into FILE."
739   (interactive
740    (list
741     (read-file-name
742      "PS file: " "/tmp/" nil nil
743      (ff/non-existing-filename
744       "/tmp"
745       (replace-regexp-in-string "[^a-zA-Z0-9_.-]" "_" (file-name-nondirectory
746                                                        (buffer-name)))
747       ".ps"))
748     ))
749   (ff/print-buffer-or-region-with-faces file))
750
751 (defun ff/print-to-printer ()
752   "Prints the region if selected or the whole buffer to a postscript
753 printer."
754   (interactive)
755   (message "Printing to '%s'" (getenv "PRINTER"))
756   (ff/print-buffer-or-region-with-faces))
757
758 ;; Can you believe it? There is a "print" key on PC keyboards ...
759
760 (define-key global-map [(print)] 'ff/print-to-file)
761 (define-key global-map [(shift print)] 'ff/print-to-printer)
762
763 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
764 ;; Dealing with the laptop battery
765 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
766
767 (defcustom ff/battery-dir "/sys/class/power_supply/BAT0"
768   "*Where to gather the battery information")
769
770 (defcustom ff/temperature-file "/sys/class/thermal/thermal_zone0/temp"
771   "*Where to gather the thermal information")
772
773 (defun ff/file-first-line (file)
774   (with-temp-buffer
775     (insert-file-contents-literally file)
776     (buffer-substring (point-at-bol) (point-at-eol))))
777
778 (defun ff/battery-percent (prefix)
779   (condition-case nil
780       (/ (* 100 (string-to-number (ff/file-first-line (format "%s/%s_now" ff/battery-dir prefix))))
781          (string-to-number (ff/file-first-line (format "%s/%s_full"  ff/battery-dir prefix))))
782     (error -1))
783   )
784
785 (defun ff/laptop-info-string () (interactive)
786   (condition-case nil
787       (concat
788
789        ;; The temperature
790
791        (let ((temp (/ (string-to-number (ff/file-first-line ff/temperature-file)) 1000)))
792          (if (> temp 50)
793              (concat
794               (let ((s (format "%dC " temp)))
795                 (if (> temp 65) (propertize s 'face
796                                             'font-lock-warning-face)
797                   s))
798               )
799            )
800          )
801
802        ;; The battery
803
804        (let ((battery-status (ff/file-first-line (concat ff/battery-dir "/status"))))
805
806          (cond
807           ((string= battery-status "Full") "L")
808
809           ((string= battery-status "Charging")
810            (format "L%d%%" (max (ff/battery-percent "charge")
811                                 (ff/battery-percent "energy"))))
812
813           ((string= battery-status "Discharging")
814            (let* ((c (max (ff/battery-percent "charge")
815                           (ff/battery-percent "energy")))
816                   (s (format "B%d%%" c)))
817              (if (>= c 20) s (propertize s 'face 'font-lock-warning-face))))
818
819           (t battery-status)
820
821           ))
822
823        )
824
825     (error nil))
826   )
827
828 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
829
830 (defun ff/system-info () (interactive)
831
832   (let ((buf (get-buffer-create "*system info*"))
833         (map (make-sparse-keymap)))
834
835     (define-key map "q" 'kill-this-buffer)
836     (display-buffer buf)
837     (set-buffer buf)
838     (setq show-trailing-whitespace nil)
839     (erase-buffer)
840
841     (let ((highlight nil))
842
843       (mapc (lambda (x)
844               (insert
845                (if (setq highlight (not highlight))
846                    (propertize
847                     (with-temp-buffer (apply 'call-process x)
848                                       (buffer-string))
849                     'face '(:background "#c0c0ff"))
850                  (with-temp-buffer (apply 'call-process x)
851                                    (buffer-string))
852                  ))
853               )
854
855             '(
856               ("hostname" nil t nil "-v")
857               ("acpi" nil t)
858               ("df" nil t nil "-h")
859               ;; ("mount" nil t)
860               ("ifconfig" nil t)
861               ("ssh-add" nil t nil "-l")
862               )))
863
864     (goto-char (point-min))
865     (while (re-search-forward "^$" nil t) (backward-delete-char 1))
866
867     (fit-window-to-buffer (get-buffer-window buf))
868     (use-local-map map)
869     (set-buffer-modified-p nil)
870     ))
871
872 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
873 ;; Make a sound when there is new mail
874 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
875
876 ;; I do not like sounds anymore
877
878 ;; (setq ff/already-boinged-for-mail nil)
879
880 ;; (defun ff/boing-if-new-mail ()
881 ;; (if mail (when (not ff/already-boinged-for-mail)
882 ;; ;; (ff/play-sound-async "~/local/sounds/boing1.wav")
883 ;; ;; (ff/show-unspooled-mails)
884 ;; (setq ff/already-boinged-for-mail t))
885 ;; (setq ff/already-boinged-for-mail nil))
886 ;; )
887
888 ;; (add-hook 'display-time-hook 'ff/boing-if-new-mail)
889
890 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
891 ;; Display time
892 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
893
894 (setq
895
896  display-time-interval 15 ;; Check every 15s
897
898  display-time-string-forms `(
899
900                              ;; (if mail
901                              ;;     (concat " "
902                              ;;             (propertize " mail "
903                              ;;                         'face 'ff/mail-alarm-face)
904                              ;;             " ")
905                              ;;   )
906
907                              (propertize (concat 24-hours ":" minutes
908                                                  " "
909                                                  dayname " "
910                                                  monthname " "
911                                                  day)
912                                          'face 'ff/date-info-face)
913
914                              load
915
916                              ,(if (ff/laptop-info-string)
917                                   '(concat " " (ff/laptop-info-string)))
918
919                              )
920
921  ;; display-time-format "%b %a %e %H:%M"
922  ;; display-time-mail-face nil
923  )
924
925 ;; Show the time, mail and stuff
926 (display-time)
927
928 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
929 ;; Moving through buffers
930 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
931
932 (defun ff/next-buffer ()
933   "Switches to the next buffer in cyclic order."
934   (interactive)
935   (let ((buffer (current-buffer)))
936     (switch-to-buffer (other-buffer buffer))
937     (bury-buffer buffer)))
938
939 (defun ff/prev-buffer ()
940   "Switches to the previous buffer in cyclic order."
941   (interactive)
942   (let ((list (nreverse (buffer-list)))
943         found)
944     (while (and (not found) list)
945       (let ((buffer (car list)))
946         (if (and (not (get-buffer-window buffer))
947                  (not (string-match "\\` " (buffer-name buffer))))
948             (setq found buffer)))
949       (setq list (cdr list)))
950     (switch-to-buffer found)))
951
952 (define-key global-map [?\C-x right] 'ff/next-buffer)
953 (define-key global-map [?\C-x left] 'ff/prev-buffer)
954
955 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
956 ;; There is actually a decent terminal emulator in emacs!
957 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
958
959 (load "term")
960
961 (defun ff/kill-associated-buffer (process str) (interactive)
962   (let ((buffer (process-buffer process)))
963     (kill-buffer buffer))
964   (message "Process finished (%s)" (replace-regexp-in-string "\n$" "" str)))
965
966 (defun ff/kill-associated-buffer-and-delete-windows (process str) (interactive)
967   (let ((buffer (process-buffer process)))
968     (delete-windows-on buffer)
969     (kill-buffer buffer))
970   (message "Process finished (%s)" (replace-regexp-in-string "\n$" "" str)))
971
972 (defun ff/shell-new-buffer (buffername program &rest param)
973   "Start a terminal-emulator in a new buffer with the shell PROGRAM,
974 optionally invoked with the parameters PARAM. The process associated
975 to the shell can be killed without query."
976
977   (interactive)
978
979   (let ((n 1)
980         (bn buffername))
981
982     (while (get-buffer (concat "*" bn "*"))
983       (setq n (1+ n)
984             bn (format "%s<%d>" buffername n)))
985
986     (set-buffer (apply 'make-term (append (list bn program nil) param)))
987
988     (setq show-trailing-whitespace nil)
989     (term-char-mode)
990     (message "C-c C-k term-char-mode, C-c C-j term-line-mode. \
991 In line mode: M-p previous line, M-n next line.")
992
993     ;; A standard setup of the face above is not enough, I have to
994     ;; force them here. Since I have a gray90 background, I like
995     ;; darker colors.
996
997     (when window-system
998       (ff/configure-faces
999        '((term-green :foreground "green3")
1000          (term-cyan :foreground "cyan3")
1001          (term-default-fg-inv :foreground "gray90" :background "black")
1002          )))
1003
1004     (term-set-escape-char ?\C-x)
1005
1006     ;; I like the shell buffer and windows to be deleted when the
1007     ;; shell process terminates. It's a bit of a mess to acheive this.
1008
1009     (let ((process (get-buffer-process (current-buffer))))
1010       (process-kill-without-query process)
1011       (set-process-sentinel process
1012                             ;; 'ff/kill-associated-buffer-and-delete-windows
1013                             'ff/kill-associated-buffer
1014                             ))
1015
1016     ;; (switch-to-buffer-other-window (concat "*" bn "*"))
1017     (switch-to-buffer (concat "*" bn "*"))
1018     ))
1019
1020 (defcustom ff/default-bash-commands '("ssh")
1021   "*List of commands to be used for completion when invoking a new
1022 bash shell with `ff/bash-new-buffer'.")
1023
1024 (defun ff/bash-new-buffer (universal)
1025   "Starts a bash in a new buffer. When invoked with a universal
1026 argument, asks for a command to execute in that bash shell. The list
1027 of commands in `ff/default-bash-commands' is used for auto-completion"
1028   (interactive "P")
1029
1030   (if universal
1031       (let ((cmd (completing-read
1032                   "Command: "
1033                   (mapcar (lambda (x) (cons x t)) ff/default-bash-commands))))
1034         (ff/shell-new-buffer cmd "/bin/bash" "-c" cmd))
1035
1036     (ff/shell-new-buffer "bash" "/bin/bash")))
1037
1038 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1039 ;; vc stuff for CVS
1040 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1041
1042 (setq ;; Always follow links if the file is under version control
1043  vc-follow-symlinks t
1044  )
1045
1046 (when (load "vc-git" nil t)
1047   (add-to-list 'vc-handled-backends 'GIT))
1048
1049 ;; alarm-vc.el is one of my own scripts, check my web page
1050
1051 (when (ff/load-or-alert "alarm-vc" t)
1052   (setq alarm-vc-mode-exceptions "^VM"))
1053
1054 (when (ff/load-or-alert "git")
1055   (setq git-show-unknown nil)
1056   )
1057
1058 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1059 ;; Makes .sh and others files executable automagically
1060 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1061
1062 ;; Please consider the security-related consequences of using it
1063
1064 ;; (defun ff/make-shell-scripts-executable (&optional filename)
1065 ;; (setq filename (or filename (buffer-name)))
1066 ;; (when (and (string-match "\\.sh$\\|\\.pl$\\|\\.rb" filename)
1067 ;; (not (file-executable-p filename))
1068 ;; )
1069 ;; (set-file-modes filename 493)
1070 ;; (message "Made %s executable" filename)))
1071
1072 ;; (add-hook 'after-save-hook 'ff/make-shell-scripts-executable)
1073
1074 (add-hook 'after-save-hook
1075           'executable-make-buffer-file-executable-if-script-p)
1076
1077 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1078 ;; Cool stuff to navigate in emacs-lisp sources
1079 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1080
1081 (load "find-func")
1082
1083 (defun ff/goto-function-definition (&optional goback)
1084   "Go directly to the definition of the function at point. With
1085 goback argument, go back where we were."
1086   (interactive "P")
1087   (if goback
1088       (if (not (and (boundp 'goto-function-history) goto-function-history))
1089           (error "We were nowhere, buddy")
1090         (message "Come back")
1091         (switch-to-buffer (car (car goto-function-history)))
1092         (goto-char (cdr (car goto-function-history)))
1093         (setq goto-function-history (cdr goto-function-history)))
1094
1095     (let ((function (function-called-at-point)))
1096       (when function
1097         (let ((location (find-function-search-for-symbol
1098                          function nil
1099                          (symbol-file function))))
1100           (setq goto-function-history
1101                 (cons (cons (current-buffer) (point))
1102                       (and (boundp 'goto-function-history)
1103                            goto-function-history)))
1104           (pop-to-buffer (car location))
1105           (goto-char (cdr location)))))))
1106
1107 (define-key global-map [(meta g)] 'ff/goto-function-definition)
1108 (define-key global-map [(meta G)] (lambda () (interactive)
1109                                     (ff/goto-function-definition t)))
1110
1111 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1112 ;; The big stuff (bbdb, mailcrypt, etc.)
1113 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1114
1115 ;; Failsafe version if we can't load bbdb
1116 (defun ff/explicit-name (email) email)
1117
1118 (load "vc-git")
1119
1120 (when (ff/load-or-alert "bbdb")
1121
1122   (setq
1123    ;; Stop asking (if not t or nil, will not ask)
1124    bbdb-offer-save 'never
1125    ;; I hate when bbdb decides to mess up my windows
1126    bbdb-use-pop-up nil
1127    ;; I have no problem with bbdb asking me if the sender email
1128    ;; does not match exactly the address we have in the database
1129    bbdb-quiet-about-name-mismatches 0
1130    ;; I have european friends, too
1131    bbdb-north-american-phone-numbers-p nil
1132    ;; To cycle through all possible addresses
1133    bbdb-complete-name-allow-cycling t
1134    ;; Cycle with full names only, not through all net-addresses alone too
1135    bbdb-dwim-net-address-allow-redundancy t
1136    ;; Do not add new addresses automatically
1137    bbdb-always-add-addresses nil
1138    )
1139
1140   (defface ff/known-address-face
1141     '((t (:foreground "blue2")))
1142     "The face to display known mail identities.")
1143
1144   (defface ff/unknown-address-face
1145     '((t (:foreground "gray50")))
1146     "The face to display unknown mail identities.")
1147
1148   (defun ff/explicit-name (email)
1149     "Returns a string identity for the first address in EMAIL. The
1150 identity is taken from bbdb if possible or from the address itself
1151 with mail-extract-address-components. The suffix \"& al.\" is added if
1152 there are more than one address.
1153
1154 If no bbdb record is found, the name is propertized with the face
1155 ff/unknown-address-face. If a record is found and contains a note
1156 'face, the associated face is used, otherwise
1157 ff/known-address-face is used."
1158
1159     (and email
1160          (let* ((data (mail-extract-address-components email))
1161                 (name (car data))
1162                 (net (cadr data))
1163                 (record (bbdb-search-simple nil net)))
1164
1165            (concat
1166
1167             (condition-case nil
1168                 (propertize (bbdb-record-name record)
1169                             'face
1170                             (or (cdr (assoc 'face
1171                                             (bbdb-record-raw-notes record)))
1172                                 'ff/known-address-face))
1173               (error
1174                (propertize (or (and data (concat "<" net ">"))
1175                                "*undefined*")
1176                            'face 'ff/unknown-address-face)
1177                ))
1178             (if (string-match "," (mail-strip-quoted-names email)) " & al.")
1179             )))
1180     )
1181
1182   (ff/configure-faces '((ff/robot-address-face :foreground "green4")
1183                         (ff/personal-address-face :foreground "dark magenta"
1184                                                   :weight 'bold)
1185                         (ff/important-address-face :foreground "blue2"
1186                                                    ;; :underline t
1187                                                    ;; :background "white"
1188                                                    ;; :foreground "green4"
1189                                                    :weight 'bold
1190                                                    ;; :slant 'italic
1191                                                    )))
1192
1193   )
1194
1195 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1196 ;; An encrypted file to put secure stuff (passwords, ...)
1197 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1198
1199 (when (ff/load-or-alert "mailcrypt")
1200   (mc-setversion "gpg")
1201   ;; Keep the passphrase for 10min
1202   (setq mc-passwd-timeout 600
1203         ff/secure-note-file "~/private/secure-notes.gpg")
1204   )
1205
1206 (defface ff/secure-date
1207   '((t (:background "white" :weight bold)))
1208   "The face to display the dates in the modeline.")
1209
1210 (defun ff/secure-note-add () (interactive)
1211   (find-file ff/secure-note-file)
1212
1213   ;; Adds a new entry (i.e. date and a bunch of empty lines)
1214
1215   (goto-char (point-min))
1216   (insert "-- "
1217           (format-time-string "%Y %b %d %H:%M:%S" (current-time))
1218           " --\n\n")
1219   (previous-line 1)
1220
1221   ;; Colorizes the dates
1222
1223   (save-excursion
1224     (goto-char (point-min))
1225     (while (re-search-forward
1226             "^-- [0-9]+ [a-z]+ [0-9]+ [0-9]+:[0-9]+:[0-9]+ -+$"
1227             nil t)
1228       (add-text-properties
1229        (match-beginning 0) (1+ (match-end 0))
1230        '(face ff/secure-date rear-nonsticky t))))
1231
1232   (set-buffer-modified-p nil)
1233   (setq buffer-undo-list nil)
1234   )
1235
1236 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1237 ;; Spelling
1238 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1239
1240 (setq ;; For french, aspell is far better than ispell
1241  ispell-program-name "aspell"
1242  ;; To avoid ispell errors in figure filenames, labels, references.
1243  ;;       ispell-tex-skip-alists
1244  ;;       (list
1245  ;;        (append (car ispell-tex-skip-alists)
1246  ;;                '(("\\\\citep"           ispell-tex-arg-end) ;; JMLR
1247  ;;                  ("\\\\cite"            ispell-tex-arg-end)
1248  ;;                  ("\\\\nocite"          ispell-tex-arg-end)
1249  ;;                  ("\\\\includegraphics" ispell-tex-arg-end)
1250  ;;                  ("\\\\author"          ispell-tex-arg-end)
1251  ;;                  ("\\\\ref"             ispell-tex-arg-end)
1252  ;;                  ("\\\\label"           ispell-tex-arg-end)
1253  ;;                  ))
1254  ;;        (cadr ispell-tex-skip-alists))
1255
1256  ;; So that reftex follows the text when moving in the summary
1257  reftex-toc-follow-mode nil
1258  ;; So that reftex visits files to follow
1259  reftex-revisit-to-follow t
1260  )
1261
1262 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1263 ;; Used in a \includegraphics runs xfig with the corresponding .fig
1264 ;; file or gimp with the corresponding bitmap picture
1265 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1266
1267 (defun ff/run-eps-edition (prefix rules &optional force)
1268   (if rules
1269       (let ((filename (concat prefix (car (car rules)))))
1270         (if (or force (file-exists-p filename))
1271             (start-process "latex-eps-editor" nil (cdr (car rules)) filename)
1272           (ff/run-eps-edition prefix (cdr rules) force)))
1273     (message "No original file found for %seps" prefix)))
1274
1275 (defcustom ff/xdvi-for-latex-options nil
1276   "*Options to pass to xdvi when invoking `ff/run-viewer'")
1277
1278 (defun ff/run-viewer (universal)
1279
1280   "Starts an editor for the .eps at point (either xfig or gimp,
1281 depending with the original file it can find), or starts xdvi for
1282 the current .tex if no .eps is found at point. When run with a
1283 universal argument starts xfig even if the .fig does not exist"
1284
1285   (interactive "P")
1286
1287   (if (and (save-excursion
1288              (and (re-search-backward "{" (point-at-bol) t)
1289                   (or (re-search-forward "{\\([^{}]*.\\)eps}" (point-at-eol) t)
1290                       (re-search-forward "{\\([^{}]*.\\)pdf}" (point-at-eol) t)
1291                       (re-search-forward "{\\([^{}]*.\\)pdf_t}" (point-at-eol) t)
1292                       (re-search-forward "{\\([^{}]*.\\)png}" (point-at-eol) t)
1293                       (re-search-forward "{\\([^{}]*.\\)jpg}" (point-at-eol) t)
1294                       )))
1295            (and (<= (match-beginning 1) (point))
1296                 (>= (match-end 1) (- (point) 2))))
1297
1298       (ff/run-eps-edition (match-string-no-properties 1)
1299                           '(("fig" . "xfig")
1300                             ("jpg" . "gimp" )
1301                             ("png" . "gimp") ("pgm" . "gimp") ("ppm" . "gimp")
1302                             ("jpg" . "xv"))
1303                           universal)
1304
1305     (if (not (and (buffer-file-name) (string-match "\\(.*\\)\.tex$"
1306                                                    (buffer-file-name))))
1307         (message "Not a latex file!")
1308       (condition-case nil (kill-process xdvi-process) (error nil))
1309       (let ((dvi-name (concat (match-string 1 (buffer-file-name)) ".dvi")))
1310         (if (not (file-exists-p dvi-name)) (error "Can not find %s !" dvi-name)
1311           (message "Starting xdvi with %s" dvi-name)
1312           (setq xdvi-process (apply 'start-process
1313                                     (append '("xdvi-for-latex" nil "xdvi")
1314                                             ff/xdvi-for-latex-options
1315                                             (list dvi-name))))
1316           (process-kill-without-query xdvi-process))))
1317     ))
1318
1319 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1320 ;; Tex mode
1321
1322 ;; When working on a tex file with other people, I can just change
1323 ;; ff/tex-command in the -*- part of the file so that I don't mess up
1324 ;; other's people configuration.
1325
1326 (defadvice tex-file (around ff/set-my-own-tex-command () activate)
1327   (let ((tex-command
1328          (or (and (boundp 'ff/tex-command)
1329                   ff/tex-command)
1330              tex-command)))
1331     ad-do-it))
1332
1333 ;; This is a bit hardcore, but really I can't bear the superscripts in
1334 ;; my emacs window and could not find another way to deactivate them.
1335
1336 (load "tex-mode")
1337 (defun tex-font-lock-suscript (pos) ())
1338
1339 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1340 ;; Prevents many errors from beeping and makes the others play a nifty
1341 ;; sound
1342 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1343
1344 (defun ff/ring-bell ()
1345   (unless (memq this-command
1346                 '(isearch-abort
1347                   abort-recursive-edit
1348                   exit-minibuffer
1349                   keyboard-quit
1350                   backward-delete-char-untabify
1351                   delete-backward-char
1352                   minibuffer-complete-and-exit
1353                   previous-line next-line
1354                   backward-char forward-char
1355                   scroll-up scroll-down
1356                   enlarge-window-horizontally shrink-window-horizontally
1357                   enlarge-window shrink-window
1358                   minibuffer-complete
1359                   ))
1360     ;; (message "command [%s]" (prin1-to-string this-command))
1361     ;; (ff/play-sound-async "~/local/sounds/short_la.wav")
1362     ))
1363
1364 (setq ring-bell-function 'ff/ring-bell)
1365
1366 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1367 ;; Past the content of the url currently in the kill-ring with
1368 ;; shift-click 2
1369 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1370
1371 (defun ff/insert-url (&optional url)
1372   "Downloads an URL with lynx and inserts it after the point."
1373   (interactive "MUrl: ")
1374   (when url
1375     (message "Inserting %s" url)
1376     (insert (concat "from: " url "\n\n"))
1377     ;; (call-process "lynx" nil t nil "-nolist" "-dump" url))
1378     (call-process "w3m" nil t nil "-dump" url))
1379   )
1380
1381 (define-key global-map [(shift mouse-2)]
1382   (lambda () (interactive) (ff/insert-url (current-kill 0))))
1383
1384 ;; lookup-dict is one of my own scripts, check my web page
1385
1386 (when (ff/load-or-alert "lookup-dict" t)
1387   (define-key global-map [(control \?)] 'lookup-dict))
1388
1389 ;; (defun ff/generate-password () (interactive)
1390 ;; (let ((c "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"))
1391 ;; (nth (random (length c)) c))
1392
1393 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1394 ;; Automatization of things I do often
1395 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1396
1397 (defun ff/snip () (interactive)
1398   (let ((start (condition-case nil (region-beginning) (error (point))))
1399         (end (condition-case nil (region-end) (error (point)))))
1400     (goto-char end)
1401     (insert "---------------------------- snip snip -------------------------------\n")
1402     (goto-char start)
1403     (insert "---------------------------- snip snip -------------------------------\n")
1404     ))
1405
1406 (defun ff/start-latex ()
1407   "Adds all that stuff to start a new LaTeX document."
1408   (interactive)
1409   (goto-char (point-min))
1410   (insert "%% -*- mode: latex; mode: reftex; mode: flyspell; coding: utf-8; tex-command: \"pdflatex.sh\" -*-
1411
1412 \\documentclass[12pt]{article}
1413 \\usepackage[a4paper,top=2.5cm,bottom=2cm,left=2.5cm,right=2.5cm]{geometry}
1414 \\usepackage[utf8]{inputenc}
1415 \\usepackage{amsmath}
1416 \\usepackage{amssymb}
1417 \\usepackage[pdftex]{graphicx}
1418 \\usepackage{microtype}
1419 \\usepackage[colorlinks=true,linkcolor=blue,urlcolor=blue,citecolor=blue]{hyperref}
1420
1421 \\setlength{\\parindent}{0cm}
1422 \\setlength{\\parskip}{12pt}
1423 \\renewcommand{\\baselinestretch}{1.3}
1424
1425 \\def\\argmax{\\operatornamewithlimits{argmax}}
1426 \\def\\argmin{\\operatornamewithlimits{argmin}}
1427
1428 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1429 %% Sans serif fonts
1430 %% \\usepackage[T1]{fontenc}
1431 %% \\usepackage[scaled]{helvet}
1432 %% \\usepackage[cm]{sfmath}
1433 %% \\renewcommand{\\ttdefault}{pcr}
1434 %% \\renewcommand*\\familydefault{\\sfdefault}
1435 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1436 %% The \\todo command
1437 \\newcounter{nbdrafts}
1438 \\setcounter{nbdrafts}{0}
1439 \\makeatletter
1440 \\newcommand{\\checknbdrafts}{
1441 \\ifnum \\thenbdrafts > 0
1442 \\@latex@warning@no@line{*WARNING* The document contains \\thenbdrafts \\space draft note(s)}
1443 \\fi}
1444 \\newcommand{\\todo}[1]{\\addtocounter{nbdrafts}{1}{\\color{red} #1}}
1445 \\makeatother
1446 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1447
1448 \\begin{document}
1449
1450 ")
1451   (save-excursion
1452     (goto-char (point-max))
1453     (insert "
1454
1455 \\end{document}
1456 "))
1457   (latex-mode))
1458
1459 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1460
1461 (defun ff/add-copyrights ()
1462   "Adds two lines for the (C) at the beginning of current buffer."
1463   (interactive)
1464
1465   (let ((comment-style 'plain))
1466
1467     (goto-char (point-min))
1468
1469     ;; If this is a script, put the copyrights after the first line
1470
1471     (when (re-search-forward "^#!" nil t)
1472       (beginning-of-line)
1473       (next-line 1))
1474
1475     (let ((start (point))
1476           (comment-style 'box))
1477       (insert
1478        (concat
1479
1480         "\nSTART_IP_HEADER\n"
1481
1482         (when (boundp 'user-full-name)
1483           (concat "\nWritten by " user-full-name "\n"))
1484
1485         (when (boundp 'user-mail-address)
1486           (concat "Contact <" user-mail-address "> for comments & bug reports\n"))
1487
1488         "\nEND_IP_HEADER\n"
1489         ))
1490
1491       (comment-region start (point)))
1492
1493     ))
1494
1495 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1496
1497 (defun ff/remove-ip-header () (interactive)
1498   (save-excursion
1499     (goto-char (point-min))
1500     (when (and (re-search-forward "START_IP_HEADER" nil t)
1501                (re-search-forward "END_IP_HEADER" nil t))
1502       (message "yep"))
1503     ))
1504
1505 (defun ff/add-gpl ()
1506   "Adds the GPL statements at the beginning of current buffer."
1507   (interactive)
1508   (let ((comment-style 'box)
1509         (gpl
1510          (concat
1511
1512           ;;           "
1513           ;; This program is free software; you can redistribute it and/or
1514           ;; modify it under the terms of the GNU General Public License
1515           ;; version 2 as published by the Free Software Foundation.
1516
1517           ;; This program is distributed in the hope that it will be useful, but
1518           ;; WITHOUT ANY WARRANTY\; without even the implied warranty of
1519           ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1520           ;; General Public License for more details.
1521           ;; "
1522
1523           "
1524 START_IP_HEADER
1525
1526 This program is free software: you can redistribute it and/or modify
1527 it under the terms of the version 3 of the GNU General Public License
1528 as published by the Free Software Foundation.
1529
1530 This program is distributed in the hope that it will be useful, but
1531 WITHOUT ANY WARRANTY; without even the implied warranty of
1532 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1533 General Public License for more details.
1534
1535 You should have received a copy of the GNU General Public License
1536 along with this program. If not, see <http://www.gnu.org/licenses/>.
1537
1538 "
1539           (when (boundp 'user-full-name)
1540             (concat "Written by and Copyright (C) " user-full-name "\n"))
1541
1542           (when (boundp 'user-mail-address)
1543             (concat "Contact <" user-mail-address "> for comments & bug reports\n"))
1544
1545           "
1546 END_IP_HEADER
1547 "
1548
1549           )))
1550
1551     (goto-char (point-min))
1552
1553     ;; If this is a script, put the gpl after the first line
1554     (when (re-search-forward "^#!" nil t)
1555       (beginning-of-line)
1556       (next-line 1))
1557
1558     (let ((start (point)))
1559       (insert gpl)
1560       (comment-region start (point)))
1561     ))
1562
1563 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1564
1565 (defun ff/start-c ()
1566   "Adds the header to start a C program."
1567   (interactive)
1568   ;;   (beginning-of-buffer)
1569   (insert
1570    "
1571 #include <stdio.h>
1572 #include <stdlib.h>
1573
1574 int main(int argc, char **argv) {
1575   exit(EXIT_SUCCESS);
1576 }
1577 ")
1578   (previous-line 2)
1579   )
1580
1581 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1582
1583 (defun ff/start-c++ ()
1584   "Adds the header to start a C++ program."
1585   (interactive)
1586   ;;   (beginning-of-buffer)
1587   (insert
1588    "
1589 #include <iostream>
1590 #include <fstream>
1591 #include <cmath>
1592 #include <stdio.h>
1593 #include <stdlib.h>
1594
1595 using namespace std;
1596
1597 int main(int argc, char **argv) {
1598
1599 }
1600 ")
1601   (previous-line 2)
1602   )
1603
1604 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1605
1606 (defun ff/headerize ()
1607   "Adds the #define HEADER_H, etc."
1608   (interactive)
1609   (let ((flag-name (replace-regexp-in-string
1610                     "[\. \(\)]" "_"
1611                     (upcase (file-name-nondirectory (buffer-file-name))))))
1612     (goto-char (point-max))
1613     (insert "\n#endif\n")
1614     (goto-char (point-min))
1615     (insert (concat "#ifndef " flag-name "\n"))
1616     (insert (concat "#define " flag-name "\n"))
1617     )
1618   )
1619
1620 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1621
1622 (defun ff/start-html ()
1623   "Adds all that stuff to start a new HTML file."
1624   (interactive)
1625   (goto-char (point-min))
1626   (insert "<?xml version=\"1.0\" encoding=\"utf-8\"?>
1627 <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
1628
1629 <html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">
1630
1631 <head>
1632 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
1633 <title></title>
1634 </head>
1635
1636 <body>
1637 ")
1638   (goto-char (point-max))
1639   (insert "
1640 </body>
1641
1642 </html>
1643 ")
1644   (html-mode))
1645
1646 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1647
1648 ;; Insert a line showing all the variables written on the current line
1649 ;; and separated by commas
1650
1651 (defun ff/cout-var (arg)
1652   "Invoked on a line with a list of variables names,
1653 it inserts a line which displays their values in cout, or cerr if
1654 the function is invoked with a universal arg"
1655   (interactive "P")
1656   (let ((line (if arg "cerr" "cout")))
1657     (goto-char (point-at-bol))
1658     ;; Regexp syntax sucks moose balls, honnest. To match '[', just
1659     ;; put it as the first char in the [...] ... This leads to some
1660     ;; obvious things like the following
1661     (while (re-search-forward "\\([][a-zA-Z0-9_.:\(\)]+\\)" (point-at-eol) t)
1662       (setq line
1663             (concat line " << \" "
1664                     (match-string 1) " = \" << " (match-string 1))))
1665     (goto-char (point-at-bol))
1666     (kill-line)
1667     (insert line " << endl\;\n")
1668     (indent-region (point-at-bol 0) (point-at-eol 0) nil)
1669     ))
1670
1671 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1672
1673 (defun ff/clean-article ()
1674   "Cleans up an article by removing the leading blanks on each line
1675 and refilling all the paragraphs."
1676   (interactive)
1677   (let ((fill-column 92))
1678     (goto-char (point-min))
1679     (while (re-search-forward "^\\ +" nil t)
1680       (replace-match "" nil nil))
1681     (fill-individual-paragraphs (point-min) (point-max) t)))
1682
1683 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1684
1685 (defun ff/start-slide ()
1686   (interactive)
1687   (insert "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1688
1689 \\begin{frame}{")
1690
1691   (save-excursion (insert "}{}
1692
1693 \\end{frame}
1694
1695 "))
1696   )
1697
1698 (add-hook
1699  'latex-mode-hook
1700  (lambda ()
1701    (define-key latex-mode-map [(meta S)] 'ff/start-slide)
1702    (define-key latex-mode-map [(control c) (control a)] 'align-current)
1703    (define-key latex-mode-map [(control end)] 'tex-close-latex-block)
1704    (define-key latex-mode-map [(control tab)] 'ispell-complete-word)
1705    (copy-face 'default 'tex-verbatim)
1706    ;; (ff/configure-faces '((tex-verbatim :background "gray95")))
1707    ))
1708
1709 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1710
1711 (defun ff/start-test-code ()
1712   (interactive)
1713   (let ((start (point)))
1714     (insert "
1715 { // ******************************* START ***************************
1716 #warning Test code added on "
1717             (format-time-string "%04Y %b %02d %02H:%02M:%02S" (current-time))
1718             "
1719
1720 } // ******************************** END ****************************
1721
1722 ")
1723     (indent-region start (point) nil))
1724   (previous-line 3)
1725   (c-indent-command))
1726
1727 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1728
1729 (defun ff/code-to-html () (interactive)
1730   (save-restriction
1731     (narrow-to-region (region-beginning) (region-end))
1732     (replace-string "\"" "&quot;" nil (point-min) (point-max))
1733     (replace-string " " "&nbsp;" nil (point-min) (point-max))
1734     (replace-string ">" "&gt;" nil (point-min) (point-max))
1735     (replace-string "<" "&lt;" nil (point-min) (point-max))
1736     (replace-string "\e" "^[" nil (point-min) (point-max))
1737     (replace-string "\7f" "^?" nil (point-min) (point-max))
1738     (replace-string "\1f" "^_" nil (point-min) (point-max))
1739     (replace-regexp "$" "<br />" nil (point-min) (point-max))
1740     )
1741   )
1742
1743 (defun ff/downcase-html-tags () (interactive)
1744   (save-excursion
1745     (beginning-of-buffer)
1746     (while (re-search-forward "<\\([^>]+\\)>" nil t)
1747       (downcase-region (match-beginning 1) (match-end 1)))
1748     )
1749   )
1750
1751 ;; If we enter html mode and there is no makefile around, create a
1752 ;; compilation command with tidy (this is cool stuff)
1753
1754 (add-hook 'html-mode-hook
1755           (lambda ()
1756             (unless (or (not (buffer-file-name))
1757                         (file-exists-p "makefile")
1758                         (file-exists-p "Makefile"))
1759               (set (make-local-variable 'compile-command)
1760                    (let ((fn (file-name-nondirectory buffer-file-name)))
1761                      (format "tidy -utf8 %s > /tmp/%s" fn fn))))))
1762
1763 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1764
1765 (defun ff/count-words-region (beginning end)
1766   "Print number of words in the region.
1767 Words are defined as at least one word-constituent character
1768 followed by at least one character that is not a
1769 word-constituent.  The buffer's syntax table determines which
1770 characters these are."
1771
1772   (interactive "r")
1773   (message "Counting words in region ... ")
1774   (save-excursion
1775     (goto-char beginning)
1776     (let ((count 0))
1777       (while (< (point) end)
1778         (re-search-forward "\\w+\\W+")
1779         (setq count (1+ count)))
1780       (cond ((zerop count) (message "The region does NOT have any word."))
1781             ((= 1 count) (message "The region has 1 word."))
1782             (t (message "The region has %d words." count))))))
1783
1784 ;; (add-hook 'html-mode-hook 'flyspell-mode)
1785
1786 (defun ff/tidy-html ()
1787   "Run tidy in on the content of the current buffer, put the result in
1788 a file in /tmp"
1789   (interactive)
1790   (call-process-region (point-min) (point-max)
1791                        "/usr/bin/tidy"
1792                        nil
1793                        (list nil (make-temp-file "/tmp/tidy-html."))))
1794
1795 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1796
1797 ;; Create the adequate embryo of a file if it does not exist
1798
1799 (defun ff/start-file () (interactive)
1800   (let ((filename (buffer-file-name)))
1801     (when filename
1802
1803       (when (string-match "\\.sh$" filename)
1804         (sh-mode)
1805         (insert "#!/bin/bash\n\nset -e\nset -o pipefail\n\n")
1806         (save-excursion
1807           (ff/add-copyrights))
1808         )
1809
1810       (when (string-match "\\.html$" filename)
1811         (html-mode)
1812         (ff/start-html)
1813         (previous-line 4)
1814         )
1815
1816       (when (string-match "\\.h$" filename)
1817         (c++-mode)
1818         (ff/headerize)
1819         (save-excursion
1820           (ff/add-copyrights)
1821           (newline))
1822         (newline)
1823         (newline)
1824         (previous-line 1)
1825         )
1826
1827       (when (string-match "\\.c$" filename)
1828         (c-mode)
1829         (ff/add-copyrights)
1830         (ff/start-c))
1831
1832       (when (string-match "\.\\(cc\\|cpp\\)$" filename)
1833         (c++-mode)
1834         (ff/add-copyrights)
1835         (let ((headername  (replace-regexp-in-string "\\.\\(cc\\|cpp\\)$" ".h"
1836                                                      filename)))
1837           (if (file-exists-p headername)
1838               (insert (concat "\n#include \"" (file-name-nondirectory headername) "\"\n"))
1839             (ff/start-c++))
1840           ))
1841
1842       (when (string-match "\\.tex$" filename)
1843         (latex-mode)
1844         (ff/start-latex)
1845         ))
1846     )
1847   (set-buffer-modified-p nil)
1848   )
1849
1850 (if (>= emacs-major-version 22)
1851     (add-to-list 'find-file-not-found-functions 'ff/start-file)
1852   (add-to-list 'find-file-not-found-hooks 'ff/start-file))
1853
1854 (when (>= emacs-major-version 24)
1855   (define-obsolete-function-alias 'make-local-hook 'ignore "21.1")
1856   (setq send-mail-function 'sendmail-send-it) ;; emacs 24.x stuff
1857
1858   (custom-set-faces
1859    '(diff-added ((default (:background "gray90" :foreground "green4" :weight bold))))
1860    '(diff-removed ((default (:background "gray90" :foreground "red2" :weight bold))))
1861    '(diff-changed ((default (:background "gray90" :foreground "blue" :weight bold))))
1862    )
1863   )
1864
1865 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1866
1867 (define-key global-map [f8] 'ff-find-other-file)
1868 (define-key global-map [(shift f8)] (lambda () (interactive) (ff-find-other-file t)))
1869
1870 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1871 ;; Antiword, htmlize and boxquote
1872 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1873
1874 (autoload 'no-word "no-word")
1875 (add-to-list 'auto-mode-alist '("\\.doc\\'" . no-word))
1876 ;; (add-to-list 'auto-mode-alist '("\\.DOC\\'" . no-word))
1877
1878 (autoload 'htmlize-buffer "htmlize" nil t)
1879
1880 (setq boxquote-top-and-tail "------------------")
1881 (autoload 'boxquote-region "boxquote" nil t)
1882
1883 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1884 ;; The compilation hacks
1885 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1886
1887 ;; If we enter c++ mode and there is no makefile around, we create a
1888 ;; make command on the fly for the specific object file
1889
1890 (add-hook 'c++-mode-hook
1891           (lambda ()
1892             (unless (or (file-exists-p "makefile") (file-exists-p "Makefile"))
1893               (set (make-local-variable 'compile-command)
1894                    (concat
1895                     "make -k "
1896                     (file-name-sans-extension
1897                      (file-name-nondirectory buffer-file-name)))))))
1898
1899 ;; <f1> runs the compilation according to the compile-command (and
1900 ;; thus does not ask any confirmation), shows the compilation buffer
1901 ;; during compilation and delete all windows showing the compilation
1902 ;; buffer if the compilation ends with no error
1903
1904 ;; <shift-f1> asks for a compilation command and runs the compilation
1905 ;; but does not restore the window configuration (i.e. the compilation
1906 ;; buffer's window will still be visible, as usual)
1907
1908 ;; <f2> goes to the next compilation error (as C-x ` does on the
1909 ;; standard configuration)
1910
1911 (defun ff/restore-windows-if-no-error (buffer msg)
1912   "Delete the windows showing the compilation buffer if msg
1913   matches \"^finished\"."
1914
1915   (when (string-match "^finished" msg)
1916     ;;     (delete-windows-on buffer)
1917     (if (boundp 'ff/window-configuration-before-compilation)
1918         (set-window-configuration ff/window-configuration-before-compilation))
1919     )
1920   )
1921
1922 (add-to-list 'compilation-finish-functions 'ff/restore-windows-if-no-error)
1923
1924 (defun ff/fast-compile ()
1925   "Compiles without asking anything."
1926   (interactive)
1927   (let ((compilation-read-command nil))
1928     (setq ff/window-configuration-before-compilation (current-window-configuration))
1929     (compile compile-command)))
1930
1931 (setq compilation-read-command t
1932       compile-command "make -j -k"
1933       compile-history '("make clean" "make DEBUG=yes -j -k" "make -j -k")
1934       )
1935
1936 (defun ff/universal-compile () (interactive)
1937   (funcall (or (cdr (assoc major-mode
1938                            '(
1939                              (latex-mode . tex-file)
1940                              (html-mode . browse-url-of-buffer)
1941                              ;; Here you can add other mode -> compile command
1942                              )))
1943                'ff/fast-compile         ;; And this is the failsafe
1944                )))
1945
1946 (define-key global-map [f1] 'ff/universal-compile)
1947 (define-key global-map [(shift f1)] 'compile)
1948 (define-key global-map [f2] 'next-error)
1949
1950 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1951 ;; Related to mail
1952 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1953
1954 ;; (when (ff/load-or-alert "flyspell-timer" t)
1955 ;;   (add-hook 'flyspell-mode-hook 'flyspell-timer-ensure-idle-timer))
1956
1957 (defun ff/pick-dictionnary () (interactive)
1958   (when (and (boundp 'flyspell-mode) flyspell-mode)
1959     (if (and current-input-method (string-match "latin" current-input-method))
1960         (ispell-change-dictionary "francais")
1961       (ispell-change-dictionary "american"))
1962     ;;     (flyspell-buffer)
1963     )
1964   )
1965
1966 (defadvice toggle-input-method (after ff/switch-dictionnary nil activate)
1967   (ff/pick-dictionnary))
1968
1969 ;; (add-hook 'message-mode-hook 'auto-fill-mode)
1970 ;; (add-hook 'message-mode-hook 'flyspell-mode)
1971
1972 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1973 ;; Delete all windows which are in the same "column", which means
1974 ;; whose xmin and xmax are bounded by the xmin and xmax of the
1975 ;; currently selected column
1976 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1977
1978 ;; This is from emacs23 ! better than my old ff/delete-other-windows-in-column
1979
1980 (unless (fboundp 'delete-other-windows-vertically)
1981
1982   (defun delete-other-windows-vertically (&optional window)
1983     "Delete the windows in the same column with WINDOW, but not WINDOW itself.
1984 This may be a useful alternative binding for \\[delete-other-windows]
1985  if you often split windows horizontally."
1986     (interactive)
1987     (let* ((window (or window (selected-window)))
1988            (edges (window-edges window))
1989            (w window) delenda)
1990       (while (not (eq (setq w (next-window w 1)) window))
1991         (let ((e (window-edges w)))
1992           (when (and (= (car e) (car edges))
1993                      (= (caddr e) (caddr edges)))
1994             (push w delenda))))
1995       (mapc 'delete-window delenda)))
1996   )
1997
1998 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1999 ;; Misc things
2000 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2001
2002 ;; Entropy is cool
2003
2004 (defun ff/entropy (l)
2005   (apply '+
2006          (mapcar
2007           (lambda (x)
2008             (if (= x 0.0) 0.0
2009               (* (- x) (/ (log x) (log 2)))))
2010           l)
2011          )
2012   )
2013
2014 ;; Usefull to deal with results in latex files
2015
2016 (defun ff/round-floats-in-region () (interactive)
2017   (save-restriction
2018     (condition-case nil
2019         (narrow-to-region (region-beginning) (region-end))
2020       (error (thing-at-point 'word)))
2021     (save-excursion
2022       (goto-char (point-min))
2023       (while (re-search-forward "[0-9\.]+" nil t)
2024         (let ((value (string-to-number (buffer-substring (match-beginning 0) (match-end 0)))))
2025           (delete-region (match-beginning 0) (match-end 0))
2026           (insert (format "%0.2f" value)))))))
2027
2028 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2029 ;; Keymaping
2030 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2031
2032 (load "info" nil t)
2033
2034 (define-key global-map [(shift iso-lefttab)] 'ispell-complete-word)
2035 ;; shift-tab going backward is kind of standard
2036 (define-key Info-mode-map [(shift iso-lefttab)] 'Info-prev-reference)
2037
2038 ;; (define-key global-map [(control x) (control a)] 'auto-fill-mode)
2039
2040 ;; Put back my keys, you thief!
2041 (define-key global-map [(home)] 'beginning-of-buffer)
2042 (define-key global-map [(end)] 'end-of-buffer)
2043 ;; (define-key global-map [(insertchar)] 'overwrite-mode)
2044 (define-key global-map [(delete)] 'delete-char)
2045
2046 ;; Cool shortcuts to move to the end / beginning of block keen
2047 (define-key global-map [(control right)] 'forward-sexp)
2048 (define-key global-map [(control left)] 'backward-sexp)
2049
2050 ;; Wheel mouse moves up and down 2 lines (and DO NOT BEEP when we are
2051 ;; out of the buffer)
2052
2053 (define-key global-map [mouse-4]
2054   (lambda () (interactive) (condition-case nil (scroll-down 2) (error nil))))
2055 (define-key global-map [mouse-5]
2056   (lambda () (interactive) (condition-case nil (scroll-up 2) (error nil))))
2057
2058 ;; with shift it goes faster
2059 (define-key global-map [(shift mouse-4)]
2060   (lambda () (interactive) (condition-case nil (scroll-down 50) (error nil))))
2061 (define-key global-map [(shift mouse-5)]
2062   (lambda () (interactive) (condition-case nil (scroll-up 50) (error nil))))
2063
2064 ;; Meta-? shows the properties of the character at point
2065 (define-key global-map [(meta ??)]
2066   (lambda () (interactive)
2067     (message (prin1-to-string (text-properties-at (point))))))
2068
2069 ;; Compiles the latex file in the current buffer
2070
2071 (setq tex-start-commands "\\input")
2072 (define-key global-map [f3] 'tex-file)
2073 (define-key global-map [(shift f3)] 'tex-bibtex-file)
2074
2075 ;; To run xdvi on the dvi associated to the .tex in the current
2076 ;; buffer, and to edit the .fig or bitmap image used to generate the
2077 ;; .eps at point
2078
2079 (define-key global-map [f4] 'ff/run-viewer)
2080
2081 ;; Closes the current \begin{}
2082
2083 (when (ff/load-or-alert "longlines")
2084
2085   (setq longlines-show-hard-newlines t
2086         longlines-auto-wrap t
2087         ;; longlines-show-effect #("|\n" 0 2 (face escape-glyph))
2088         ;; longlines-show-effect #("∴\n" 0 2 (face escape-glyph))
2089         longlines-show-effect #("•\n" 0 2 (face escape-glyph))
2090         ;; longlines-show-effect #("↵\n" 0 2 (face escape-glyph))
2091         )
2092
2093   ;; (defun ff/auto-longlines ()
2094   ;; (when (save-excursion
2095   ;; (goto-char (point-min))
2096   ;; (re-search-forward "^.\\{81,\\}$" nil t))
2097   ;; (longlines-mode)
2098   ;; (message "Switched on the lonlines mode automatically")
2099   ;; ))
2100
2101   ;; (add-hook 'latex-mode-hook 'ff/auto-longlines)
2102
2103   )
2104
2105 ;; Meta-/ remaped (completion)
2106
2107 (define-key global-map [(shift right)] 'dabbrev-expand)
2108 (define-key global-map [(meta =)] 'dabbrev-expand)
2109
2110 ;; Change the current window.
2111
2112 (defun ff/next-same-frame-window () (interactive)
2113   (select-window (next-window (selected-window)
2114                               (> (minibuffer-depth) 0)
2115                               nil)))
2116
2117 (defun ff/previous-same-frame-window () (interactive)
2118   (select-window (previous-window (selected-window)
2119                                   (> (minibuffer-depth) 0)
2120                                   nil)))
2121
2122 (define-key global-map [(shift prior)] 'ff/next-same-frame-window)
2123 (define-key global-map [(shift next)] 'ff/previous-same-frame-window)
2124
2125 (define-key global-map [(control })] 'enlarge-window-horizontally)
2126 (define-key global-map [(control {)] 'shrink-window-horizontally)
2127 (define-key global-map [(control \")] 'enlarge-window)
2128 (define-key global-map [(control :)] 'shrink-window)
2129
2130 ;; (define-key global-map [(control shift prior)] 'next-multiframe-window)
2131 ;; (define-key global-map [(control shift next)] 'previous-multiframe-window)
2132
2133 ;; I have two screens sometime!
2134
2135 (define-key global-map [(meta next)] 'other-frame)
2136 (define-key global-map [(meta prior)] (lambda () (interactive) (other-frame -1)))
2137
2138 (define-key global-map [(shift home)] 'delete-other-windows-vertically)
2139
2140 ;; (define-key global-map [(control +)] 'enlarge-window)
2141 ;; (define-key global-map [(control -)] 'shrink-window)
2142
2143 ;; Goes to next/previous buffer
2144
2145 (define-key global-map [(control prior)] 'ff/next-buffer)
2146 (define-key global-map [(control next)] 'ff/prev-buffer)
2147
2148 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2149 ;; If M-. on a symbol, show where it is defined in another window
2150 ;; without giving focus, cycle if repeated.
2151 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2152
2153 (when (ff/load-or-alert "etags")
2154
2155   (defun ff/find-tag-nofocus () (interactive)
2156     "Show in another window the definition of the current tag"
2157     (let ((tag (find-tag-default)))
2158       (display-buffer (find-tag-noselect tag (string= tag last-tag)))
2159       (message "Tag %s" tag)
2160       )
2161     )
2162
2163   (define-key global-map [(meta .)] 'ff/find-tag-nofocus)
2164   )
2165
2166 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2167 ;; Destroys the current buffer and its window if it's not the only one
2168 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2169
2170 (defcustom ff/kill-this-buffer-and-delete-window-exceptions ""
2171   "*Regexp matching the buffer names which have to be kept when using
2172 `ff/kill-this-buffer-and-delete-window'.")
2173
2174 (defun ff/kill-this-buffer-and-delete-window (universal)
2175   "Unless its name matches
2176 `ff/kill-this-buffer-and-delete-window-exceptions', kills the
2177 current buffer and deletes the current window if it's not the
2178 only one in the frame. If the buffer has to be kept, go to the
2179 next one. With universal argument, kill all killable buffers."
2180   (interactive "P")
2181   (if universal
2182       (let ((nb-killed 0))
2183         (mapc (lambda (x)
2184                 (unless (string-match ff/kill-this-buffer-and-delete-window-exceptions
2185                                       (buffer-name x))
2186                   (kill-buffer x)
2187                   (setq nb-killed (1+ nb-killed))
2188                   ))
2189               (buffer-list))
2190         (message "Killed %d buffer%s" nb-killed (if (> nb-killed 1) "s" "")))
2191     (if (string-match ff/kill-this-buffer-and-delete-window-exceptions (buffer-name))
2192         (ff/next-buffer)
2193       (kill-this-buffer)))
2194   ;; (unless (one-window-p t) (delete-window))
2195   )
2196
2197 (define-key global-map [(control backspace)] 'ff/kill-this-buffer-and-delete-window)
2198 ;; (define-key calc-mode-map [(control backspace)] 'calc-quit)
2199
2200
2201 (setq ff/kill-this-buffer-and-delete-window-exceptions
2202       "^ \\|\\*Messages\\*\\|\\*scratch\\*\\|\\*Group\\*\\|\\*-jabber-\\*\\|\\*-jabber-process-\\*\\|\\*media\\*")
2203
2204 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2205 ;; Misc stuff
2206 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2207
2208 (defun ff/elisp-debug-on ()
2209   "Switches `debug-on-error' and `debug-on-quit'."
2210   (interactive)
2211   (if debug-on-error
2212       (setq debug-on-error nil
2213             debug-on-quit nil)
2214     (setq debug-on-error t
2215           debug-on-quit t))
2216   (if debug-on-error
2217       (message "elisp debug on")
2218     (message "elisp debug off")))
2219
2220 (defun ff/create-dummy-buffer (&optional universal) (interactive "P")
2221   (find-file (concat "/tmp/" (ff/non-existing-filename "/tmp/" "dummy" "")))
2222   (text-mode)
2223   (if universal (ff/insert-url (current-kill 0)))
2224   (message "New dummy text-mode buffer"))
2225
2226 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2227 ;; Recentf to keep a list of recently visited files. I use it
2228 ;; exclusively with my selector.el
2229 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2230
2231 (load "recentf")
2232
2233 ;; If we just check for file-symlink-p, everytime we start emacs it
2234 ;; will check all the remote files listed in recentf-list, so we check
2235 ;; that they are not remote first
2236 (defun ff/file-not-remote-but-symlink (filename)
2237   (and (not (file-remote-p filename)) (file-symlink-p filename)))
2238
2239 (setq recentf-exclude (append recentf-exclude
2240                               '(
2241                                 ff/file-not-remote-but-symlink
2242                                 "enotes$" "secure-notes$" "media-playlists$"
2243                                 "bbdb$"
2244                                 "svn-commit.tmp$" ".git/COMMIT_EDITMSG$"
2245                                 "\.bbl$" "\.aux$" "\.toc$"
2246                                 ))
2247       recentf-max-saved-items 1000
2248       recentf-save-file "~/private/emacs/recentf"
2249       )
2250
2251 (when (boundp 'recentf-keep) (add-to-list 'recentf-keep 'file-remote-p))
2252
2253 (recentf-mode 1)
2254
2255 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2256 ;; My front-end to mplayer
2257 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2258
2259 ;; (ff/compile-when-needed "media/mplayer")
2260 ;; (ff/compile-when-needed "media")
2261
2262 (when (ff/load-or-alert "media")
2263
2264   (unless window-system
2265     (ff/configure-faces
2266      '(
2267        (media/mode-string-face
2268         :foreground "blue4" :weight 'bold)
2269
2270        (media/current-tune-face
2271         :foreground "black" :background "yellow" :weight 'normal)
2272
2273        (media/instant-highlight-face
2274         :foreground "black" :background "orange" :weight 'normal)
2275        ))
2276     )
2277
2278   (define-key global-map [(meta \\)] 'media)
2279
2280   (setq media/expert t
2281         media/add-current-song-to-interrupted-when-killing t
2282         media/duration-to-history 30
2283         media/history-size 1000
2284         media/playlist-file "~/private/emacs/media-playlists"
2285         media/mplayer/args '(
2286                              "-framedrop"
2287                              "-zoom"
2288                              "-cache" "512"
2289                              "-subfont-osd-scale" "3"
2290                              ;; "-stop-xscreensaver"
2291                              ;; "-osdlevel" "3"
2292                              )
2293         media/mplayer/timing-request-period 5.0
2294         )
2295   )
2296
2297 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2298 ;; A dynamic search
2299 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2300
2301 ;; selector.el is one of my own scripts, check my web page
2302
2303 (when (ff/load-or-alert "selector" t)
2304   ;; (define-key global-map [(shift return)] 'selector/quick-move-in-buffer)
2305   (define-key global-map [(control x) (control b)] 'selector/switch-buffer)
2306
2307   (defun ff/visit-debpkg-file (&optional regexp)
2308     "This function lists all the files found with dpkg -S and
2309 proposes to visit them."
2310     (interactive "sPattern: ")
2311
2312     (selector/select
2313
2314      (mapcar
2315       (lambda (s)
2316         (cons (selector/filename-to-string s) s))
2317       (split-string
2318        (shell-command-to-string (concat "dpkg -S " regexp " | awk '{print $2}'"))))
2319
2320      'selector/find-file
2321      "*selector find-file*"
2322      ))
2323   )
2324
2325 (add-hook 'selector/mode-hook (lambda () (setq truncate-lines t)))
2326
2327 (defun ff/selector-insert-record-callback (r)
2328   (bbdb-display-records (list r))
2329   ;; Weird things will happen if you kill the buffer from which you
2330   ;; invoked ff/selector-mail-from-bbdb
2331   (insert (car (elt r 6)))
2332   )
2333
2334 (defun ff/selector-compose-mail-callback (r)
2335   (vm-compose-mail (car (elt r 6)))
2336   )
2337
2338 (defun ff/selector-mail-from-bbdb () (interactive)
2339   (selector/select
2340    (mapcar
2341     (lambda (r) (cons (concat (elt r 0)
2342                               " "
2343                               (elt r 1)
2344                               " ("
2345                               (car (elt r 6))
2346                               ")")
2347                       r))
2348     (bbdb-records))
2349    (if (string= mode-name "Mail")
2350        'ff/selector-insert-record-callback
2351      'ff/selector-compose-mail-callback)
2352    "*bbdb-search*"
2353    )
2354   )
2355
2356 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2357 ;; My script to automatically count the number of words and characters
2358 ;; between two markers
2359
2360 (load "text-counters.el")
2361
2362 ;; Display them in the modeline when in text-mode
2363
2364 (add-hook 'text-mode-hook 'tc/add-text-counters-in-modeline)
2365
2366 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2367 ;; A function to remove temporary alarm windows
2368 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2369
2370 (defcustom ff/annoying-windows-regexp
2371   "\\*Messages\\*\\|\\*compilation\\*\\|\\*tex-shell\\*\\|\\*Help\\*\\|\\*info\\*\\|\\*Apropos\\*\\|\\*BBDB\\*\\|\\*.*-diff\\*"
2372   "The regexp matching the windows to be deleted by `ff/delete-annoying-windows'"
2373   )
2374
2375 (defun ff/delete-annoying-windows ()
2376   "Close all the windows showing buffers whose names match
2377 `ff/annoying-windows-regexp'."
2378   (interactive)
2379   (when ff/annoying-windows-regexp
2380     (mapc (lambda (w)
2381             (when (and (not (one-window-p w))
2382                        (string-match ff/annoying-windows-regexp
2383                                      (buffer-name (window-buffer w))))
2384               (delete-window w)))
2385           (window-list)
2386           )
2387     (message "Removed annoying windows")
2388     )
2389   )
2390
2391 (setq ff/annoying-windows-regexp
2392       (concat ff/annoying-windows-regexp
2393               "\\|\\*unspooled mails\\*\\|\\*enotes alarms\\*\\|\\*system info\\*"))
2394
2395 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2396 ;; Some handy functions
2397 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2398
2399 (defun ff/twin-horizontal-current-buffer () (interactive)
2400   (delete-other-windows)
2401   (split-window-horizontally)
2402   (balance-windows)
2403   )
2404
2405 (defun ff/twin-vertical-current-buffer () (interactive)
2406   (delete-other-windows)
2407   (split-window-vertically)
2408   (balance-windows)
2409   )
2410
2411 (defun ff/flyspell-mode (arg) (interactive "p")
2412   (if flyspell-mode (flyspell-mode -1)
2413     (flyspell-mode 1)
2414     (flyspell-buffer))
2415 )
2416
2417 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2418 ;; The fridge!
2419 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2420
2421 (defun ff/move-region-to-fridge () (interactive)
2422   "Cut the current region, paste it in a file called ./fridge
2423 with a time tag, and save this file"
2424   (unless (use-region-p) (error "No region selected"))
2425   (let ((bn (file-name-nondirectory (buffer-file-name))))
2426     (kill-region (region-beginning) (region-end))
2427     (with-current-buffer (find-file-noselect "fridge")
2428       (goto-char (point-max))
2429       (insert "\n")
2430       (insert "######################################################################\n")
2431       (insert "\n"
2432               (format-time-string "%Y %b %d %H:%M:%S" (current-time))
2433               " (from "
2434               bn
2435               ")\n\n")
2436       (yank)
2437       (save-buffer)
2438       (message "Region moved to fridge")
2439       )
2440     )
2441   )
2442
2443 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2444 ;; My own keymap
2445 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2446
2447 (setq ff/map (make-sparse-keymap))
2448 (define-key global-map [(control \`)] ff/map)
2449 ;;(define-key global-map [(control @)] ff/map)
2450
2451 (define-key esc-map "`" ff/map)
2452
2453 (defun ff/git-status (&optional dir) (interactive)
2454   (if (buffer-file-name)
2455       (git-status (file-name-directory (buffer-file-name)))
2456     (error "No file attached to this buffer")))
2457
2458 (defun ff/insert-date () (interactive)
2459   (insert (format-time-string "\n * %Y %b %d %H:%M:%S\n\n" (current-time)))
2460   )
2461
2462 (define-key ff/map [(control g)] 'ff/git-status)
2463 (define-key ff/map [(control w)] 'server-edit)
2464 (define-key ff/map [(control d)] 'ff/elisp-debug-on)
2465 ;; (define-key ff/map "d" 'diary)
2466 (define-key ff/map "d" 'ff/insert-date)
2467 (define-key ff/map [(control \`)] 'ff/bash-new-buffer)
2468 (define-key ff/map [(control n)] 'enotes/show-all-notes)
2469 (define-key ff/map [(control s)] 'ff/secure-note-add)
2470 (define-key ff/map [(control t)] 'ff/start-test-code)
2471 (define-key ff/map [(control q)] 'ff/create-dummy-buffer)
2472 (define-key ff/map [(control a)] 'auto-fill-mode)
2473 (define-key ff/map [(control i)] 'ff/system-info)
2474 (define-key ff/map "w" 'ff/word-occurences)
2475 (define-key ff/map [(control c)] 'calendar)
2476 ;; (define-key ff/map [(control c)] (lambda () (interactive) (save-excursion (calendar))))
2477 (define-key ff/map [(control l)] 'goto-line)
2478 (define-key ff/map "l" 'longlines-mode)
2479 (define-key ff/map [(control o)] 'selector/quick-pick-recent)
2480 (define-key ff/map "s" 'selector/quick-move-in-buffer)
2481 (define-key ff/map "S" 'selector/search-sentence)
2482 (define-key ff/map "t" (lambda () (interactive) (find-file "~/private/TODO.txt")))
2483 (define-key ff/map "h" 'ff/tidy-html)
2484 (define-key ff/map "c" 'ff/count-char)
2485 (define-key ff/map [(control p)] 'ff/print-to-file)
2486 (define-key ff/map "P" 'ff/print-to-printer)
2487 (define-key ff/map [(control b)] 'bbdb)
2488 (define-key ff/map "m" 'ff/selector-mail-from-bbdb)
2489 (define-key ff/map [(control m)] 'woman)
2490 (define-key ff/map "b" 'bookmark-jump)
2491 (define-key ff/map [(control =)] 'calc)
2492 (define-key ff/map [(control shift b)]
2493   (lambda () (interactive)
2494     (bookmark-set)
2495     (bookmark-save)))
2496 (define-key ff/map "f" 'ff/move-region-to-fridge)
2497 (define-key ff/map [(control f)] 'ff/flyspell-mode)
2498
2499 (define-key ff/map [?\C-0] 'ff/delete-annoying-windows)
2500 (define-key ff/map "1" 'delete-other-windows)
2501 (define-key ff/map [?\C-1] 'delete-other-windows)
2502 (define-key ff/map "2" 'ff/twin-vertical-current-buffer)
2503 (define-key ff/map [?\C-2] 'ff/twin-vertical-current-buffer)
2504 (define-key ff/map "3" 'ff/twin-horizontal-current-buffer)
2505 (define-key ff/map [?\C-3] 'ff/twin-horizontal-current-buffer)
2506
2507 (define-key ff/map " " 'delete-trailing-whitespace)
2508
2509 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2510 ;; Hacks so that all keys are functionnal in xterm and through ssh.
2511 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2512
2513 (unless window-system
2514
2515   ;; One day I will understand these clipboard business. Until then,
2516   ;; so that it works in xterm (yes), let's use xclip. This is a bit
2517   ;; ugly.
2518
2519   ;; (defun ff/yank-with-xclip (&optional arg)
2520   ;; "Paste the content of the X clipboard with the xclip
2521   ;; command. Without ARG converts some of the '\\uxxxx' characters."
2522   ;; (interactive "P")
2523   ;; (with-temp-buffer
2524   ;; (shell-command "xclip -o" t)
2525   ;; (unless arg
2526   ;; (mapc (lambda (x) (replace-string (concat "\\u" (car x)) (cdr x) nil (point-min) (point-max)))
2527   ;; '(("fffd" . "??")
2528   ;; ("2013" . "-")
2529   ;; ("2014" . "--")
2530   ;; ("2018" . "`")
2531   ;; ("2019" . "'")
2532   ;; ("201c" . "``")
2533   ;; ("201d" . "''")
2534   ;; ("2022" . "*")
2535   ;; ("2026" . "...")
2536   ;; ("20ac" . "EUR")
2537   ;; )))
2538   ;; (kill-ring-save (point-min) (point-max)))
2539
2540   ;; (yank))
2541
2542   ;; (define-key global-map [(meta y)] 'ff/yank-with-xclip)
2543
2544   ;;   (set-terminal-coding-system 'iso-latin-1)
2545   ;; (set-terminal-coding-system 'utf-8)
2546
2547   ;; I have in my .Xressource
2548
2549   ;; XTerm.VT100.translations: #override\n\
2550   ;;   <Btn4Down>,<Btn4Up>:scroll-back(2,line)\n\
2551   ;;   <Btn5Down>,<Btn5Up>:scroll-forw(2,line)\n\
2552   ;;   Ctrl<Btn4Down>,Ctrl<Btn4Up>:scroll-back(1,page)\n\
2553   ;;   Ctrl<Btn5Down>,Ctrl<Btn5Up>:scroll-forw(1,page)\n\
2554   ;;   Shift<Btn4Down>,Shift<Btn4Up>:scroll-back(1,halfpage)\n\
2555   ;;   Shift<Btn5Down>,Shift<Btn5Up>:scroll-forw(1,halfpage)\n\
2556   ;;   Alt<KeyPress>:insert-eight-bit()\n\
2557   ;;   !Shift<Key>BackSpace: string("\7f")\n\
2558   ;;   Ctrl<Key>BackSpace: string("\eOZ")\n\
2559   ;;   Shift<Key>Prior: string("\e[5;2~")\n\
2560   ;;   Shift<Key>Next: string("\e[6;2~")\n\
2561   ;;   Shift Ctrl<Key>]: string("\eO}")\n\
2562   ;;   Shift Ctrl<Key>[: string("\eO{")\n\
2563   ;;   Shift Ctrl<Key>/: string("\eO?")\n\
2564   ;;   Ctrl<Key>/: string("\eO/")\n\
2565   ;;   Shift Ctrl<Key>=: string("\eO+")\n\
2566   ;;   Ctrl<Key>=: string("\eO=")\n\
2567   ;;   Shift Ctrl<Key>;: string("\eO:")\n\
2568   ;;   Ctrl<Key>;: string("\eO;")\n\
2569   ;;   Shift Ctrl<Key>`: string("\eO~")\n\
2570   ;;   Ctrl<Key>`: string("\eO`")\n\
2571   ;;   Shift Ctrl<Key>': string("\eO\\\"")\n\
2572   ;;   Ctrl<Key>': string("\eO'")\n\
2573   ;;   Shift Ctrl<Key>.: string("\eO>")\n\
2574   ;;   Ctrl<Key>.: string("\eO.")\n\
2575   ;;   Shift Ctrl<Key>\\,: string("\eO<")\n\
2576   ;;   Ctrl<Key>\\,: string("\eO,")
2577
2578   (define-key function-key-map "\e[2~" [insert])
2579
2580   (define-key function-key-map "\e[Z" [S-iso-lefttab])
2581
2582   (define-key function-key-map "\e[1;2A" [S-up])
2583   (define-key function-key-map "\e[1;2B" [S-down])
2584   (define-key function-key-map "\e[1;2C" [S-right])
2585   (define-key function-key-map "\e[1;2D" [S-left])
2586   (define-key function-key-map "\e[1;2F" [S-end])
2587   (define-key function-key-map "\e[1;2H" [S-home])
2588
2589   (define-key function-key-map "\e[2;2~" [S-insert])
2590   (define-key function-key-map "\e[5;2~" [S-prior])
2591   (define-key function-key-map "\e[6;2~" [S-next])
2592
2593   (define-key function-key-map "\e[1;2P" [S-f1])
2594   (define-key function-key-map "\e[1;2Q" [S-f2])
2595   (define-key function-key-map "\e[1;2R" [S-f3])
2596   (define-key function-key-map "\e[1;2S" [S-f4])
2597   (define-key function-key-map "\e[15;2~" [S-f5])
2598   (define-key function-key-map "\e[17;2~" [S-f6])
2599   (define-key function-key-map "\e[18;2~" [S-f7])
2600   (define-key function-key-map "\e[19;2~" [S-f8])
2601   (define-key function-key-map "\e[20;2~" [S-f9])
2602   (define-key function-key-map "\e[21;2~" [S-f10])
2603
2604   (define-key function-key-map "\e[1;5A" [C-up])
2605   (define-key function-key-map "\e[1;5B" [C-down])
2606   (define-key function-key-map "\e[1;5C" [C-right])
2607   (define-key function-key-map "\e[1;5D" [C-left])
2608   (define-key function-key-map "\e[1;5F" [C-end])
2609   (define-key function-key-map "\e[1;5H" [C-home])
2610
2611   (define-key function-key-map "\e[2;5~" [C-insert])
2612   (define-key function-key-map "\e[5;5~" [C-prior])
2613   (define-key function-key-map "\e[6;5~" [C-next])
2614
2615   (define-key function-key-map "\e[1;9A" [M-up])
2616   (define-key function-key-map "\e[1;9B" [M-down])
2617   (define-key function-key-map "\e[1;9C" [M-right])
2618   (define-key function-key-map "\e[1;9D" [M-left])
2619   (define-key function-key-map "\e[1;9F" [M-end])
2620   (define-key function-key-map "\e[1;9H" [M-home])
2621
2622   (define-key function-key-map "\e[2;9~" [M-insert])
2623   (define-key function-key-map "\e[5;9~" [M-prior])
2624   (define-key function-key-map "\e[6;9~" [M-next])
2625
2626   ;; The following ones are not standard
2627
2628   (define-key function-key-map "\eO}" (kbd "C-}"))
2629   (define-key function-key-map "\eO{" (kbd "C-{"))
2630   (define-key function-key-map "\eO?" (kbd "C-?"))
2631   (define-key function-key-map "\eO/" (kbd "C-/"))
2632   (define-key function-key-map "\eO:" (kbd "C-:"))
2633   (define-key function-key-map "\eO;" (kbd "C-;"))
2634   (define-key function-key-map "\eO~" (kbd "C-~"))
2635   (define-key function-key-map "\eO`" (kbd "C-\`"))
2636   (define-key function-key-map "\eO\"" (kbd "C-\""))
2637   (define-key function-key-map "\eO|" (kbd "C-|"))
2638   (define-key function-key-map "\eO'" (kbd "C-'"))
2639   (define-key function-key-map "\eO>" (kbd "C->"))
2640   (define-key function-key-map "\eO." (kbd "C-."))
2641   (define-key function-key-map "\eO<" (kbd "C-<"))
2642   (define-key function-key-map "\eO," (kbd "C-,"))
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
2647   (define-key function-key-map "\eOZ" [C-backspace])
2648
2649   (define-key minibuffer-local-map "\10" 'previous-history-element)
2650   (define-key minibuffer-local-map "\ e" 'next-history-element)
2651
2652   ;; (define-key global-map [(alt prior)] 'ff/prev-buffer)
2653   ;; (define-key global-map [(alt next)] 'ff/next-buffer)
2654
2655   )
2656
2657 ;; I am fed up with Alt-Backspace in the minibuffer erasing the
2658 ;; content of the kill-ring
2659
2660 (defun ff/backward-delete-word (arg)
2661   "Delete characters forward until encountering the end of a word, but do not put them in the kill ring.
2662 With argument ARG, do this that many times."
2663   (interactive "p")
2664   (delete-region (point) (progn (forward-word (- arg)) (point))))
2665
2666 (define-key minibuffer-local-map
2667   [remap backward-kill-word] 'ff/backward-delete-word)
2668
2669 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2670 ;; Privacy
2671 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2672
2673 ;; Where to save the bookmarks and where is bbdb
2674
2675 (setq bookmark-default-file "~/private/emacs/bmk"
2676       bbdb-file "~/private/bbdb"
2677       custom-file "~/private/emacs/custom")
2678
2679 ;; enotes.el is one of my own scripts, check my web page
2680
2681 (when (ff/load-or-alert "enotes" t)
2682   (setq enotes/file "~/private/enotes"
2683         enotes/show-help nil
2684         enotes/full-display nil
2685         enotes/default-time-fields "9:30")
2686
2687   (enotes/init)
2688   ;; (add-hook 'enotes/alarm-hook
2689   ;;  (lambda () (ff/play-sound-async "~/local/sounds/three_notes2.wav")))
2690   )
2691
2692 ;; (when (ff/load-or-alert "goto-last-change.el")
2693 ;; (define-key global-map [(control x) (control a)] 'goto-last-change))
2694
2695 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2696 ;; My private stuff (email adresses, mail filters, etc.)
2697 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2698
2699 (ff/load-or-alert "~/private/emacs.perso.el" t)
2700
2701 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2702 ;; emacs server
2703 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2704
2705 ;; Runs in server mode, so that emacsclient works
2706 (server-start)
2707
2708 (defun ff/raise-frame-and-give-focus ()
2709   (when window-system
2710     (raise-frame)
2711     (x-focus-frame (selected-frame))
2712     (set-mouse-pixel-position (selected-frame) 4 4)
2713     ))
2714
2715 ;; Raises the window when the server is invoked
2716
2717 (add-hook 'server-switch-hook 'ff/raise-frame-and-give-focus)