* gnus-spec.el (gnus-correct-length): New function.
[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 (defun gnus-correct-length (string)
255   "Return the correct width of STRING."
256   (let ((length 0))
257     (mapcar (lambda (char) (incf length (char-width char))) string)
258     length))
259
260 (defun gnus-correct-substring (string start end)
261   (let ((wstart 0)
262         (wend 0)
263         (seek 0)
264         (length (length string)))
265     ;; Find the start position.
266     (while (and (< seek length)
267                 (< wstart start))
268       (incf wstart (char-width (aref string seek)))
269       (incf seek))
270     (setq wend wstart
271           wstart seek)
272     ;; Find the end position.
273     (while (and (< seek length)
274                 (< wend end))
275       (incf wend (char-width (aref string seek)))
276       (incf seek))
277     (setq wend seek)
278     (substring string wstart (1- wend))))
279
280 (defun gnus-tilde-max-form (el max-width)
281   "Return a form that limits EL to MAX-WIDTH."
282   (let ((max (abs max-width)))
283     (if (symbolp el)
284         `(if (> (,(if gnus-use-correct-string-widths
285                       'gnus-correct-length
286                     'length) ,el)
287                 ,max)
288              ,(if (< max-width 0)
289                   `(,(if gnus-use-correct-string-widths
290                          'gnus-correct-substring
291                        'substring)
292                     ,el (- (,(if gnus-use-correct-string-widths
293                                  'gnus-correct-length
294                                'length)
295                             el) ,max))
296                 `(,(if gnus-use-correct-string-widths
297                        'gnus-correct-substring
298                      'substring)
299                   ,el 0 ,max))
300            ,el)
301       `(let ((val (eval ,el)))
302          (if (> (,(if gnus-use-correct-string-widths
303                       'gnus-correct-length
304                     'length) val) ,max)
305              ,(if (< max-width 0)
306                   `(,(if gnus-use-correct-string-widths
307                          'gnus-correct-substring
308                        'substring)
309                     val (- (,(if gnus-use-correct-string-widths
310                                  'gnus-correct-length
311                                'length) val) ,max))
312                 `(,(if gnus-use-correct-string-widths
313                        'gnus-correct-substring
314                      'substring)
315                   val 0 ,max))
316            val)))))
317
318 (defun gnus-tilde-cut-form (el cut-width)
319   "Return a form that cuts CUT-WIDTH off of EL."
320   (let ((cut (abs cut-width)))
321     (if (symbolp el)
322         `(if (> (length ,el) ,cut)
323              ,(if (< cut-width 0)
324                   `(substring ,el 0 (- (length el) ,cut))
325                 `(substring ,el ,cut))
326            ,el)
327       `(let ((val (eval ,el)))
328          (if (> (length val) ,cut)
329              ,(if (< cut-width 0)
330                   `(substring val 0 (- (length val) ,cut))
331                 `(substring val ,cut))
332            val)))))
333
334 (defun gnus-tilde-ignore-form (el ignore-value)
335   "Return a form that is blank when EL is IGNORE-VALUE."
336   (if (symbolp el)
337       `(if (equal ,el ,ignore-value)
338            "" ,el)
339     `(let ((val (eval ,el)))
340        (if (equal val ,ignore-value)
341            "" val))))
342
343 (defun gnus-parse-format (format spec-alist &optional insert)
344   ;; This function parses the FORMAT string with the help of the
345   ;; SPEC-ALIST and returns a list that can be eval'ed to return the
346   ;; string.  If the FORMAT string contains the specifiers %( and %)
347   ;; the text between them will have the mouse-face text property.
348   ;; If the FORMAT string contains the specifiers %[ and %], the text between
349   ;; them will have the balloon-help text property.
350   (if (string-match
351        "\\`\\(.*\\)%[0-9]?[{(«]\\(.*\\)%[0-9]?[»})]\\(.*\n?\\)\\'"
352        format)
353       (gnus-parse-complex-format format spec-alist)
354     ;; This is a simple format.
355     (gnus-parse-simple-format format spec-alist insert)))
356
357 (defun gnus-parse-complex-format (format spec-alist)
358   (save-excursion
359     (gnus-set-work-buffer)
360     (insert format)
361     (goto-char (point-min))
362     (while (re-search-forward "\"" nil t)
363       (replace-match "\\\"" nil t))
364     (goto-char (point-min))
365     (insert "(\"")
366     (while (re-search-forward "%\\([0-9]+\\)?\\([«»{}()]\\)" nil t)
367       (let ((number (if (match-beginning 1)
368                         (match-string 1) "0"))
369             (delim (aref (match-string 2) 0)))
370         (if (or (= delim ?\()
371                 (= delim ?\{)
372                 (= delim ?\«))
373             (replace-match (concat "\"("
374                                    (cond ((= delim ?\() "mouse")
375                                          ((= delim ?\{) "face")
376                                          (t "balloon"))
377                                    " " number " \""))
378           (replace-match "\")\""))))
379     (goto-char (point-max))
380     (insert "\")")
381     (goto-char (point-min))
382     (let ((form (read (current-buffer))))
383       (cons 'progn (gnus-complex-form-to-spec form spec-alist)))))
384
385 (defun gnus-complex-form-to-spec (form spec-alist)
386   (delq nil
387         (mapcar
388          (lambda (sform)
389            (if (stringp sform)
390                (gnus-parse-simple-format sform spec-alist t)
391              (funcall (intern (format "gnus-%s-face-function" (car sform)))
392                       (gnus-complex-form-to-spec (cddr sform) spec-alist)
393                       (nth 1 sform))))
394          form)))
395
396 (defun gnus-parse-simple-format (format spec-alist &optional insert)
397   ;; This function parses the FORMAT string with the help of the
398   ;; SPEC-ALIST and returns a list that can be eval'ed to return a
399   ;; string.
400   (let ((max-width 0)
401         spec flist fstring elem result dontinsert user-defined
402         type value pad-width spec-beg cut-width ignore-value
403         tilde-form tilde elem-type)
404     (save-excursion
405       (gnus-set-work-buffer)
406       (insert format)
407       (goto-char (point-min))
408       (while (re-search-forward "%" nil t)
409         (setq user-defined nil
410               spec-beg nil
411               pad-width nil
412               max-width nil
413               cut-width nil
414               ignore-value nil
415               tilde-form nil)
416         (setq spec-beg (1- (point)))
417
418         ;; Parse this spec fully.
419         (while
420             (cond
421              ((looking-at "\\([-.0-9]+\\)\\(,[-0-9]+\\)?")
422               (setq pad-width (string-to-number (match-string 1)))
423               (when (match-beginning 2)
424                 (setq max-width (string-to-number (buffer-substring
425                                                    (1+ (match-beginning 2))
426                                                    (match-end 2)))))
427               (goto-char (match-end 0)))
428              ((looking-at "~")
429               (forward-char 1)
430               (setq tilde (read (current-buffer))
431                     type (car tilde)
432                     value (cadr tilde))
433               (cond
434                ((memq type '(pad pad-left))
435                 (setq pad-width value))
436                ((eq type 'pad-right)
437                 (setq pad-width (- value)))
438                ((memq type '(max-right max))
439                 (setq max-width value))
440                ((eq type 'max-left)
441                 (setq max-width (- value)))
442                ((memq type '(cut cut-left))
443                 (setq cut-width value))
444                ((eq type 'cut-right)
445                 (setq cut-width (- value)))
446                ((eq type 'ignore)
447                 (setq ignore-value
448                       (if (stringp value) value (format "%s" value))))
449                ((eq type 'form)
450                 (setq tilde-form value))
451                (t
452                 (error "Unknown tilde type: %s" tilde)))
453               t)
454              (t
455               nil)))
456         ;; User-defined spec -- find the spec name.
457         (when (eq (setq spec (char-after)) ?u)
458           (forward-char 1)
459           (setq user-defined (char-after)))
460         (forward-char 1)
461         (delete-region spec-beg (point))
462
463         ;; Now we have all the relevant data on this spec, so
464         ;; we start doing stuff.
465         (insert "%")
466         (if (eq spec ?%)
467             ;; "%%" just results in a "%".
468             (insert "%")
469           (cond
470            ;; Do tilde forms.
471            ((eq spec ?@)
472             (setq elem (list tilde-form ?s)))
473            ;; Treat user defined format specifiers specially.
474            (user-defined
475             (setq elem
476                   (list
477                    (list (intern (format "gnus-user-format-function-%c"
478                                          user-defined))
479                          'gnus-tmp-header)
480                    ?s)))
481            ;; Find the specification from `spec-alist'.
482            ((setq elem (cdr (assq spec spec-alist))))
483            (t
484             (setq elem '("*" ?s))))
485           (setq elem-type (cadr elem))
486           ;; Insert the new format elements.
487           (when pad-width
488             (insert (number-to-string pad-width)))
489           ;; Create the form to be evaled.
490           (if (or max-width cut-width ignore-value)
491               (progn
492                 (insert ?s)
493                 (let ((el (car elem)))
494                   (cond ((= (cadr elem) ?c)
495                          (setq el (list 'char-to-string el)))
496                         ((= (cadr elem) ?d)
497                          (setq el (list 'int-to-string el))))
498                   (when ignore-value
499                     (setq el (gnus-tilde-ignore-form el ignore-value)))
500                   (when cut-width
501                     (setq el (gnus-tilde-cut-form el cut-width)))
502                   (when max-width
503                     (setq el (gnus-tilde-max-form el max-width)))
504                   (push el flist)))
505             (insert elem-type)
506             (push (car elem) flist))))
507       (setq fstring (buffer-string)))
508
509     ;; Do some postprocessing to increase efficiency.
510     (setq
511      result
512      (cond
513       ;; Emptyness.
514       ((string= fstring "")
515        nil)
516       ;; Not a format string.
517       ((not (string-match "%" fstring))
518        (list fstring))
519       ;; A format string with just a single string spec.
520       ((string= fstring "%s")
521        (list (car flist)))
522       ;; A single character.
523       ((string= fstring "%c")
524        (list (car flist)))
525       ;; A single number.
526       ((string= fstring "%d")
527        (setq dontinsert)
528        (if insert
529            (list `(princ ,(car flist)))
530          (list `(int-to-string ,(car flist)))))
531       ;; Just lots of chars and strings.
532       ((string-match "\\`\\(%[cs]\\)+\\'" fstring)
533        (nreverse flist))
534       ;; A single string spec at the beginning of the spec.
535       ((string-match "\\`%[sc][^%]+\\'" fstring)
536        (list (car flist) (substring fstring 2)))
537       ;; A single string spec in the middle of the spec.
538       ((string-match "\\`\\([^%]+\\)%[sc]\\([^%]+\\)\\'" fstring)
539        (list (match-string 1 fstring) (car flist) (match-string 2 fstring)))
540       ;; A single string spec in the end of the spec.
541       ((string-match "\\`\\([^%]+\\)%[sc]\\'" fstring)
542        (list (match-string 1 fstring) (car flist)))
543       ;; A more complex spec.
544       (t
545        (list (cons 'format (cons fstring (nreverse flist)))))))
546
547     (if insert
548         (when result
549           (if dontinsert
550               result
551             (cons 'insert result)))
552       (cond ((stringp result)
553              result)
554             ((consp result)
555              (cons 'concat result))
556             (t "")))))
557
558 (defun gnus-eval-format (format &optional alist props)
559   "Eval the format variable FORMAT, using ALIST.
560 If PROPS, insert the result."
561   (let ((form (gnus-parse-format format alist props)))
562     (if props
563         (gnus-add-text-properties (point) (progn (eval form) (point)) props)
564       (eval form))))
565
566 (defun gnus-compile ()
567   "Byte-compile the user-defined format specs."
568   (interactive)
569   (require 'bytecomp)
570   (let ((entries gnus-format-specs)
571         (byte-compile-warnings '(unresolved callargs redefine))
572         entry gnus-tmp-func)
573     (save-excursion
574       (gnus-message 7 "Compiling format specs...")
575
576       (while entries
577         (setq entry (pop entries))
578         (if (eq (car entry) 'version)
579             (setq gnus-format-specs (delq entry gnus-format-specs))
580           (let ((form (caddr entry)))
581             (when (and (listp form)
582                        ;; Under GNU Emacs, it's (byte-code ...)
583                        (not (eq 'byte-code (car form)))
584                        ;; Under XEmacs, it's (funcall #<compiled-function ...>)
585                        (not (and (eq 'funcall (car form))
586                                  (byte-code-function-p (cadr form)))))
587               (defalias 'gnus-tmp-func `(lambda () ,form))
588               (byte-compile 'gnus-tmp-func)
589               (setcar (cddr entry) (gnus-byte-code 'gnus-tmp-func))))))
590
591       (push (cons 'version emacs-version) gnus-format-specs)
592       ;; Mark the .newsrc.eld file as "dirty".
593       (gnus-dribble-touch)
594       (gnus-message 7 "Compiling user specs...done"))))
595
596 (defun gnus-set-format (type &optional insertable)
597   (set (intern (format "gnus-%s-line-format-spec" type))
598        (gnus-parse-format
599         (symbol-value (intern (format "gnus-%s-line-format" type)))
600         (symbol-value (intern (format "gnus-%s-line-format-alist" type)))
601         insertable)))
602
603 (provide 'gnus-spec)
604
605 ;; Local Variables:
606 ;; coding: iso-8859-1
607 ;; End:
608
609 ;;; gnus-spec.el ends here