2001-08-19 Simon Josefsson <jas@extundo.com>
[gnus] / lisp / gnus-spec.el
1 ;;; gnus-spec.el --- format spec functions for Gnus  -*- coding: iso-latin-1 -*-
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;;; Code:
28
29 (eval-when-compile (require 'cl))
30
31 (require 'gnus)
32
33 (defcustom gnus-use-correct-string-widths t
34   "*If non-nil, use correct functions for dealing with wide characters."
35   :group 'gnus-format
36   :type 'boolean)
37
38 ;;; Internal variables.
39
40 (defvar gnus-summary-mark-positions nil)
41 (defvar gnus-group-mark-positions nil)
42 (defvar gnus-group-indentation "")
43
44 ;; Format specs.  The chunks below are the machine-generated forms
45 ;; that are to be evaled as the result of the default format strings.
46 ;; We write them in here to get them byte-compiled.  That way the
47 ;; default actions will be quite fast, while still retaining the full
48 ;; flexibility of the user-defined format specs.
49
50 ;; First we have lots of dummy defvars to let the compiler know these
51 ;; are really dynamic variables.
52
53 (defvar gnus-tmp-unread)
54 (defvar gnus-tmp-replied)
55 (defvar gnus-tmp-score-char)
56 (defvar gnus-tmp-indentation)
57 (defvar gnus-tmp-opening-bracket)
58 (defvar gnus-tmp-lines)
59 (defvar gnus-tmp-name)
60 (defvar gnus-tmp-closing-bracket)
61 (defvar gnus-tmp-subject-or-nil)
62 (defvar gnus-tmp-subject)
63 (defvar gnus-tmp-marked)
64 (defvar gnus-tmp-marked-mark)
65 (defvar gnus-tmp-subscribed)
66 (defvar gnus-tmp-process-marked)
67 (defvar gnus-tmp-number-of-unread)
68 (defvar gnus-tmp-group-name)
69 (defvar gnus-tmp-group)
70 (defvar gnus-tmp-article-number)
71 (defvar gnus-tmp-unread-and-unselected)
72 (defvar gnus-tmp-news-method)
73 (defvar gnus-tmp-news-server)
74 (defvar gnus-tmp-article-number)
75 (defvar gnus-mouse-face)
76 (defvar gnus-mouse-face-prop)
77
78 (defun gnus-summary-line-format-spec ()
79   (insert gnus-tmp-unread gnus-tmp-replied
80           gnus-tmp-score-char gnus-tmp-indentation)
81   (gnus-put-text-property
82    (point)
83    (progn
84      (insert
85       gnus-tmp-opening-bracket
86       (format "%4d: %-20s"
87               gnus-tmp-lines
88               (if (> (length gnus-tmp-name) 20)
89                   (substring gnus-tmp-name 0 20)
90                 gnus-tmp-name))
91       gnus-tmp-closing-bracket)
92      (point))
93    gnus-mouse-face-prop gnus-mouse-face)
94   (insert " " gnus-tmp-subject-or-nil "\n"))
95
96 (defvar gnus-summary-line-format-spec
97   (gnus-byte-code 'gnus-summary-line-format-spec))
98
99 (defun gnus-summary-dummy-line-format-spec ()
100   (insert "*  ")
101   (gnus-put-text-property
102    (point)
103    (progn
104      (insert ":                          :")
105      (point))
106    gnus-mouse-face-prop gnus-mouse-face)
107   (insert " " gnus-tmp-subject "\n"))
108
109 (defvar gnus-summary-dummy-line-format-spec
110   (gnus-byte-code 'gnus-summary-dummy-line-format-spec))
111
112 (defun gnus-group-line-format-spec ()
113   (insert gnus-tmp-marked-mark gnus-tmp-subscribed
114           gnus-tmp-process-marked
115           gnus-group-indentation
116           (format "%5s: " gnus-tmp-number-of-unread))
117   (gnus-put-text-property
118    (point)
119    (progn
120      (insert gnus-tmp-group "\n")
121      (1- (point)))
122    gnus-mouse-face-prop gnus-mouse-face))
123 (defvar gnus-group-line-format-spec
124   (gnus-byte-code 'gnus-group-line-format-spec))
125
126 (defvar gnus-format-specs
127   `((version . ,emacs-version)
128     (group "%M\%S\%p\%P\%5y: %(%g%)%l\n" ,gnus-group-line-format-spec)
129     (summary-dummy "*  %(:                          :%) %S\n"
130                    ,gnus-summary-dummy-line-format-spec)
131     (summary "%U\%R\%z\%I\%(%[%4L: %-23,23n%]%) %s\n"
132              ,gnus-summary-line-format-spec))
133   "Alist of format specs.")
134
135 (defvar gnus-article-mode-line-format-spec nil)
136 (defvar gnus-summary-mode-line-format-spec nil)
137 (defvar gnus-group-mode-line-format-spec nil)
138
139 ;;; Phew.  All that gruft is over, fortunately.
140
141 ;;;###autoload
142 (defun gnus-update-format (var)
143   "Update the format specification near point."
144   (interactive
145    (list
146     (save-excursion
147       (eval-defun nil)
148       ;; Find the end of the current word.
149       (re-search-forward "[ \t\n]" nil t)
150       ;; Search backward.
151       (when (re-search-backward "\\(gnus-[-a-z]+-line-format\\)" nil t)
152         (match-string 1)))))
153   (let* ((type (intern (progn (string-match "gnus-\\([-a-z]+\\)-line" var)
154                               (match-string 1 var))))
155          (entry (assq type gnus-format-specs))
156          value spec)
157     (when entry
158       (setq gnus-format-specs (delq entry gnus-format-specs)))
159     (set
160      (intern (format "%s-spec" var))
161      (gnus-parse-format (setq value (symbol-value (intern var)))
162                         (symbol-value (intern (format "%s-alist" var)))
163                         (not (string-match "mode" var))))
164     (setq spec (symbol-value (intern (format "%s-spec" var))))
165     (push (list type value spec) gnus-format-specs)
166
167     (pop-to-buffer "*Gnus Format*")
168     (erase-buffer)
169     (lisp-interaction-mode)
170     (insert (pp-to-string spec))))
171
172 (defun gnus-update-format-specifications (&optional force &rest types)
173   "Update all (necessary) format specifications."
174   ;; Make the indentation array.
175   ;; See whether all the stored info needs to be flushed.
176   (when (or force
177             (not (equal emacs-version
178                         (cdr (assq 'version gnus-format-specs)))))
179     (setq gnus-format-specs nil))
180
181   ;; Go through all the formats and see whether they need updating.
182   (let (new-format entry type val)
183     (while (setq type (pop types))
184       ;; Jump to the proper buffer to find out the value of
185       ;; the variable, if possible.  (It may be buffer-local.)
186       (save-excursion
187         (let ((buffer (intern (format "gnus-%s-buffer" type)))
188               val)
189           (when (and (boundp buffer)
190                      (setq val (symbol-value buffer))
191                      (gnus-buffer-exists-p val))
192             (set-buffer val))
193           (setq new-format (symbol-value
194                             (intern (format "gnus-%s-line-format" type)))))
195         (setq entry (cdr (assq type gnus-format-specs)))
196         (if (and (car entry)
197                  (equal (car entry) new-format))
198             ;; Use the old format.
199             (set (intern (format "gnus-%s-line-format-spec" type))
200                  (cadr entry))
201           ;; This is a new format.
202           (setq val
203                 (if (not (stringp new-format))
204                     ;; This is a function call or something.
205                     new-format
206                   ;; This is a "real" format.
207                   (gnus-parse-format
208                    new-format
209                    (symbol-value
210                     (intern (format "gnus-%s-line-format-alist" type)))
211                    (not (string-match "mode$" (symbol-name type))))))
212           ;; Enter the new format spec into the list.
213           (if entry
214               (progn
215                 (setcar (cdr entry) val)
216                 (setcar entry new-format))
217             (push (list type new-format val) gnus-format-specs))
218           (set (intern (format "gnus-%s-line-format-spec" type)) val)))))
219
220   (unless (assq 'version gnus-format-specs)
221     (push (cons 'version emacs-version) gnus-format-specs)))
222
223 (defvar gnus-mouse-face-0 'highlight)
224 (defvar gnus-mouse-face-1 'highlight)
225 (defvar gnus-mouse-face-2 'highlight)
226 (defvar gnus-mouse-face-3 'highlight)
227 (defvar gnus-mouse-face-4 'highlight)
228
229 (defun gnus-mouse-face-function (form type)
230   `(gnus-put-text-property
231     (point) (progn ,@form (point))
232     gnus-mouse-face-prop
233     ,(if (equal type 0)
234          'gnus-mouse-face
235        `(quote ,(symbol-value (intern (format "gnus-mouse-face-%d" type)))))))
236
237 (defvar gnus-face-0 'bold)
238 (defvar gnus-face-1 'italic)
239 (defvar gnus-face-2 'bold-italic)
240 (defvar gnus-face-3 'bold)
241 (defvar gnus-face-4 'bold)
242
243 (defun gnus-face-face-function (form type)
244   `(gnus-add-text-properties
245     (point) (progn ,@form (point))
246     '(gnus-face t face ,(symbol-value (intern (format "gnus-face-%d" type))))))
247
248 (defun gnus-balloon-face-function (form type)
249   `(gnus-put-text-property
250     (point) (progn ,@form (point))
251     'balloon-help
252     ,(intern (format "gnus-balloon-face-%d" type))))
253
254 (eval-and-compile
255   (defalias 'gnus-char-width
256     (if (fboundp 'char-width)
257         'char-width
258       (lambda (ch) 1)))) ;; A simple hack.
259
260 (defun gnus-correct-length (string)
261   "Return the correct width of STRING."
262   (let ((length 0))
263     (mapcar (lambda (char) (incf length (gnus-char-width char))) string)
264     length))
265
266 (defun gnus-correct-substring (string start end)
267   (let ((wstart 0)
268         (wend 0)
269         (seek 0)
270         (length (length string)))
271     ;; Find the start position.
272     (while (and (< seek length)
273                 (< wstart start))
274       (incf wstart (gnus-char-width (aref string seek)))
275       (incf seek))
276     (setq wend wstart
277           wstart seek)
278     ;; Find the end position.
279     (while (and (< seek length)
280                 (< wend end))
281       (incf wend (gnus-char-width (aref string seek)))
282       (incf seek))
283     (setq wend seek)
284     (substring string wstart (1- wend))))
285
286 (defun gnus-tilde-max-form (el max-width)
287   "Return a form that limits EL to MAX-WIDTH."
288   (let ((max (abs max-width)))
289     (if (symbolp el)
290         `(if (> (,(if gnus-use-correct-string-widths
291                       'gnus-correct-length
292                     'length) ,el)
293                 ,max)
294              ,(if (< max-width 0)
295                   `(,(if gnus-use-correct-string-widths
296                          'gnus-correct-substring
297                        'substring)
298                     ,el (- (,(if gnus-use-correct-string-widths
299                                  'gnus-correct-length
300                                'length)
301                             el) ,max))
302                 `(,(if gnus-use-correct-string-widths
303                        'gnus-correct-substring
304                      'substring)
305                   ,el 0 ,max))
306            ,el)
307       `(let ((val (eval ,el)))
308          (if (> (,(if gnus-use-correct-string-widths
309                       'gnus-correct-length
310                     'length) val) ,max)
311              ,(if (< max-width 0)
312                   `(,(if gnus-use-correct-string-widths
313                          'gnus-correct-substring
314                        'substring)
315                     val (- (,(if gnus-use-correct-string-widths
316                                  'gnus-correct-length
317                                'length) val) ,max))
318                 `(,(if gnus-use-correct-string-widths
319                        'gnus-correct-substring
320                      'substring)
321                   val 0 ,max))
322            val)))))
323
324 (defun gnus-tilde-cut-form (el cut-width)
325   "Return a form that cuts CUT-WIDTH off of EL."
326   (let ((cut (abs cut-width)))
327     (if (symbolp el)
328         `(if (> (length ,el) ,cut)
329              ,(if (< cut-width 0)
330                   `(substring ,el 0 (- (length el) ,cut))
331                 `(substring ,el ,cut))
332            ,el)
333       `(let ((val (eval ,el)))
334          (if (> (length val) ,cut)
335              ,(if (< cut-width 0)
336                   `(substring val 0 (- (length val) ,cut))
337                 `(substring val ,cut))
338            val)))))
339
340 (defun gnus-tilde-ignore-form (el ignore-value)
341   "Return a form that is blank when EL is IGNORE-VALUE."
342   (if (symbolp el)
343       `(if (equal ,el ,ignore-value)
344            "" ,el)
345     `(let ((val (eval ,el)))
346        (if (equal val ,ignore-value)
347            "" val))))
348
349 (defun gnus-parse-format (format spec-alist &optional insert)
350   ;; This function parses the FORMAT string with the help of the
351   ;; SPEC-ALIST and returns a list that can be eval'ed to return the
352   ;; string.  If the FORMAT string contains the specifiers %( and %)
353   ;; the text between them will have the mouse-face text property.
354   ;; If the FORMAT string contains the specifiers %[ and %], the text between
355   ;; them will have the balloon-help text property.
356   (if (string-match
357        "\\`\\(.*\\)%[0-9]?[{(«]\\(.*\\)%[0-9]?[»})]\\(.*\n?\\)\\'"
358        format)
359       (gnus-parse-complex-format format spec-alist)
360     ;; This is a simple format.
361     (gnus-parse-simple-format format spec-alist insert)))
362
363 (defun gnus-parse-complex-format (format spec-alist)
364   (save-excursion
365     (gnus-set-work-buffer)
366     (insert format)
367     (goto-char (point-min))
368     (while (re-search-forward "\"" nil t)
369       (replace-match "\\\"" nil t))
370     (goto-char (point-min))
371     (insert "(\"")
372     (while (re-search-forward "%\\([0-9]+\\)?\\([«»{}()]\\)" nil t)
373       (let ((number (if (match-beginning 1)
374                         (match-string 1) "0"))
375             (delim (aref (match-string 2) 0)))
376         (if (or (= delim ?\()
377                 (= delim ?\{)
378                 (= delim ?\«))
379             (replace-match (concat "\"("
380                                    (cond ((= delim ?\() "mouse")
381                                          ((= delim ?\{) "face")
382                                          (t "balloon"))
383                                    " " number " \""))
384           (replace-match "\")\""))))
385     (goto-char (point-max))
386     (insert "\")")
387     (goto-char (point-min))
388     (let ((form (read (current-buffer))))
389       (cons 'progn (gnus-complex-form-to-spec form spec-alist)))))
390
391 (defun gnus-complex-form-to-spec (form spec-alist)
392   (delq nil
393         (mapcar
394          (lambda (sform)
395            (if (stringp sform)
396                (gnus-parse-simple-format sform spec-alist t)
397              (funcall (intern (format "gnus-%s-face-function" (car sform)))
398                       (gnus-complex-form-to-spec (cddr sform) spec-alist)
399                       (nth 1 sform))))
400          form)))
401
402 (defun gnus-parse-simple-format (format spec-alist &optional insert)
403   ;; This function parses the FORMAT string with the help of the
404   ;; SPEC-ALIST and returns a list that can be eval'ed to return a
405   ;; string.
406   (let ((max-width 0)
407         spec flist fstring elem result dontinsert user-defined
408         type value pad-width spec-beg cut-width ignore-value
409         tilde-form tilde elem-type)
410     (save-excursion
411       (gnus-set-work-buffer)
412       (insert format)
413       (goto-char (point-min))
414       (while (re-search-forward "%" nil t)
415         (setq user-defined nil
416               spec-beg nil
417               pad-width nil
418               max-width nil
419               cut-width nil
420               ignore-value nil
421               tilde-form nil)
422         (setq spec-beg (1- (point)))
423
424         ;; Parse this spec fully.
425         (while
426             (cond
427              ((looking-at "\\([-.0-9]+\\)\\(,[-0-9]+\\)?")
428               (setq pad-width (string-to-number (match-string 1)))
429               (when (match-beginning 2)
430                 (setq max-width (string-to-number (buffer-substring
431                                                    (1+ (match-beginning 2))
432                                                    (match-end 2)))))
433               (goto-char (match-end 0)))
434              ((looking-at "~")
435               (forward-char 1)
436               (setq tilde (read (current-buffer))
437                     type (car tilde)
438                     value (cadr tilde))
439               (cond
440                ((memq type '(pad pad-left))
441                 (setq pad-width value))
442                ((eq type 'pad-right)
443                 (setq pad-width (- value)))
444                ((memq type '(max-right max))
445                 (setq max-width value))
446                ((eq type 'max-left)
447                 (setq max-width (- value)))
448                ((memq type '(cut cut-left))
449                 (setq cut-width value))
450                ((eq type 'cut-right)
451                 (setq cut-width (- value)))
452                ((eq type 'ignore)
453                 (setq ignore-value
454                       (if (stringp value) value (format "%s" value))))
455                ((eq type 'form)
456                 (setq tilde-form value))
457                (t
458                 (error "Unknown tilde type: %s" tilde)))
459               t)
460              (t
461               nil)))
462         ;; User-defined spec -- find the spec name.
463         (when (eq (setq spec (char-after)) ?u)
464           (forward-char 1)
465           (setq user-defined (char-after)))
466         (forward-char 1)
467         (delete-region spec-beg (point))
468
469         ;; Now we have all the relevant data on this spec, so
470         ;; we start doing stuff.
471         (insert "%")
472         (if (eq spec ?%)
473             ;; "%%" just results in a "%".
474             (insert "%")
475           (cond
476            ;; Do tilde forms.
477            ((eq spec ?@)
478             (setq elem (list tilde-form ?s)))
479            ;; Treat user defined format specifiers specially.
480            (user-defined
481             (setq elem
482                   (list
483                    (list (intern (format "gnus-user-format-function-%c"
484                                          user-defined))
485                          'gnus-tmp-header)
486                    ?s)))
487            ;; Find the specification from `spec-alist'.
488            ((setq elem (cdr (assq spec spec-alist))))
489            (t
490             (setq elem '("*" ?s))))
491           (setq elem-type (cadr elem))
492           ;; Insert the new format elements.
493           (when pad-width
494             (insert (number-to-string pad-width)))
495           ;; Create the form to be evaled.
496           (if (or max-width cut-width ignore-value)
497               (progn
498                 (insert ?s)
499                 (let ((el (car elem)))
500                   (cond ((= (cadr elem) ?c)
501                          (setq el (list 'char-to-string el)))
502                         ((= (cadr elem) ?d)
503                          (setq el (list 'int-to-string el))))
504                   (when ignore-value
505                     (setq el (gnus-tilde-ignore-form el ignore-value)))
506                   (when cut-width
507                     (setq el (gnus-tilde-cut-form el cut-width)))
508                   (when max-width
509                     (setq el (gnus-tilde-max-form el max-width)))
510                   (push el flist)))
511             (insert elem-type)
512             (push (car elem) flist))))
513       (setq fstring (buffer-string)))
514
515     ;; Do some postprocessing to increase efficiency.
516     (setq
517      result
518      (cond
519       ;; Emptyness.
520       ((string= fstring "")
521        nil)
522       ;; Not a format string.
523       ((not (string-match "%" fstring))
524        (list fstring))
525       ;; A format string with just a single string spec.
526       ((string= fstring "%s")
527        (list (car flist)))
528       ;; A single character.
529       ((string= fstring "%c")
530        (list (car flist)))
531       ;; A single number.
532       ((string= fstring "%d")
533        (setq dontinsert)
534        (if insert
535            (list `(princ ,(car flist)))
536          (list `(int-to-string ,(car flist)))))
537       ;; Just lots of chars and strings.
538       ((string-match "\\`\\(%[cs]\\)+\\'" fstring)
539        (nreverse flist))
540       ;; A single string spec at the beginning of the spec.
541       ((string-match "\\`%[sc][^%]+\\'" fstring)
542        (list (car flist) (substring fstring 2)))
543       ;; A single string spec in the middle of the spec.
544       ((string-match "\\`\\([^%]+\\)%[sc]\\([^%]+\\)\\'" fstring)
545        (list (match-string 1 fstring) (car flist) (match-string 2 fstring)))
546       ;; A single string spec in the end of the spec.
547       ((string-match "\\`\\([^%]+\\)%[sc]\\'" fstring)
548        (list (match-string 1 fstring) (car flist)))
549       ;; A more complex spec.
550       (t
551        (list (cons 'format (cons fstring (nreverse flist)))))))
552
553     (if insert
554         (when result
555           (if dontinsert
556               result
557             (cons 'insert result)))
558       (cond ((stringp result)
559              result)
560             ((consp result)
561              (cons 'concat result))
562             (t "")))))
563
564 (defun gnus-eval-format (format &optional alist props)
565   "Eval the format variable FORMAT, using ALIST.
566 If PROPS, insert the result."
567   (let ((form (gnus-parse-format format alist props)))
568     (if props
569         (gnus-add-text-properties (point) (progn (eval form) (point)) props)
570       (eval form))))
571
572 (defun gnus-compile ()
573   "Byte-compile the user-defined format specs."
574   (interactive)
575   (require 'bytecomp)
576   (let ((entries gnus-format-specs)
577         (byte-compile-warnings '(unresolved callargs redefine))
578         entry gnus-tmp-func)
579     (save-excursion
580       (gnus-message 7 "Compiling format specs...")
581
582       (while entries
583         (setq entry (pop entries))
584         (if (eq (car entry) 'version)
585             (setq gnus-format-specs (delq entry gnus-format-specs))
586           (let ((form (caddr entry)))
587             (when (and (listp form)
588                        ;; Under GNU Emacs, it's (byte-code ...)
589                        (not (eq 'byte-code (car form)))
590                        ;; Under XEmacs, it's (funcall #<compiled-function ...>)
591                        (not (and (eq 'funcall (car form))
592                                  (byte-code-function-p (cadr form)))))
593               (defalias 'gnus-tmp-func `(lambda () ,form))
594               (byte-compile 'gnus-tmp-func)
595               (setcar (cddr entry) (gnus-byte-code 'gnus-tmp-func))))))
596
597       (push (cons 'version emacs-version) gnus-format-specs)
598       ;; Mark the .newsrc.eld file as "dirty".
599       (gnus-dribble-touch)
600       (gnus-message 7 "Compiling user specs...done"))))
601
602 (defun gnus-set-format (type &optional insertable)
603   (set (intern (format "gnus-%s-line-format-spec" type))
604        (gnus-parse-format
605         (symbol-value (intern (format "gnus-%s-line-format" type)))
606         (symbol-value (intern (format "gnus-%s-line-format-alist" type)))
607         insertable)))
608
609 (provide 'gnus-spec)
610
611 ;; Local Variables:
612 ;; coding: iso-8859-1
613 ;; End:
614
615 ;;; gnus-spec.el ends here