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