Initial Commit
[packages] / xemacs-packages / text-modes / po-mode.el
1 ;;; po-mode.el -- major mode for GNU gettext PO files
2
3 ;; Copyright (C) 1995-1999, 2000-2002 Free Software Foundation, Inc.
4
5 ;; Authors: François Pinard <pinard@iro.umontreal.ca>
6 ;;          Greg McGary <gkm@magilla.cichlid.com>
7 ;; Keywords: i18n gettext
8 ;; Created: 1995
9
10 ;; This file is part of GNU gettext.
11
12 ;; GNU gettext is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU gettext is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, 59 Temple Place - Suite 330, Boston,
25 ;; MA 02111-1307, USA.
26
27 ;;; Commentary:
28
29 ;; This package provides the tools meant to help editing PO files,
30 ;; as documented in the GNU gettext user's manual.  See this manual
31 ;; for user documentation, which is not repeated here.
32
33 ;; To install, merely put this file somewhere GNU Emacs will find it,
34 ;; then add the following lines to your .emacs file:
35 ;;
36 ;;   (autoload 'po-mode "po-mode"
37 ;;             "Major mode for translators to edit PO files" t)
38 ;;   (setq auto-mode-alist (cons '("\\.po\\'\\|\\.po\\." . po-mode)
39 ;;                                auto-mode-alist))
40 ;;
41 ;; To use the right coding system automatically under Emacs 20 or newer,
42 ;; also add:
43 ;;
44 ;;   (autoload 'po-find-file-coding-system "po-compat")
45 ;;   (modify-coding-system-alist 'file "\\.po\\'\\|\\.po\\."
46 ;;                                'po-find-file-coding-system)
47 ;;
48 ;; You may also adjust some variables, below, by defining them in your
49 ;; '.emacs' file, either directly or through command 'M-x customize'.
50
51 ;;; Code:
52 \f
53 (defconst po-mode-version-string "2.01" "\
54 Version number of this version of po-mode.el.")
55
56 ;;; Emacs portability matters - part I.
57 ;;; Here is the minimum for customization to work.  See part II.
58
59 ;; Identify which Emacs variety is being used.
60 ;; This file supports:
61 ;;   - XEmacs (version 19 and above) -> po-XEMACS = t,
62 ;;   - GNU Emacs (version 20 and above) -> po-EMACS20 = t,
63 ;;   - GNU Emacs (version 19) -> no flag.
64 (eval-and-compile
65   (cond ((string-match "XEmacs\\|Lucid" emacs-version)
66          (setq po-EMACS20 nil po-XEMACS t))
67         ((and (string-lessp "19" emacs-version) (featurep 'faces))
68          (setq po-EMACS20 t po-XEMACS nil))
69         (t (setq po-EMACS20 nil po-XEMACS nil))))
70
71 ;; Experiment with Emacs LISP message internationalisation.
72 (eval-and-compile
73   (or (fboundp 'set-translation-domain)
74       (defsubst set-translation-domain (string) nil))
75   (or (fboundp 'translate-string)
76       (defsubst translate-string (string) string)))
77 (defsubst _ (string) (translate-string string))
78 (defsubst N_ (string) string)
79
80 ;; Handle missing 'customs' package.
81 (eval-and-compile
82   (condition-case ()
83       (require 'custom)
84     (error nil))
85   (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
86       nil
87     (defmacro defgroup (&rest args)
88       nil)
89     (defmacro defcustom (var value doc &rest args)
90       (` (defvar (, var) (, value) (, doc))))))
91 \f
92 ;;; Customisation.
93
94 (defgroup po nil
95   "Major mode for editing PO files"
96   :group 'i18n)
97
98 (defcustom po-auto-edit-with-msgid nil
99   "*Automatically use msgid when editing untranslated entries."
100   :type 'boolean
101   :group 'po)
102
103 (defcustom po-auto-fuzzy-on-edit nil
104   "*Automatically mark entries fuzzy when being edited."
105   :type 'boolean
106   :group 'po)
107
108 (defcustom po-auto-select-on-unfuzzy nil
109   "*Automatically select some new entry while making an entry not fuzzy."
110   :type 'boolean
111   :group 'po)
112
113 (defcustom po-auto-replace-revision-date t
114   "*Automatically revise date in headers.  Value is nil, t, or ask."
115   :type '(choice (const nil)
116                  (const t)
117                  (const ask))
118   :group 'po)
119
120 (defcustom po-default-file-header "\
121 # SOME DESCRIPTIVE TITLE.
122 # Copyright (C) YEAR Free Software Foundation, Inc.
123 # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
124 #
125 #, fuzzy
126 msgid \"\"
127 msgstr \"\"
128 \"Project-Id-Version: PACKAGE VERSION\\n\"
129 \"PO-Revision-Date: YEAR-MO-DA HO:MI +ZONE\\n\"
130 \"Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n\"
131 \"Language-Team: LANGUAGE <LL@li.org>\\n\"
132 \"MIME-Version: 1.0\\n\"
133 \"Content-Type: text/plain; charset=CHARSET\\n\"
134 \"Content-Transfer-Encoding: 8bit\\n\"
135 "
136   "*Default PO file header."
137   :type 'string
138   :group 'po)
139
140 (defcustom po-translation-project-address
141   "translation@iro.umontreal.ca"
142   "*Electronic mail address of the Translation Project.
143 Typing \\[po-send-mail] (normally bound to `M') the user will send the PO file
144 to this email address."
145   :type 'string
146   :group 'po)
147
148 (defcustom po-translation-project-mail-label "TP-Robot"
149   "*Subject label when sending the PO file to `po-translation-project-address'.
150 Don't change it when you send PO files to \"translation@iro.umontreal.ca\", the
151 Translation Project Robot at http://www.iro.umontreal.ca/contrib/po/HTML/.  If
152 the label is different, your submission will be consiedered as a regular mail
153 and not stored at the TP site and also not forwarded to the package maintainer."
154   :type 'string
155   :group 'po)
156
157 (defcustom po-highlighting (or po-EMACS20 po-XEMACS)
158   "*Highlight text whenever appropriate, when non-nil.
159 However, on older Emacses, a yet unexplained highlighting bug causes files
160 to get mangled."
161   :type 'boolean
162   :group 'po)
163
164 (defcustom po-highlight-face 'highlight
165   "*The face used for PO mode highlighting.  For Emacses with overlays.
166 Possible values are 'highlight', 'modeline', 'secondary-selection',
167 'region', and 'underline'.
168 This variable can be set by the user to whatever face they desire.
169 It's most convenient if the cursor color and highlight color are
170 slightly different."
171   :type 'face
172   :group 'po)
173
174 (defcustom po-team-name-to-code
175   ;; All possible languages, a complete ISO 639 list and a little more.
176   '(("LANGUAGE" . "LL")
177     ("(Afan) Oromo" . "om")
178     ("Abkhazian" . "ab")
179     ("Afar" . "aa")
180     ("Afrikaans" . "af")
181     ("Albanian" . "sq")
182     ("Amharic" . "am")
183     ("Arabic" . "ar")
184     ("Argentinian" . "es_AR")
185     ("Armenian" . "hy")
186     ("Assamese" . "as")
187     ("Avestan" . "ae")
188     ("Aymara" . "ay")
189     ("Azerbaijani" . "az")
190     ("Bashkir" . "ba")
191     ("Basque" . "eu")
192     ("Belarusian" . "be")
193     ("Bengali" . "bn")
194     ("Bihari" . "bh")
195     ("Bislama" . "bi")
196     ("Bosnian" . "bs")
197     ("Brazilian Portuguese" . "pt_BR")
198     ("Breton" . "br")
199     ("Bulgarian" . "bg")
200     ("Burmese" . "my")
201     ("Catalan" . "ca")
202     ("Chamorro" . "ch")
203     ("Chechen" . "ce")
204     ("Chinese" . "zh")
205     ("Chinese (simplified)" . "zh_CN")
206     ("Chinese (traditional)" . "zh_TW")
207     ("Church Slavic" . "cu")
208     ("Chuvash" . "cv")
209     ("Cornish" . "kw")
210     ("Corsican" . "co")
211     ("Croatian" . "hr")
212     ("Czech" . "cs")
213     ("Danish" . "da")
214     ("Dutch" . "nl")
215     ("Dzongkha" . "dz")
216     ("English" . "en")
217     ("Esperanto" . "eo")
218     ("Estonian" . "et")
219     ("Faroese" . "fo")
220     ("Fijian" . "fj")
221     ("Finnish" . "fi")
222     ("French" . "fr")
223     ("Frisian" . "fy")
224     ("Galician" . "gl")
225     ("Georgian" . "ka")
226     ("German" . "de")
227     ("Greek" . "el")
228     ("Guarani" . "gn")
229     ("Gujarati" . "gu")
230     ("Hausa" . "ha")
231     ("Hebrew" . "he")
232     ("Herero" . "hz")
233     ("Hindi" . "hi")
234     ("Hiri Motu" . "ho")
235     ("Hungarian" . "hu")
236     ("Icelandic" . "is")
237     ("Ido" . "io")
238     ("Indonesian" . "id")
239     ("Interlingua" . "ia")
240     ("Interlingue" . "ie")
241     ("Inuktitut" . "iu")
242     ("Inupiak" . "ik")
243     ("Irish" . "ga")
244     ("Italian" . "it")
245     ("Japanese" . "ja")
246     ("Javanese" . "jv")
247     ("Kalaallisut" . "kl")
248     ("Kannada" . "kn")
249     ("Kashmiri" . "ks")
250     ("Kazakh" . "kk")
251     ("Khmer" . "km")
252     ("Kikuyu" . "ki")
253     ("Kinyarwanda" . "rw")
254     ("Kirghiz" . "ky")
255     ("Kirundi" . "rn")
256     ("Komi" . "kv")
257     ("Konkani" . "kok")
258     ("Korean" . "ko")
259     ("Kuanyama" . "kj")
260     ("Kurdish" . "ku")
261     ("Laotian" . "lo")
262     ("Latin" . "la")
263     ("Latvian" . "lv")
264     ("Letzeburgesch" . "lb")
265     ("Lingala" . "ln")
266     ("Lithuanian" . "lt")
267     ("Macedonian" . "mk")
268     ("Malagasy" . "mg")
269     ("Malay" . "ms")
270     ("Malayalam" . "ml")
271     ("Maltese" . "mt")
272     ("Manipuri" . "mni")
273     ("Manx" . "gv")
274     ("Maori" . "mi")
275     ("Marathi" . "mr")
276     ("Marshall" . "mh")
277     ("Moldavian" . "mo")
278     ("Mongolian" . "mn")
279     ("Nauru" . "na")
280     ("Navajo" . "nv")
281     ("Ndonga" . "ng")
282     ("Nepali" . "ne")
283     ("North Ndebele" . "nd")
284     ("Northern Sami" . "se")
285     ("Norwegian Bokmal" . "nb")
286     ("Norwegian Nynorsk" . "nn")
287     ("Norwegian" . "no")
288     ("Nyanja" . "ny")
289     ("Occitan" . "oc")
290     ("Oriya" . "or")
291     ("Ossetian" . "os")
292     ("Pali" . "pi")
293     ("Pashto" . "ps")
294     ("Persian" . "fa")
295     ("Polish" . "pl")
296     ("Portuguese" . "pt")
297     ("Punjabi" . "pa")
298     ("Quechua" . "qu")
299     ("Rhaeto-Roman" . "rm")
300     ("Romanian" . "ro")
301     ("Russian" . "ru")
302     ("Samoan" . "sm")
303     ("Sango" . "sg")
304     ("Sanskrit" . "sa")
305     ("Sardinian" . "sc")
306     ("Scots" . "gd")
307     ("Serbian" . "sr")
308     ("Sesotho" . "st")
309     ("Setswana" . "tn")
310     ("Shona" . "sn")
311     ("Sindhi" . "sd")
312     ("Sinhalese" . "si")
313     ("Siswati" . "ss")
314     ("Slovak" . "sk")
315     ("Slovenian" . "sl")
316     ("Somali" . "so")
317     ("Sorbian" . "wen")
318     ("South Ndebele" . "nr")
319     ("Spanish" . "es")
320     ("Sundanese" . "su")
321     ("Swahili" . "sw")
322     ("Swedish" . "sv")
323     ("Tagalog" . "tl")
324     ("Tahitian" . "ty")
325     ("Tajik" . "tg")
326     ("Tamil" . "ta")
327     ("Tatar" . "tt")
328     ("Telugu" . "te")
329     ("Thai" . "th")
330     ("Tibetan" . "bo")
331     ("Tigrinya" . "ti")
332     ("Tonga" . "to")
333     ("Tsonga" . "ts")
334     ("Turkish" . "tr")
335     ("Turkmen" . "tk")
336     ("Twi" . "tw")
337     ("Uighur" . "ug")
338     ("Ukrainian" . "uk")
339     ("Urdu" . "ur")
340     ("Uzbek" . "uz")
341     ("Vietnamese" . "vi")
342     ("Volapuk" . "vo")
343     ("Walloon" . "wa")
344     ("Welsh" . "cy")
345     ("Wolof" . "wo")
346     ("Xhosa" . "xh")
347     ("Yiddish" . "yi")
348     ("Yoruba" . "yo")
349     ("Zhuang" . "za")
350     ("Zulu" . "zu")
351     )
352   "*Association list giving team codes from team names.
353 This is used for generating a submission file name for the 'M' command.
354 If a string instead of an alist, it is a team code to use unconditionnally."
355   :type 'sexp
356   :group 'po)
357
358 (defcustom po-gzip-uuencode-command "gzip -9 | uuencode -m"
359   "*The filter to use for preparing a mail invoice of the PO file.
360 Normally \"gzip -9 | uuencode -m\", remove the -9 for lesser compression,
361 or remove the -m if you are not using the GNU version of 'uuencode'."
362   :type 'string
363   :group 'po)
364
365 (defvar po-subedit-mode-syntax-table
366   (copy-syntax-table text-mode-syntax-table)
367   "Syntax table used while in PO mode.")
368 \f
369 ;;; Emacs portability matters - part II.
370
371 ;;; Many portability matters are addressed in this page.  The few remaining
372 ;;; cases, elsewhere, all involve  'eval-and-compile', 'boundp' or 'fboundp'.
373
374 ;; Protect string comparisons from text properties if possible.
375 (eval-and-compile
376   (fset 'po-buffer-substring
377         (symbol-function (if (fboundp 'buffer-substring-no-properties)
378                              'buffer-substring-no-properties
379                            'buffer-substring)))
380
381   (if (fboundp 'match-string-no-properties)
382       (fset 'po-match-string (symbol-function 'match-string-no-properties))
383     (defun po-match-string (number)
384       "Return string of text matched by last search."
385       (po-buffer-substring (match-beginning number) (match-end number)))))
386
387 ;; Handle missing 'with-temp-buffer' function.
388 (eval-and-compile
389   (if (fboundp 'with-temp-buffer)
390       (fset 'po-with-temp-buffer (symbol-function 'with-temp-buffer))
391
392     (defmacro po-with-temp-buffer (&rest forms)
393       "Create a temporary buffer, and evaluate FORMS there like 'progn'."
394       (let ((curr-buffer (make-symbol "curr-buffer"))
395             (temp-buffer (make-symbol "temp-buffer")))
396         `(let ((,curr-buffer (current-buffer))
397                (,temp-buffer (get-buffer-create
398                               (generate-new-buffer-name " *po-temp*"))))
399            (unwind-protect
400                (progn
401                  (set-buffer ,temp-buffer)
402                  ,@forms)
403              (set-buffer ,curr-buffer)
404              (and (buffer-name ,temp-buffer)
405                   (kill-buffer ,temp-buffer))))))))
406
407 ;; Handle missing 'kill-new' function.
408 (eval-and-compile
409   (if (fboundp 'kill-new)
410       (fset 'po-kill-new (symbol-function 'kill-new))
411
412     (defun po-kill-new (string)
413       "Push STRING onto the kill ring, for Emacs 18 where kill-new is missing."
414       (po-with-temp-buffer
415         (insert string)
416         (kill-region (point-min) (point-max))))))
417
418 ;; Handle missing 'read-event' function.
419 (eval-and-compile
420   (fset 'po-read-event
421         (cond ((fboundp 'read-event)
422                ;; GNU Emacs.
423                'read-event)
424               ((fboundp 'next-command-event)
425                ;; XEmacs.
426                'next-command-event)
427               (t
428                ;; Older Emacses.
429                'read-char))))
430
431 ;; Handle missing 'force-mode-line-update' function.
432 (eval-and-compile
433   (if (fboundp 'force-mode-line-update)
434       (fset 'po-force-mode-line-update
435             (symbol-function 'force-mode-line-update))
436
437     (defun po-force-mode-line-update ()
438       "Force the mode-line of the current buffer to be redisplayed."
439       (set-buffer-modified-p (buffer-modified-p)))))
440
441 ;; Handle portable highlighting.  Code has been adapted (OK... stolen! :-)
442 ;; from 'ispell.el'.
443 (eval-and-compile
444   (cond
445    (po-EMACS20
446
447     (defun po-create-overlay ()
448       "Create and return a deleted overlay structure.
449 The variable 'po-highlight-face' selects the face to use for highlighting."
450       (let ((overlay (make-overlay (point) (point))))
451         (overlay-put overlay 'face po-highlight-face)
452         ;; The fun thing is that a deleted overlay retains its face, and is
453         ;; movable.
454         (delete-overlay overlay)
455         overlay))
456
457     (defun po-highlight (overlay start end &optional buffer)
458       "Use OVERLAY to highlight the string from START to END.
459 If limits are not relative to the current buffer, use optional BUFFER."
460       (move-overlay overlay start end (or buffer (current-buffer))))
461
462     (defun po-rehighlight (overlay)
463       "Ensure OVERLAY is highlighted."
464       ;; There is nothing to do, as GNU Emacs allows multiple highlights.
465       nil)
466
467     (defun po-dehighlight (overlay)
468       "Display normally the last string which OVERLAY highlighted.
469 The current buffer should be in PO mode, when this function is called."
470       (delete-overlay overlay)))
471
472    (po-XEMACS
473
474     (defun po-create-overlay ()
475       "Create and return a deleted overlay structure."
476       ;; The same as for GNU Emacs above, except the created extent is
477       ;; already detached, so there's no need to "delete" it
478       ;; explicitly.
479       (let ((extent (make-extent nil nil)))
480         (set-extent-face extent po-highlight-face)
481         extent))
482
483     (defun po-highlight (extent start end &optional buffer)
484       "Use EXTENT to highlight the string from START to END.
485 If limits are not relative to the current buffer, use optional BUFFER."
486       (set-extent-endpoints extent start end (or buffer (current-buffer))))
487
488     (defun po-rehighlight (extent)
489       "Ensure EXTENT is highlighted."
490       ;; Nothing to do here.
491       nil)
492
493     (defun po-dehighlight (extent)
494       "Display normally the last string which EXTENT highlighted."
495       (detach-extent extent)))
496
497    (t
498
499     (defun po-create-overlay ()
500       "Create and return a deleted overlay structure."
501       (cons (make-marker) (make-marker)))
502
503     (defun po-highlight (overlay start end &optional buffer)
504       "Use OVERLAY to highlight the string from START to END.
505 If limits are not relative to the current buffer, use optional BUFFER.
506 No doubt that highlighting, when Emacs does not allow it, is a kludge."
507       (save-excursion
508         (and buffer (set-buffer buffer))
509         (let ((modified (buffer-modified-p))
510               (buffer-read-only nil)
511               (inhibit-quit t)
512               (buffer-undo-list t)
513               (text (buffer-substring start end)))
514           (goto-char start)
515           (delete-region start end)
516           (insert-char ?  (- end start))
517           (sit-for 0)
518           (setq inverse-video (not inverse-video))
519           (delete-region start end)
520           (insert text)
521           (sit-for 0)
522           (setq inverse-video (not inverse-video))
523           (set-buffer-modified-p modified)))
524       (set-marker (car overlay) start (or buffer (current-buffer)))
525       (set-marker (cdr overlay) end (or buffer (current-buffer))))
526
527     (defun po-rehighlight (overlay)
528       "Ensure OVERLAY is highlighted."
529       (let ((buffer (marker-buffer (car overlay)))
530             (start (marker-position (car overlay)))
531             (end (marker-position (cdr overlay))))
532         (and buffer
533              (buffer-name buffer)
534              (po-highlight overlay start end buffer))))
535
536     (defun po-dehighlight (overlay)
537       "Display normally the last string which OVERLAY highlighted."
538       (let ((buffer (marker-buffer (car overlay)))
539             (start (marker-position (car overlay)))
540             (end (marker-position (cdr overlay))))
541         (if buffer
542             (save-excursion
543               (set-buffer buffer)
544               (let ((modified (buffer-modified-p))
545                     (buffer-read-only nil)
546                     (inhibit-quit t)
547                     (buffer-undo-list t))
548                 (let ((text (buffer-substring start end)))
549                   (goto-char start)
550                   (delete-region start end)
551                   (insert-char ?  (- end start))
552                   (sit-for 0)
553                   (delete-region start end)
554                   (insert text)
555                   (sit-for 0)
556                   (set-buffer-modified-p modified)))))
557         (setcar overlay (make-marker))
558         (setcdr overlay (make-marker))))
559
560     )))
561 \f
562 ;;; Buffer local variables.
563
564 ;; The following block of declarations has the main purpose of avoiding
565 ;; byte compiler warnings.  It also introduces some documentation for
566 ;; each of these variables, all meant to be local to PO mode buffers.
567
568 ;; Flag telling that MODE-LINE-STRING should be displayed.  See 'Window'
569 ;; page below.  Exceptionally, this variable is local to *all* buffers.
570 (defvar po-mode-flag)
571
572 ;; PO buffers are kept read-only to prevent random modifications.  READ-ONLY
573 ;; holds the value of the read-only flag before PO mode was entered.
574 (defvar po-read-only)
575
576 ;; The current entry extends from START-OF-ENTRY to END-OF-ENTRY, it
577 ;; includes preceding whitespace and excludes following whitespace.  The
578 ;; start of keyword lines are START-OF-MSGID and START-OF-MSGSTR.
579 ;; ENTRY-TYPE classifies the entry.
580 (defvar po-start-of-entry)
581 (defvar po-start-of-msgid)
582 (defvar po-start-of-msgstr)
583 (defvar po-end-of-entry)
584 (defvar po-entry-type)
585
586 ;; A few counters are usefully shown in the Emacs mode line.
587 (defvar po-translated-counter)
588 (defvar po-fuzzy-counter)
589 (defvar po-untranslated-counter)
590 (defvar po-obsolete-counter)
591 (defvar po-mode-line-string)
592
593 ;; PO mode keeps track of fields being edited, for one given field should
594 ;; have one editing buffer at most, and for exiting a PO buffer properly
595 ;; should offer to close all pending edits.  Variable EDITED-FIELDS holds an
596 ;; an list of "slots" of the form: (ENTRY-MARKER EDIT-BUFFER OVERLAY-INFO).
597 ;; To allow simultaneous edition of the comment and the msgstr of an entry,
598 ;; ENTRY-MARKER points to the msgid line if a comment is being edited, or to
599 ;; the msgstr line if the msgstr is being edited.  EDIT-BUFFER is the
600 ;; temporary Emacs buffer used to edit the string.  OVERLAY-INFO, when not
601 ;; nil, holds an overlay (or if overlays are not supported, a cons of two
602 ;; markers) for this msgid string which became highlighted for the edit.
603 (defvar po-edited-fields)
604
605 ;; We maintain a set of movable pointers for returning to entries.
606 (defvar po-marker-stack)
607
608 ;; SEARCH path contains a list of directories where files may be found,
609 ;; in a format suitable for read completion.  Each directory includes
610 ;; its trailing slash.  PO mode starts with "./" and "../".
611 (defvar po-search-path)
612
613 ;; The following variables are meaningful only when REFERENCE-CHECK
614 ;; is identical to START-OF-ENTRY, else they should be recomputed.
615 ;; REFERENCE-ALIST contains all known references for the current
616 ;; entry, each list element is (PROMPT FILE LINE), where PROMPT may
617 ;; be used for completing read, FILE is a string and LINE is a number.
618 ;; REFERENCE-CURSOR is a cycling cursor into REFERENCE-ALIST.
619 (defvar po-reference-alist)
620 (defvar po-reference-cursor)
621 (defvar po-reference-check)
622
623 ;; The following variables are for marking translatable strings in program
624 ;; sources.  KEYWORDS is the list of keywords for marking translatable
625 ;; strings, kept in a format suitable for reading with completion.
626 ;; STRING-CONTENTS holds the value of the most recent string found in sources,
627 ;; and when it is not nil, then STRING-BUFFER, STRING-START and STRING-END
628 ;; describe where it is.  MARKING-OVERLAY, if not 'nil', holds the overlay
629 ;; which highlight the last found string; for older Emacses, it holds the cons
630 ;; of two markers around the highlighted region.
631 (defvar po-keywords)
632 (defvar po-string-contents)
633 (defvar po-string-buffer)
634 (defvar po-string-start)
635 (defvar po-string-end)
636 (defvar po-marking-overlay)
637 \f
638 ;;; PO mode variables and constants (usually not to customize).
639
640 ;; The textdomain should really be "gettext", only trying it for now.
641 ;; All this requires more thinking, we cannot just do this like that.
642 (set-translation-domain "po-mode")
643
644 (defun po-mode-version ()
645   "Show Emacs PO mode version."
646   (interactive)
647   (message (_"Emacs PO mode, version %s") po-mode-version-string))
648
649 (defconst po-help-display-string
650   (_"\
651 PO Mode Summary           Next Previous            Miscellaneous
652 *: Later, /: Docum        n    p    Any type       .     Redisplay
653                           t    T    Translated     /v    Version info
654 Moving around             f    F    Fuzzy          ?, h  This help
655 <    First if any         o    O    Obsolete       =     Current index
656 >    Last if any          u    U    Untranslated   0     Other window
657 /SPC Auto select                                   V     Validate
658                         Msgstr Comments            M     Mail officially
659 Modifying entries         RET  #    Call editor    _     Undo
660 TAB   Remove fuzzy mark   k    K    Kill to        E     Edit out full
661 DEL   Fuzzy or fade out   w    W    Copy to        Q     Forceful quit
662 LFD   Init with msgid     y    Y    Yank from      q     Confirm and quit
663
664 gettext Keyword Marking                            Position Stack
665 ,    Find next string     Compendiums              m  Mark and push current
666 M-,  Mark translatable    *c    To compendium      r  Pop and return
667 M-.  Change mark, mark    *M-C  Select, save       x  Exchange current/top
668
669 Program Sources           Auxiliary Files          Lexicography
670 s    Cycle reference      a    Cycle file          *l    Lookup translation
671 M-s  Select reference     C-c C-a  Select file     *M-l  Add/edit translation
672 S    Consider path        A    Consider PO file    *L    Consider lexicon
673 M-S  Ignore path          M-A  Ignore PO file      *M-L  Ignore lexicon
674 ")
675   "Help page for PO mode.")
676
677 (defconst po-mode-menu-layout
678   `("PO"
679     ("Moving around"
680      ["Auto select" po-auto-select-entry
681       ,@(if (featurep 'xemacs) '(t)
682           '(:help "Jump to next interesting entry"))]
683      "---"
684      "Forward"
685      ["Any next" po-next-entry
686       ,@(if (featurep 'xemacs) '(t)
687           '(:help "Jump to next entry"))]
688      ["Next translated" po-next-translated-entry
689       ,@(if (featurep 'xemacs) '(t)
690           '(:help "Jump to next translated entry"))]
691      ["Next fuzzy" po-next-fuzzy-entry
692       ,@(if (featurep 'xemacs) '(t)
693           '(:help "Jump to next fuzzy entry"))]
694      ["Next obsolete" po-next-obsolete-entry
695       ,@(if (featurep 'xemacs) '(t)
696           '(:help "Jump to next obsolete entry"))]
697      ["Next untranslated" po-next-untranslated-entry
698       ,@(if (featurep 'xemacs) '(t)
699           '(:help "Jump to next untranslated entry"))]
700      ["Last file entry" po-last-entry
701       ,@(if (featurep 'xemacs) '(t)
702           '(:help "Jump to last entry"))]
703      "---"
704      "Backward"
705      ["Any previous" po-previous-entry
706       ,@(if (featurep 'xemacs) '(t)
707           '(:help "Jump to previous entry"))]
708      ["Previous translated" po-previous-translated-entry
709       ,@(if (featurep 'xemacs) '(t)
710           '(:help "Jump to previous translated entry"))]
711      ["Previous fuzzy" po-previous-fuzzy-entry
712       ,@(if (featurep 'xemacs) '(t)
713           '(:help "Jump to previous fuzzy entry"))]
714      ["Previous obsolete" po-previous-obsolete-entry
715       ,@(if (featurep 'xemacs) '(t)
716           '(:help "Jump to previous obsolete entry"))]
717      ["Previous untranslated" po-previous-untranslated-entry
718       ,@(if (featurep 'xemacs) '(t)
719           '(:help "Jump to previous untranslated entry"))]
720      ["First file entry" po-first-entry
721       ,@(if (featurep 'xemacs) '(t)
722           '(:help "Jump to first entry"))]
723      "---"
724      "Position stack"
725      ["Mark and push current" po-push-location
726       ,@(if (featurep 'xemacs) '(t)
727           '(:help "Remember current location"))]
728      ["Pop and return" po-pop-location
729       ,@(if (featurep 'xemacs) '(t)
730           '(:help "Jump to last remembered location and forget about it"))]
731      ["Exchange current/top" po-exchange-location
732       ,@(if (featurep 'xemacs) '(t)
733           '(:help "Jump to last remembered location and remember current location"))]
734      "---"
735      ["Redisplay" po-current-entry
736       ,@(if (featurep 'xemacs) '(t)
737           '(:help "Make current entry properly visible"))]
738      ["Current index" po-statistics
739       ,@(if (featurep 'xemacs) '(t)
740           '(:help "Statistical info on current translation file"))])
741     ("Modifying entries"
742      ["Undo" po-undo
743       ,@(if (featurep 'xemacs) '(t)
744           '(:help "Revoke last changed entry"))]
745      "---"
746      "Msgstr"
747      ["Edit msgstr" po-edit-msgstr
748       ,@(if (featurep 'xemacs) '(t)
749           '(:help "Edit current translation"))]
750      ["Ediff and merge msgstr" po-edit-msgstr-and-ediff
751       ,@(if (featurep 'xemacs) '(t)
752           '(:help "Call `ediff' on current translation for merging"))]
753      ["Cut msgstr" po-kill-msgstr
754       ,@(if (featurep 'xemacs) '(t)
755           '(:help "Cut (kill) current translation"))]
756      ["Copy msgstr" po-kill-ring-save-msgstr
757       ,@(if (featurep 'xemacs) '(t)
758           '(:help "Copy current translation"))]
759      ["Paste msgstr" po-yank-msgstr
760       ,@(if (featurep 'xemacs) '(t)
761           '(:help "Paste (yank) text most recently cut/copied translation"))]
762      "---"
763      "Comments"
764      ["Edit comment" po-edit-comment
765       ,@(if (featurep 'xemacs) '(t)
766           '(:help "Edit current comment"))]
767      ["Ediff and merge comment" po-edit-comment-and-ediff
768       ,@(if (featurep 'xemacs) '(t)
769           '(:help "Call `ediff' on current comment for merging"))]
770      ["Cut comment" po-kill-comment
771       ,@(if (featurep 'xemacs) '(t)
772           '(:help "Cut (kill) current comment"))]
773      ["Copy comment" po-kill-ring-save-comment
774       ,@(if (featurep 'xemacs) '(t)
775           '(:help "Copy current translation"))]
776      ["Paste comment" po-yank-comment
777       ,@(if (featurep 'xemacs) '(t)
778           '(:help "Paste (yank) text most recently cut/copied"))]
779      "---"
780      ["Remove fuzzy mark" po-unfuzzy
781       ,@(if (featurep 'xemacs) '(t)
782           '(:help "Remove \"#, fuzzy\""))]
783      ["Fuzzy or fade out" po-fade-out-entry
784       ,@(if (featurep 'xemacs) '(t)
785           '(:help "Set current entry fuzzy, or if already fuzzy delete it"))]
786      ["Init with msgid" po-msgid-to-msgstr
787       ,@(if (featurep 'xemacs) '(t)
788           '(:help "\
789 Initialize or replace current translation with the original message"))])
790     ("Other files"
791      ["Other window" po-other-window
792       ,@(if (featurep 'xemacs) '(t)
793           '(:help "Select other window; if necessay split current frame"))]
794      "---"
795      "Program sources"
796      ["Cycle reference" po-cycle-source-reference t]
797      ["Select reference" po-select-source-reference t]
798      ["Consider path" po-consider-source-path t]
799      ["Ignore path" po-ignore-source-path t]
800      "---"
801      "Compendiums"
802      ["To compendium" po-save-entry nil]
803      ["Select, save" po-select-and-save-entry nil]
804      "---"
805      "Auxiliary files"
806      ["Cycle file" po-cycle-auxiliary t]
807      ["Select file" po-select-auxiliary t]
808      ["Consider file" po-consider-as-auxiliary t]
809      ["Ignore file" po-ignore-as-auxiliary t]
810      "---"
811      "Lexicography"
812      ["Lookup translation" po-lookup-lexicons nil]
813      ["Add/edit translation" po-edit-lexicon-entry nil]
814      ["Consider lexicon" po-consider-lexicon-file nil]
815      ["Ignore lexicon" po-ignore-lexicon-file nil])
816     "---"
817     "Source marking"
818     ["Find first string" (po-tags-search '(nil)) t]
819     ["Prefer keyword" (po-select-mark-and-mark '(nil)) t]
820     ["Find next string" po-tags-search t]
821     ["Mark preferred" po-mark-translatable t]
822     ["Mark with keyword" po-select-mark-and-mark t]
823     "---"
824     ["Version info" po-mode-version
825      ,@(if (featurep 'xemacs) '(t)
826           '(:help "Display version number of PO mode"))]
827     ["Help page" po-help
828      ,@(if (featurep 'xemacs) '(t)
829           '(:help "Show the PO mode help screen"))]
830     ["Validate" po-validate
831      ,@(if (featurep 'xemacs) '(t)
832           '(:help "Check validity of current translation file using `msgfmt'"))]
833     ["Mail officially" po-send-mail
834      ,@(if (featurep 'xemacs) '(t)
835           '(:help "Send current translation file to the Translation Robot by mail"))]
836     ["Edit out full" po-edit-out-full
837      ,@(if (featurep 'xemacs) '(t)
838           '(:help "Leave PO mode to edit translation file using fundamental mode"))]
839     "---"
840     ["Forceful quit" po-quit
841      ,@(if (featurep 'xemacs) '(t)
842           '(:help "Close (kill) current translation file without saving"))]
843     ["Soft quit" po-confirm-and-quit
844      ,@(if (featurep 'xemacs) '(t)
845           '(:help "Save current translation file, than close (kill) it"))])
846   "Menu layout for PO mode.")
847
848 (defconst po-subedit-mode-menu-layout
849   `("PO-Edit"
850     ["Ediff and merge translation variants" po-subedit-ediff
851       ,@(if (featurep 'xemacs) '(t)
852           '(:help "Call `ediff' for merging variants"))]
853     ["Cycle through auxiliary files" po-subedit-cycle-auxiliary t]
854     "---"
855     ["Abort edit" po-subedit-abort
856      ,@(if (featurep 'xemacs) '(t)
857           '(:help "Don't change the translation"))]
858     ["Exit edit" po-subedit-exit
859      ,@(if (featurep 'xemacs) '(t)
860          '(:help "Use this text as the translation and close current edit buffer"))])
861   "Menu layout for PO subedit mode.")
862
863 (defconst po-subedit-message
864   (_"Type 'C-c C-c' once done, or 'C-c C-k' to abort edit")
865   "Message to post in the minibuffer when an edit buffer is displayed.")
866
867 (defvar po-auxiliary-list nil
868   "List of auxiliary PO files, in completing read format.")
869
870 (defvar po-auxiliary-cursor nil
871   "Cursor into the 'po-auxiliary-list'.")
872
873 (defvar po-compose-mail-function
874   (let ((functions '(compose-mail-other-window
875                      message-mail-other-window
876                      compose-mail
877                      message-mail))
878         result)
879     (while (and (not result) functions)
880       (if (fboundp (car functions))
881           (setq result (car functions))
882         (setq functions (cdr functions))))
883     (cond (result)
884           ((fboundp 'mail-other-window)
885            (function (lambda (to subject)
886                        (mail-other-window nil to subject))))
887           ((fboundp 'mail)
888            (function (lambda (to subject)
889                        (mail nil to subject))))
890           (t (function (lambda (to subject)
891                          (error (_"I do not know how to mail to '%s'") to))))))
892   "Function to start composing an electronic message.")
893
894 (defvar po-any-msgid-regexp
895   "^\\(#~[ \t]*\\)?msgid.*\n\\(\\(#~[ \t]*\\)?\".*\n\\)*"
896   "Regexp matching a whole msgid field, whether obsolete or not.")
897
898 (defvar po-any-msgstr-regexp
899   ;; "^\\(#~[ \t]*\\)?msgstr.*\n\\(\\(#~[ \t]*\\)?\".*\n\\)*"
900   "^\\(#~[ \t]*\\)?msgstr\\(\\[[0-9]\\]\\)?.*\n\\(\\(#~[ \t]*\\)?\".*\n\\)*"
901   "Regexp matching a whole msgstr or msgstr[] field, whether obsolete or not.")
902
903 (defvar po-msgstr-idx-keyword-regexp
904   "^\\(#~[ \t]*\\)?msgstr\\[[0-9]\\]"
905   "Regexp matching an indexed msgstr keyword, whether obsolete or not.")
906
907 (defvar po-msgfmt-program "msgfmt"
908   "Path to msgfmt program from GNU gettext package.")
909
910 ;; Font lock based highlighting code.
911 (defconst po-font-lock-keywords
912   '(
913     ;; ("^\\(msgid \\|msgstr \\)?\"\\|\"$" . font-lock-keyword-face)
914     ;; (regexp-opt
915     ;;  '("msgid " "msgid_plural " "msgstr " "msgstr[0] " "msgstr[1] "))
916     ("\
917 ^\\(\\(msg\\(id\\(_plural\\)?\\|str\\(\\[[0-9]\\]\\)?\\)?\\) \\)?\"\\|\"$"
918      . font-lock-keyword-face)
919     ("\\\\.\\|%\\*?[-.0-9ul]*[a-zA-Z]" . font-lock-variable-name-face)
920     ("^# .*\\|^#[:,]?" . font-lock-comment-face)
921     ("^#:\\(.*\\)" 1 font-lock-reference-face)
922     ;; The following line does not work, and I wonder why.
923     ;;("^#,\\(.*\\)" 1 font-function-name-reference-face)
924     )
925   "Additional expressions to highlight in PO mode.")
926
927 ;; Old activator for 'font lock'.  Is it still useful?  I don't think so.
928 ;;(if (boundp 'font-lock-keywords)
929 ;;    (put 'po-mode 'font-lock-keywords 'po-font-lock-keywords))
930
931 ;; 'hilit19' based highlighting code has been disabled, as most probably
932 ;; nobody really needs it (it also generates ugly byte-compiler warnings).
933 ;;
934 ;;(if (fboundp 'hilit-set-mode-patterns)
935 ;;    (hilit-set-mode-patterns 'po-mode
936 ;;                           '(("^# .*\\|^#$" nil comment)
937 ;;                             ("^#[.,:].*" nil include)
938 ;;                             ("^\\(msgid\\|msgstr\\) *\"" nil keyword)
939 ;;                             ("^\"\\|\"$" nil keyword))))
940 \f
941 ;;; Mode activation.
942
943 ;; Emacs 21.2 comes with po-find-file-coding-system. We give preference
944 ;; to the version shipped with Emacs.
945 (if (not (fboundp 'po-find-file-coding-system))
946   (require 'po-compat))
947
948 (defvar po-mode-abbrev-table nil
949   "Abbrev table used while in PO mode.")
950 (define-abbrev-table 'po-mode-abbrev-table ())
951
952 (defvar po-mode-map
953   ;; Use (make-keymap) because (make-sparse-keymap) does not work on Demacs.
954   (let ((po-mode-map (make-keymap)))
955     (suppress-keymap po-mode-map)
956     (define-key po-mode-map "\C-i" 'po-unfuzzy)
957     (define-key po-mode-map "\C-j" 'po-msgid-to-msgstr)
958     (define-key po-mode-map "\C-m" 'po-edit-msgstr)
959     (define-key po-mode-map " " 'po-auto-select-entry)
960     (define-key po-mode-map "?" 'po-help)
961     (define-key po-mode-map "#" 'po-edit-comment)
962     (define-key po-mode-map "," 'po-tags-search)
963     (define-key po-mode-map "." 'po-current-entry)
964     (define-key po-mode-map "<" 'po-first-entry)
965     (define-key po-mode-map "=" 'po-statistics)
966     (define-key po-mode-map ">" 'po-last-entry)
967     (define-key po-mode-map "a" 'po-cycle-auxiliary)
968 ;;;;  (define-key po-mode-map "c" 'po-save-entry)
969     (define-key po-mode-map "f" 'po-next-fuzzy-entry)
970     (define-key po-mode-map "h" 'po-help)
971     (define-key po-mode-map "k" 'po-kill-msgstr)
972 ;;;;  (define-key po-mode-map "l" 'po-lookup-lexicons)
973     (define-key po-mode-map "m" 'po-push-location)
974     (define-key po-mode-map "n" 'po-next-entry)
975     (define-key po-mode-map "o" 'po-next-obsolete-entry)
976     (define-key po-mode-map "p" 'po-previous-entry)
977     (define-key po-mode-map "q" 'po-confirm-and-quit)
978     (define-key po-mode-map "r" 'po-pop-location)
979     (define-key po-mode-map "s" 'po-cycle-source-reference)
980     (define-key po-mode-map "t" 'po-next-translated-entry)
981     (define-key po-mode-map "u" 'po-next-untranslated-entry)
982     (define-key po-mode-map "v" 'po-mode-version)
983     (define-key po-mode-map "w" 'po-kill-ring-save-msgstr)
984     (define-key po-mode-map "x" 'po-exchange-location)
985     (define-key po-mode-map "y" 'po-yank-msgstr)
986     (define-key po-mode-map "A" 'po-consider-as-auxiliary)
987     (define-key po-mode-map "E" 'po-edit-out-full)
988     (define-key po-mode-map "F" 'po-previous-fuzzy-entry)
989     (define-key po-mode-map "K" 'po-kill-comment)
990 ;;;;  (define-key po-mode-map "L" 'po-consider-lexicon-file)
991     (define-key po-mode-map "M" 'po-send-mail)
992     (define-key po-mode-map "O" 'po-previous-obsolete-entry)
993     (define-key po-mode-map "T" 'po-previous-translated-entry)
994     (define-key po-mode-map "U" 'po-previous-untranslated-entry)
995     (define-key po-mode-map "Q" 'po-quit)
996     (define-key po-mode-map "S" 'po-consider-source-path)
997     (define-key po-mode-map "V" 'po-validate)
998     (define-key po-mode-map "W" 'po-kill-ring-save-comment)
999     (define-key po-mode-map "Y" 'po-yank-comment)
1000     (define-key po-mode-map "_" 'po-undo)
1001     (define-key po-mode-map "0" 'po-other-window)
1002     (define-key po-mode-map "\177" 'po-fade-out-entry)
1003     (define-key po-mode-map "\C-c\C-a" 'po-select-auxiliary)
1004     (define-key po-mode-map "\C-c\C-e" 'po-edit-msgstr-and-ediff)
1005     (define-key po-mode-map [(control c) (control \#)]
1006       'po-edit-comment-and-ediff)
1007     (define-key po-mode-map "\C-c\C-C" 'po-edit-comment-and-ediff)
1008     (define-key po-mode-map "\M-," 'po-mark-translatable)
1009     (define-key po-mode-map "\M-." 'po-select-mark-and-mark)
1010 ;;;;  (define-key po-mode-map "\M-c" 'po-select-and-save-entry)
1011 ;;;;  (define-key po-mode-map "\M-l" 'po-edit-lexicon-entry)
1012     (define-key po-mode-map "\M-s" 'po-select-source-reference)
1013     (define-key po-mode-map "\M-A" 'po-ignore-as-auxiliary)
1014 ;;;;  (define-key po-mode-map "\M-L" 'po-ignore-lexicon-file)
1015     (define-key po-mode-map "\M-S" 'po-ignore-source-path)
1016     po-mode-map)
1017   "Keymap for PO mode.")
1018
1019 ;; XEmacs note: this should really be autoloaded, but is currently not due
1020 ;; to reportedly intrusive keybindings (not autoloaded upstream either as of
1021 ;; gettext 0.13.1).  See also end of file for auto-mode-alist comments.
1022 (defun po-mode ()
1023   "Major mode for translators when they edit PO files.
1024
1025 Special commands:
1026 \\{po-mode-map}
1027 Turning on PO mode calls the value of the variable 'po-mode-hook',
1028 if that value is non-nil.  Behaviour may be adjusted through some variables,
1029 all reachable through 'M-x customize', in group 'Emacs.Editing.I18n.Po'."
1030   (interactive)
1031   (kill-all-local-variables)
1032   (setq major-mode 'po-mode
1033         mode-name "PO")
1034   (use-local-map po-mode-map)
1035   (if (fboundp 'easy-menu-define)
1036       (progn
1037         (easy-menu-define po-mode-menu po-mode-map "" po-mode-menu-layout)
1038         (and po-XEMACS (easy-menu-add po-mode-menu))))
1039   (set (make-local-variable 'font-lock-defaults) '(po-font-lock-keywords t))
1040
1041   (set (make-local-variable 'po-read-only) buffer-read-only)
1042   (setq buffer-read-only t)
1043
1044   (make-local-variable 'po-start-of-entry)
1045   (make-local-variable 'po-start-of-msgid)
1046   (make-local-variable 'po-start-of-msgstr)
1047   (make-local-variable 'po-end-of-entry)
1048   (make-local-variable 'po-entry-type)
1049
1050   (make-local-variable 'po-translated-counter)
1051   (make-local-variable 'po-fuzzy-counter)
1052   (make-local-variable 'po-untranslated-counter)
1053   (make-local-variable 'po-obsolete-counter)
1054   (make-local-variable 'po-mode-line-string)
1055
1056   (setq po-mode-flag t)
1057
1058   (po-check-file-header)
1059   (po-compute-counters nil)
1060
1061   (set (make-local-variable 'po-edited-fields) nil)
1062   (set (make-local-variable 'po-marker-stack) nil)
1063   (set (make-local-variable 'po-search-path) '(("./") ("../")))
1064
1065   (set (make-local-variable 'po-reference-alist) nil)
1066   (set (make-local-variable 'po-reference-cursor) nil)
1067   (set (make-local-variable 'po-reference-check) 0)
1068
1069   (set (make-local-variable 'po-keywords)
1070        '(("gettext") ("gettext_noop") ("_") ("N_")))
1071   (set (make-local-variable 'po-string-contents) nil)
1072   (set (make-local-variable 'po-string-buffer) nil)
1073   (set (make-local-variable 'po-string-start) nil)
1074   (set (make-local-variable 'po-string-end) nil)
1075   (set (make-local-variable 'po-marking-overlay) (po-create-overlay))
1076
1077   (add-hook 'write-contents-hooks 'po-replace-revision-date)
1078
1079   (run-hooks 'po-mode-hook)
1080   (message (_"You may type 'h' or '?' for a short PO mode reminder.")))
1081
1082 (defvar po-subedit-mode-map
1083   ;; Use (make-keymap) because (make-sparse-keymap) does not work on Demacs.
1084   (let ((po-subedit-mode-map (make-keymap)))
1085     (define-key po-subedit-mode-map "\C-c\C-a" 'po-subedit-cycle-auxiliary)
1086     (define-key po-subedit-mode-map "\C-c\C-c" 'po-subedit-exit)
1087     (define-key po-subedit-mode-map "\C-c\C-e" 'po-subedit-ediff)
1088     (define-key po-subedit-mode-map "\C-c\C-k" 'po-subedit-abort)
1089     po-subedit-mode-map)
1090   "Keymap while editing a PO mode entry (or the full PO file).")
1091 \f
1092 ;;; Window management.
1093
1094 (make-variable-buffer-local 'po-mode-flag)
1095
1096 (defvar po-mode-line-entry '(po-mode-flag ("  " po-mode-line-string))
1097   "Mode line format entry displaying MODE-LINE-STRING.")
1098
1099 ;; Insert MODE-LINE-ENTRY in mode line, but on first load only.
1100 (or (member po-mode-line-entry mode-line-format)
1101     ;; mode-line-format usually contains global-mode-string, but some
1102     ;; people customize this variable. As a last resort, append at the end.
1103     (let ((prev-entry (or (member 'global-mode-string mode-line-format)
1104                           (member "   " mode-line-format)
1105                           (last mode-line-format))))
1106       (setcdr prev-entry (cons po-mode-line-entry (cdr prev-entry)))))
1107
1108 (defun po-update-mode-line-string ()
1109   "Compute a new statistics string to display in mode line."
1110   (setq po-mode-line-string
1111         (concat (format "%dt" po-translated-counter)
1112                 (if (> po-fuzzy-counter 0)
1113                     (format "+%df" po-fuzzy-counter))
1114                 (if (> po-untranslated-counter 0)
1115                     (format "+%du" po-untranslated-counter))
1116                 (if (> po-obsolete-counter 0)
1117                     (format "+%do" po-obsolete-counter))))
1118   (po-force-mode-line-update))
1119
1120 (defun po-type-counter ()
1121   "Return the symbol name of the counter appropriate for the current entry."
1122   (cond ((eq po-entry-type 'obsolete) 'po-obsolete-counter)
1123         ((eq po-entry-type 'fuzzy) 'po-fuzzy-counter)
1124         ((eq po-entry-type 'translated) 'po-translated-counter)
1125         ((eq po-entry-type 'untranslated) 'po-untranslated-counter)
1126         (t (error (_"Unknown entry type")))))
1127
1128 (defun po-decrease-type-counter ()
1129   "Decrease the counter corresponding to the nature of the current entry."
1130   (let ((counter (po-type-counter)))
1131     (set counter (1- (eval counter)))))
1132
1133 (defun po-increase-type-counter ()
1134   "Increase the counter corresponding to the nature of the current entry.
1135 Then, update the mode line counters."
1136   (let ((counter (po-type-counter)))
1137     (set counter (1+ (eval counter))))
1138   (po-update-mode-line-string))
1139
1140 ;; Avoid byte compiler warnings.
1141 (defvar po-fuzzy-regexp)
1142 (defvar po-untranslated-regexp)
1143
1144 (defun po-compute-counters (flag)
1145   "Prepare counters for mode line display.  If FLAG, also echo entry position."
1146   (and flag (po-find-span-of-entry))
1147   (setq po-translated-counter 0
1148         po-fuzzy-counter 0
1149         po-untranslated-counter 0
1150         po-obsolete-counter 0)
1151   (let ((position 0) (total 0) current here)
1152     ;; FIXME 'here' looks obsolete / 2001-08-23 03:54:26 CEST -ke-
1153     (save-excursion
1154       (po-find-span-of-entry)
1155       (setq current po-start-of-msgstr)
1156       (goto-char (point-min))
1157       ;; While counting, skip the header entry, for consistency with msgfmt.
1158       (po-find-span-of-entry)
1159       (if (string-equal (po-get-msgid nil) "")
1160           (goto-char po-end-of-entry))
1161       (if (re-search-forward "^msgid" (point-max) t)
1162           (progn
1163             ;; Start counting
1164             (while (re-search-forward po-any-msgstr-regexp nil t)
1165               (and (= (% total 20) 0)
1166                    (if flag
1167                        (message (_"Position %d/%d") position total)
1168                      (message (_"Position %d") total)))
1169               (setq here (point))
1170               (goto-char (match-beginning 0))
1171               (setq total (1+ total))
1172               (and flag (eq (point) current) (setq position total))
1173               (cond ((eq (following-char) ?#)
1174                      (setq po-obsolete-counter (1+ po-obsolete-counter)))
1175                     ((looking-at po-untranslated-regexp)
1176                      (setq po-untranslated-counter (1+ po-untranslated-counter)))
1177                     (t (setq po-translated-counter (1+ po-translated-counter))))
1178               (goto-char here))
1179
1180             ;; Make another pass just for the fuzzy entries, kind of kludgey.
1181             ;; FIXME: Counts will be wrong if untranslated entries are fuzzy, yet
1182             ;; this should not normally happen.
1183             (goto-char (point-min))
1184             (while (re-search-forward po-fuzzy-regexp nil t)
1185               (setq po-fuzzy-counter (1+ po-fuzzy-counter)))
1186             (setq po-translated-counter (- po-translated-counter po-fuzzy-counter)))
1187         '()))
1188
1189     ;; Push the results out.
1190     (if flag
1191         (message (_"\
1192 Position %d/%d; %d translated, %d fuzzy, %d untranslated, %d obsolete")
1193                  position total po-translated-counter po-fuzzy-counter
1194                  po-untranslated-counter po-obsolete-counter)
1195       (message "")))
1196   (po-update-mode-line-string))
1197
1198 (defun po-redisplay ()
1199   "Redisplay the current entry."
1200   ;; FIXME: Should try to fit the whole entry on the window.  If this is not
1201   ;; possible, should try to fit the comment and the msgid.  Otherwise,
1202   ;; should try to fit the msgid.  Else, the first line of the msgid should
1203   ;; be at the top of the window.
1204   (goto-char po-start-of-msgid))
1205
1206 (defun po-other-window ()
1207   "Get the cursor into another window, out of PO mode."
1208   (interactive)
1209   (if (one-window-p t)
1210       (progn
1211         (split-window)
1212         (switch-to-buffer (other-buffer)))
1213     (other-window 1)))
1214 \f
1215 ;;; Processing the PO file header entry.
1216
1217 (defun po-check-file-header ()
1218   "Create a missing PO mode file header, or replace an oldish one."
1219   (save-excursion
1220     (let ((buffer-read-only po-read-only)
1221           insert-flag end-of-header)
1222       (goto-char (point-min))
1223       (if (re-search-forward po-any-msgstr-regexp nil t)
1224           (progn
1225             ;; There is at least one entry.
1226             (goto-char (match-beginning 0))
1227             (previous-line 1)
1228             (setq end-of-header (match-end 0))
1229             (if (looking-at "msgid \"\"\n")
1230                 ;; There is indeed a PO file header.
1231                 (if (re-search-forward "\n\"PO-Revision-Date: "
1232                                        end-of-header t)
1233                     nil
1234                   ;; This is an oldish header.  Replace it all.
1235                   (goto-char end-of-header)
1236                   (while (> (point) (point-min))
1237                     (previous-line 1)
1238                     (insert "#~ ")
1239                     (beginning-of-line))
1240                   (beginning-of-line)
1241                   (setq insert-flag t))
1242               ;; The first entry is not a PO file header, insert one.
1243               (setq insert-flag t)))
1244         ;; Not a single entry found.
1245         (setq insert-flag t))
1246       (goto-char (point-min))
1247       (if insert-flag
1248           (progn
1249             (insert po-default-file-header)
1250             (if (not (eobp))
1251                 (insert "\n")))))))
1252
1253 (defun po-replace-revision-date ()
1254   "Replace the revision date by current time in the PO file header."
1255   (if (fboundp 'format-time-string)
1256       (if (or (eq po-auto-replace-revision-date t)
1257               (and (eq po-auto-replace-revision-date 'ask)
1258                    (y-or-n-p (_"May I set PO-Revision-Date? "))))
1259           (save-excursion
1260             (goto-char (point-min))
1261             (if (re-search-forward "^\"PO-Revision-Date:.*" nil t)
1262                 (let* ((buffer-read-only po-read-only)
1263                        (time (current-time))
1264                        (seconds (or (car (current-time-zone time)) 0))
1265                        (minutes (/ (abs seconds) 60))
1266                        (zone (format "%c%02d%02d"
1267                                      (if (< seconds 0) ?- ?+)
1268                                      (/ minutes 60)
1269                                      (% minutes 60))))
1270                   (replace-match
1271                        (concat "\"PO-Revision-Date: "
1272                                (format-time-string "%Y-%m-%d %H:%M" time)
1273                                zone "\\n\"")
1274                        t t))))
1275         (message ""))
1276     (message (_"PO-Revision-Date should be adjusted..."))))
1277 \f
1278 ;;; Handling span of entry, entry type and entry attributes.
1279
1280 (defun po-find-span-of-entry ()
1281   "Find the extent of the PO file entry where the cursor is.
1282 Set variables PO-START-OF-ENTRY, PO-START-OF-MSGID, PO-START-OF-MSGSTR,
1283 PO-END-OF-ENTRY and PO-ENTRY-TYPE to meaningful values.  Decreasing priority
1284 of type interpretation is: obsolete, fuzzy, untranslated or translated."
1285   (let ((here (point)))
1286     (if (re-search-backward po-any-msgstr-regexp nil t)
1287         (progn
1288           ;; After a backward match, (match-end 0) will not extend
1289           ;; beyond point, in case point was *inside* the regexp.  We
1290           ;; need a dependable (match-end 0), so we redo the match in
1291           ;; the forward direction.
1292           (re-search-forward po-any-msgstr-regexp)
1293           (if (<= (match-end 0) here)
1294               (progn
1295                 ;; We most probably found the msgstr of the previous
1296                 ;; entry.  The current entry then starts just after
1297                 ;; its end, save this information just in case.
1298                 (setq po-start-of-entry (match-end 0))
1299                 ;; However, it is also possible that we are located in
1300                 ;; the crumb after the last entry in the file.  If
1301                 ;; yes, we know the middle and end of last PO entry.
1302                 (setq po-start-of-msgstr (match-beginning 0)
1303                       po-end-of-entry (match-end 0))
1304                 (if (re-search-forward po-any-msgstr-regexp nil t)
1305                     (progn
1306                       ;; We definitely were not in the crumb.
1307                       (setq po-start-of-msgstr (match-beginning 0)
1308                             po-end-of-entry (match-end 0)))
1309                   ;; We were in the crumb.  The start of the last PO
1310                   ;; file entry is the end of the previous msgstr if
1311                   ;; any, or else, the beginning of the file.
1312                   (goto-char po-start-of-msgstr)
1313                   (setq po-start-of-entry
1314                         (if (re-search-backward po-any-msgstr-regexp nil t)
1315                             (match-end 0)
1316                           (point-min)))))
1317             ;; The cursor was inside msgstr of the current entry.
1318             (setq po-start-of-msgstr (match-beginning 0)
1319                   po-end-of-entry (match-end 0))
1320             ;; The start of this entry is the end of the previous
1321             ;; msgstr if any, or else, the beginning of the file.
1322             (goto-char po-start-of-msgstr)
1323             (setq po-start-of-entry
1324                   (if (re-search-backward po-any-msgstr-regexp nil t)
1325                       (match-end 0)
1326                     (point-min)))))
1327       ;; The cursor was before msgstr in the first entry in the file.
1328       (setq po-start-of-entry (point-min))
1329       (goto-char po-start-of-entry)
1330       ;; There is at least the PO file header, so this should match.
1331       (re-search-forward po-any-msgstr-regexp)
1332       (setq po-start-of-msgstr (match-beginning 0)
1333             po-end-of-entry (match-end 0)))
1334     ;; Find start of msgid.
1335     (goto-char po-start-of-entry)
1336     (re-search-forward po-any-msgid-regexp)
1337     (setq po-start-of-msgid (match-beginning 0))
1338     ;; Classify the entry.
1339     (setq po-entry-type
1340           (if (eq (following-char) ?#)
1341               'obsolete
1342             (goto-char po-start-of-entry)
1343             (if (re-search-forward po-fuzzy-regexp po-start-of-msgid t)
1344                 'fuzzy
1345               (goto-char po-start-of-msgstr)
1346               (if (looking-at po-untranslated-regexp)
1347                   'untranslated
1348                 'translated))))
1349     ;; Put the cursor back where it was.
1350     (goto-char here)))
1351
1352 (defun po-add-attribute (name)
1353   "Add attribute NAME to the current entry, unless it is already there."
1354   (save-excursion
1355     (let ((buffer-read-only po-read-only))
1356       (goto-char po-start-of-entry)
1357       (if (re-search-forward "\n#[,!] .*" po-start-of-msgid t)
1358           (save-restriction
1359             (narrow-to-region (match-beginning 0) (match-end 0))
1360             (goto-char (point-min))
1361             (if (re-search-forward (concat "\\b" name "\\b") nil t)
1362                 nil
1363               (goto-char (point-max))
1364               (insert ", " name)))
1365         (skip-chars-forward "\n")
1366         (while (eq (following-char) ?#)
1367           (next-line 1))
1368         (insert "#, " name "\n")))))
1369
1370 (defun po-delete-attribute (name)
1371   "Delete attribute NAME from the current entry, if any."
1372   (save-excursion
1373     (let ((buffer-read-only po-read-only))
1374       (goto-char po-start-of-entry)
1375       (if (re-search-forward "\n#[,!] .*" po-start-of-msgid t)
1376           (save-restriction
1377             (narrow-to-region (match-beginning 0) (match-end 0))
1378             (goto-char (point-min))
1379             (if (re-search-forward
1380                  (concat "\\(\n#[,!] " name "$\\|, " name "$\\| " name ",\\)")
1381                  nil t)
1382                 (replace-match "" t t)))))))
1383 \f
1384 ;;; Entry positionning.
1385
1386 (defun po-say-location-depth ()
1387   "Tell how many entries in the entry location stack."
1388   (let ((depth (length po-marker-stack)))
1389     (cond ((= depth 0) (message (_"Empty location stack")))
1390           ((= depth 1) (message (_"One entry in location stack")))
1391           (t (message (_"%d entries in location stack") depth)))))
1392
1393 (defun po-push-location ()
1394   "Stack the location of the current entry, for later return."
1395   (interactive)
1396   (po-find-span-of-entry)
1397   (save-excursion
1398     (goto-char po-start-of-msgid)
1399     (setq po-marker-stack (cons (point-marker) po-marker-stack)))
1400   (po-say-location-depth))
1401
1402 (defun po-pop-location ()
1403   "Unstack a saved location, and return to the corresponding entry."
1404   (interactive)
1405   (if po-marker-stack
1406       (progn
1407         (goto-char (car po-marker-stack))
1408         (setq po-marker-stack (cdr po-marker-stack))
1409         (po-current-entry)
1410         (po-say-location-depth))
1411     (error (_"The entry location stack is empty"))))
1412
1413 (defun po-exchange-location ()
1414   "Exchange the location of the current entry with the top of stack."
1415   (interactive)
1416   (if po-marker-stack
1417       (progn
1418         (po-find-span-of-entry)
1419         (goto-char po-start-of-msgid)
1420         (let ((location (point-marker)))
1421           (goto-char (car po-marker-stack))
1422           (setq po-marker-stack (cons location (cdr po-marker-stack))))
1423         (po-current-entry)
1424         (po-say-location-depth))
1425     (error (_"The entry location stack is empty"))))
1426
1427 (defun po-current-entry ()
1428   "Display the current entry."
1429   (interactive)
1430   (po-find-span-of-entry)
1431   (po-redisplay))
1432
1433 (defun po-first-entry-with-regexp (regexp)
1434   "Display the first entry in the file which msgstr matches REGEXP."
1435   (let ((here (point)))
1436     (goto-char (point-min))
1437     (if (re-search-forward regexp nil t)
1438         (progn
1439           (goto-char (match-beginning 0))
1440           (po-current-entry))
1441       (goto-char here)
1442       (error (_"There is no such entry")))))
1443
1444 (defun po-last-entry-with-regexp (regexp)
1445   "Display the last entry in the file which msgstr matches REGEXP."
1446   (let ((here (point)))
1447     (goto-char (point-max))
1448     (if (re-search-backward regexp nil t)
1449         (po-current-entry)
1450       (goto-char here)
1451       (error (_"There is no such entry")))))
1452
1453 (defun po-next-entry-with-regexp (regexp wrap)
1454   "Display the entry following the current entry which msgstr matches REGEXP.
1455 If WRAP is not nil, the search may wrap around the buffer."
1456   (po-find-span-of-entry)
1457   (let ((here (point)))
1458     (goto-char po-end-of-entry)
1459     (if (re-search-forward regexp nil t)
1460         (progn
1461           (goto-char (match-beginning 0))
1462           (po-current-entry))
1463       (if (and wrap
1464                (progn
1465                  (goto-char (point-min))
1466                  (re-search-forward regexp po-start-of-entry t)))
1467           (progn
1468             (goto-char (match-beginning 0))
1469             (po-current-entry)
1470             (message (_"Wrapping around the buffer")))
1471         (goto-char here)
1472         (error (_"There is no such entry"))))))
1473
1474 (defun po-previous-entry-with-regexp (regexp wrap)
1475   "Redisplay the entry preceding the current entry which msgstr matches REGEXP.
1476 If WRAP is not nil, the search may wrap around the buffer."
1477   (po-find-span-of-entry)
1478   (let ((here (point)))
1479     (goto-char po-start-of-entry)
1480     (if (re-search-backward regexp nil t)
1481         (po-current-entry)
1482       (if (and wrap
1483                (progn
1484                  (goto-char (point-max))
1485                  (re-search-backward regexp po-end-of-entry t)))
1486           (progn
1487             (po-current-entry)
1488             (message (_"Wrapping around the buffer")))
1489         (goto-char here)
1490         (error (_"There is no such entry"))))))
1491
1492 ;; Any entries.
1493
1494 (defun po-first-entry ()
1495   "Display the first entry."
1496   (interactive)
1497   (po-first-entry-with-regexp po-any-msgstr-regexp))
1498
1499 (defun po-last-entry ()
1500   "Display the last entry."
1501   (interactive)
1502   (po-last-entry-with-regexp po-any-msgstr-regexp))
1503
1504 (defun po-next-entry ()
1505   "Display the entry following the current entry."
1506   (interactive)
1507   (po-next-entry-with-regexp po-any-msgstr-regexp nil))
1508
1509 (defun po-previous-entry ()
1510   "Display the entry preceding the current entry."
1511   (interactive)
1512   (po-previous-entry-with-regexp po-any-msgstr-regexp nil))
1513
1514 ;; Untranslated entries.
1515
1516 (defvar po-after-entry-regexp
1517   "\\(\\'\\|\\(#[ \t]*\\)?$\\)"
1518   "Regexp which should be true after a full msgstr string matched.")
1519
1520 (defvar po-untranslated-regexp
1521   (concat "^msgstr[ \t]*\"\"\n" po-after-entry-regexp)
1522   "Regexp matching a whole msgstr field, but only if active and empty.")
1523
1524 (defun po-next-untranslated-entry ()
1525   "Find the next untranslated entry, wrapping around if necessary."
1526   (interactive)
1527   (po-next-entry-with-regexp po-untranslated-regexp t))
1528
1529 (defun po-previous-untranslated-entry ()
1530   "Find the previous untranslated entry, wrapping around if necessary."
1531   (interactive)
1532   (po-previous-entry-with-regexp po-untranslated-regexp t))
1533
1534 (defun po-msgid-to-msgstr ()
1535   "Use another window to edit msgstr reinitialized with msgid."
1536   (interactive)
1537   (po-find-span-of-entry)
1538   (if (or (eq po-entry-type 'untranslated)
1539           (eq po-entry-type 'obsolete)
1540           (y-or-n-p (_"Really loose previous translation? ")))
1541       (po-set-msgstr (po-get-msgid nil)))
1542   (message ""))
1543
1544 ;; Obsolete entries.
1545
1546 (defvar po-obsolete-msgstr-regexp
1547   "^#~[ \t]*msgstr.*\n\\(#~[ \t]*\".*\n\\)*"
1548   "Regexp matching a whole msgstr field of an obsolete entry.")
1549
1550 (defun po-next-obsolete-entry ()
1551   "Find the next obsolete entry, wrapping around if necessary."
1552   (interactive)
1553   (po-next-entry-with-regexp po-obsolete-msgstr-regexp t))
1554
1555 (defun po-previous-obsolete-entry ()
1556   "Find the previous obsolete entry, wrapping around if necessary."
1557   (interactive)
1558   (po-previous-entry-with-regexp po-obsolete-msgstr-regexp t))
1559
1560 ;; Fuzzy entries.
1561
1562 (defvar po-fuzzy-regexp "^#[,!] .*fuzzy"
1563   "Regexp matching the string inserted by msgmerge for translations
1564 which does not match exactly.")
1565
1566 (defun po-next-fuzzy-entry ()
1567   "Find the next fuzzy entry, wrapping around if necessary."
1568   (interactive)
1569   (po-next-entry-with-regexp po-fuzzy-regexp t))
1570
1571 (defun po-previous-fuzzy-entry ()
1572   "Find the next fuzzy entry, wrapping around if necessary."
1573   (interactive)
1574   (po-previous-entry-with-regexp po-fuzzy-regexp t))
1575
1576 (defun po-unfuzzy ()
1577   "Remove the fuzzy attribute for the current entry."
1578   (interactive)
1579   (po-find-span-of-entry)
1580   (cond ((eq po-entry-type 'fuzzy)
1581          (po-decrease-type-counter)
1582          (po-delete-attribute "fuzzy")
1583          (po-current-entry)
1584          (po-increase-type-counter)))
1585   (if po-auto-select-on-unfuzzy
1586       (po-auto-select-entry))
1587   (po-update-mode-line-string))
1588
1589 ;; Translated entries.
1590
1591 (defun po-next-translated-entry ()
1592   "Find the next translated entry, wrapping around if necessary."
1593   (interactive)
1594   (if (= po-translated-counter 0)
1595       (error (_"There is no such entry"))
1596     (po-next-entry-with-regexp po-any-msgstr-regexp t)
1597     (po-find-span-of-entry)
1598     (while (not (eq po-entry-type 'translated))
1599       (po-next-entry-with-regexp po-any-msgstr-regexp t)
1600       (po-find-span-of-entry))))
1601
1602 (defun po-previous-translated-entry ()
1603   "Find the previous translated entry, wrapping around if necessary."
1604   (interactive)
1605   (if (= po-translated-counter 0)
1606       (error (_"There is no such entry"))
1607     (po-previous-entry-with-regexp po-any-msgstr-regexp t)
1608     (po-find-span-of-entry)
1609     (while (not (eq po-entry-type 'translated))
1610       (po-previous-entry-with-regexp po-untranslated-regexp t)
1611       (po-find-span-of-entry))))
1612
1613 ;; Auto-selection feature.
1614
1615 (defun po-auto-select-entry ()
1616   "Select the next entry having the same type as the current one.
1617 If none, wrap from the beginning of the buffer with another type,
1618 going from untranslated to fuzzy, and from fuzzy to obsolete.
1619 Plain translated entries are always disregarded unless there are
1620 no entries of the other types."
1621   (interactive)
1622   (po-find-span-of-entry)
1623   (goto-char po-end-of-entry)
1624   (if (and (= po-untranslated-counter 0)
1625            (= po-fuzzy-counter 0)
1626            (= po-obsolete-counter 0))
1627       ;; All entries are plain translated.  Next entry will do, or
1628       ;; wrap around if there is none.
1629       (if (re-search-forward po-any-msgstr-regexp nil t)
1630           (goto-char (match-beginning 0))
1631         (goto-char (point-min)))
1632     ;; If over a translated entry, look for an untranslated one first.
1633     ;; Else, look for an entry of the same type first.
1634     (let ((goal (if (eq po-entry-type 'translated)
1635                     'untranslated
1636                   po-entry-type)))
1637       (while goal
1638         ;; Find an untranslated entry, or wrap up for a fuzzy entry.
1639         (if (eq goal 'untranslated)
1640             (if (and (> po-untranslated-counter 0)
1641                      (re-search-forward po-untranslated-regexp nil t))
1642                 (progn
1643                   (goto-char (match-beginning 0))
1644                   (setq goal nil))
1645               (goto-char (point-min))
1646               (setq goal 'fuzzy)))
1647         ;; Find a fuzzy entry, or wrap up for an obsolete entry.
1648         (if (eq goal 'fuzzy)
1649             (if (and (> po-fuzzy-counter 0)
1650                      (re-search-forward po-fuzzy-regexp nil t))
1651                 (progn
1652                   (goto-char (match-beginning 0))
1653                   (setq goal nil))
1654               (goto-char (point-min))
1655               (setq goal 'obsolete)))
1656         ;; Find an obsolete entry, or wrap up for an untranslated entry.
1657         (if (eq goal 'obsolete)
1658             (if (and (> po-obsolete-counter 0)
1659                      (re-search-forward po-obsolete-msgstr-regexp nil t))
1660                 (progn
1661                   (goto-char (match-beginning 0))
1662                   (setq goal nil))
1663               (goto-char (point-min))
1664               (setq goal 'untranslated))))))
1665   ;; Display this entry nicely.
1666   (po-current-entry))
1667 \f
1668 ;;; Killing and yanking fields.
1669
1670 (defun po-extract-unquoted (buffer start end)
1671   "Extract and return the unquoted string in BUFFER going from START to END.
1672 Crumb preceding or following the quoted string is ignored."
1673   (save-excursion
1674     (goto-char start)
1675     (search-forward "\"")
1676     (setq start (point))
1677     (goto-char end)
1678     (search-backward "\"")
1679     (setq end (point)))
1680   (po-extract-part-unquoted buffer start end))
1681
1682 (defun po-extract-part-unquoted (buffer start end)
1683   "Extract and return the unquoted string in BUFFER going from START to END.
1684 Surrounding quotes are already excluded by the position of START and END."
1685   (po-with-temp-buffer
1686    (insert-buffer-substring buffer start end)
1687    ;; Glue concatenated strings.
1688    (goto-char (point-min))
1689    (while (re-search-forward "\"[ \t]*\\\\?\n\\(#~\\)?[ \t]*\"" nil t)
1690      (replace-match "" t t))
1691    ;; Remove escaped newlines.
1692    (goto-char (point-min))
1693    (while (re-search-forward "\\\\[ \t]*\n" nil t)
1694      (replace-match "" t t))
1695    ;; Unquote individual characters.
1696    (goto-char (point-min))
1697    (while (re-search-forward "\\\\[\"abfnt\\0-7]" nil t)
1698      (cond ((eq (preceding-char) ?\") (replace-match "\"" t t))
1699            ((eq (preceding-char) ?a) (replace-match "\a" t t))
1700            ((eq (preceding-char) ?b) (replace-match "\b" t t))
1701            ((eq (preceding-char) ?f) (replace-match "\f" t t))
1702            ((eq (preceding-char) ?n) (replace-match "\n" t t))
1703            ((eq (preceding-char) ?t) (replace-match "\t" t t))
1704            ((eq (preceding-char) ?\\) (replace-match "\\" t t))
1705            (t (let ((value (- (preceding-char) ?0)))
1706                 (replace-match "" t t)
1707                 (while (looking-at "[0-7]")
1708                   (setq value (+ (* 8 value) (- (following-char) ?0)))
1709                   (replace-match "" t t))
1710                 (insert value)))))
1711    (buffer-string)))
1712
1713 (defun po-eval-requoted (form prefix obsolete)
1714   "Eval FORM, which inserts a string, and return the string fully requoted.
1715 If PREFIX, precede the result with its contents.  If OBSOLETE, comment all
1716 generated lines in the returned string.  Evaluating FORM should insert the
1717 wanted string in the buffer which is current at the time of evaluation.
1718 If FORM is itself a string, then this string is used for insertion."
1719   (po-with-temp-buffer
1720     (if (stringp form)
1721         (insert form)
1722       (push-mark)
1723       (eval form))
1724     (goto-char (point-min))
1725     (let ((multi-line (re-search-forward "[^\n]\n+[^\n]" nil t)))
1726       (goto-char (point-min))
1727       (while (re-search-forward "[\"\a\b\f\n\r\t\\]" nil t)
1728         (cond ((eq (preceding-char) ?\") (replace-match "\\\"" t t))
1729               ((eq (preceding-char) ?\a) (replace-match "\\a" t t))
1730               ((eq (preceding-char) ?\b) (replace-match "\\b" t t))
1731               ((eq (preceding-char) ?\f) (replace-match "\\f" t t))
1732               ((eq (preceding-char) ?\n)
1733                (replace-match (if (or (not multi-line) (eobp))
1734                                   "\\n"
1735                                 "\\n\"\n\"")
1736                               t t))
1737               ((eq (preceding-char) ?\r) (replace-match "\\r" t t))
1738               ((eq (preceding-char) ?\t) (replace-match "\\t" t t))
1739               ((eq (preceding-char) ?\\) (replace-match "\\\\" t t))))
1740       (goto-char (point-min))
1741       (if prefix (insert prefix " "))
1742       (insert (if multi-line "\"\"\n\"" "\""))
1743       (goto-char (point-max))
1744       (insert "\"")
1745       (if prefix (insert "\n"))
1746       (if obsolete
1747           (progn
1748             (goto-char (point-min))
1749             (while (not (eobp))
1750               (or (eq (following-char) ?\n) (insert "#~ "))
1751               (search-forward "\n"))))
1752       (buffer-string))))
1753
1754 (defun po-get-msgid (kill)
1755   "Extract and return the unquoted msgid string.
1756 If KILL, then add the unquoted string to the kill ring."
1757   (let ((string (po-extract-unquoted (current-buffer)
1758                                      po-start-of-msgid po-start-of-msgstr)))
1759     (if kill (po-kill-new string))
1760     string))
1761
1762 (defun po-get-msgstr (kill)
1763   "Extract and return the unquoted msgstr string.
1764 If KILL, then add the unquoted string to the kill ring."
1765   (let ((string (po-extract-unquoted (current-buffer)
1766                                      po-start-of-msgstr po-end-of-entry)))
1767     (if kill (po-kill-new string))
1768     string))
1769
1770 (defun po-set-msgid (form)
1771   "Replace the current msgid, using FORM to get a string.
1772 Evaluating FORM should insert the wanted string in the current buffer.  If
1773 FORM is itself a string, then this string is used for insertion.  The string
1774 is properly requoted before the replacement occurs.
1775
1776 Returns 'nil' if the buffer has not been modified, for if the new msgid
1777 described by FORM is merely identical to the msgid already in place."
1778   (let ((string (po-eval-requoted form "msgid" (eq po-entry-type 'obsolete))))
1779     (save-excursion
1780       (goto-char po-start-of-entry)
1781       (re-search-forward po-any-msgid-regexp po-start-of-msgstr)
1782       (and (not (string-equal (po-match-string 0) string))
1783            (let ((buffer-read-only po-read-only))
1784              (replace-match string t t)
1785              (goto-char po-start-of-msgid)
1786              (po-find-span-of-entry)
1787              t)))))
1788
1789 (defun po-set-msgstr (form)
1790   "Replace the current msgstr or msgstr[], using FORM to get a string.
1791 Evaluating FORM should insert the wanted string in the current buffer.  If
1792 FORM is itself a string, then this string is used for insertion.  The string
1793 is properly requoted before the replacement occurs.
1794
1795 Returns 'nil' if the buffer has not been modified, for if the new msgstr
1796 described by FORM is merely identical to the msgstr already in place."
1797   (let ((string (po-eval-requoted form "msgstr" (eq po-entry-type 'obsolete)))
1798         (msgstr-idx nil))
1799     (save-excursion
1800       (goto-char po-start-of-entry)
1801       (save-excursion                   ; check for an indexed msgstr
1802         (if (re-search-forward po-msgstr-idx-keyword-regexp
1803                                po-end-of-entry t)
1804             (setq msgstr-idx (buffer-substring-no-properties
1805                               (match-beginning 0) (match-end 0)))))
1806       (re-search-forward po-any-msgstr-regexp po-end-of-entry)
1807       (and (not (string-equal (po-match-string 0) string))
1808            (let ((buffer-read-only po-read-only))
1809              (po-decrease-type-counter)
1810              (replace-match string t t)
1811              (goto-char (match-beginning 0))
1812              (if (eq msgstr-idx nil) ; hack: replace msgstr with msgstr[d]
1813                  nil
1814                (insert msgstr-idx)
1815                (looking-at "\\(#~[ \t]*\\)?msgstr")
1816                (replace-match ""))
1817              (goto-char po-start-of-msgid)
1818              (po-find-span-of-entry)
1819              (po-increase-type-counter)
1820              t)))))
1821
1822 (defun po-kill-ring-save-msgstr ()
1823   "Push the msgstr string from current entry on the kill ring."
1824   (interactive)
1825   (po-find-span-of-entry)
1826   (po-get-msgstr t))
1827
1828 (defun po-kill-msgstr ()
1829   "Empty the msgstr string from current entry, pushing it on the kill ring."
1830   (interactive)
1831   (po-kill-ring-save-msgstr)
1832   (po-set-msgstr ""))
1833
1834 (defun po-yank-msgstr ()
1835   "Replace the current msgstr string by the top of the kill ring."
1836   (interactive)
1837   (po-find-span-of-entry)
1838   (po-set-msgstr (if (eq last-command 'yank) '(yank-pop 1) '(yank)))
1839   (setq this-command 'yank))
1840
1841 (defun po-fade-out-entry ()
1842   "Mark an active entry as fuzzy; obsolete a fuzzy or untranslated entry;
1843 or completely delete an obsolete entry, saving its msgstr on the kill ring."
1844   (interactive)
1845   (po-find-span-of-entry)
1846
1847   (cond ((eq po-entry-type 'translated)
1848          (po-decrease-type-counter)
1849          (po-add-attribute "fuzzy")
1850          (po-current-entry)
1851          (po-increase-type-counter))
1852
1853         ((or (eq po-entry-type 'fuzzy)
1854              (eq po-entry-type 'untranslated))
1855          (if (y-or-n-p (_"Should I really obsolete this entry? "))
1856              (progn
1857                (po-decrease-type-counter)
1858                (save-excursion
1859                  (save-restriction
1860                    (narrow-to-region po-start-of-entry po-end-of-entry)
1861                    (let ((buffer-read-only po-read-only))
1862                      (goto-char (point-min))
1863                      (skip-chars-forward "\n")
1864                      (while (not (eobp))
1865                        (insert "#~ ")
1866                        (search-forward "\n")))))
1867                (po-current-entry)
1868                (po-increase-type-counter)))
1869          (message ""))
1870
1871         ((and (eq po-entry-type 'obsolete)
1872               (po-check-for-pending-edit po-start-of-msgid)
1873               (po-check-for-pending-edit po-start-of-msgstr))
1874          (po-decrease-type-counter)
1875          (po-update-mode-line-string)
1876          (po-get-msgstr t)
1877          (let ((buffer-read-only po-read-only))
1878            (delete-region po-start-of-entry po-end-of-entry))
1879          (goto-char po-start-of-entry)
1880          (if (re-search-forward po-any-msgstr-regexp nil t)
1881              (goto-char (match-beginning 0))
1882            (re-search-backward po-any-msgstr-regexp nil t))
1883          (po-current-entry)
1884          (message ""))))
1885 \f
1886 ;;; Killing and yanking comments.
1887
1888 (defvar po-active-comment-regexp
1889   "^\\(#\n\\|# .*\n\\)+"
1890   "Regexp matching the whole editable comment part of an active entry.")
1891
1892 (defvar po-obsolete-comment-regexp
1893   "^\\(#~ #\n\\|#~ # .*\n\\)+"
1894   "Regexp matching the whole editable comment part of an obsolete entry.")
1895
1896 (defun po-get-comment (kill-flag)
1897   "Extract and return the editable comment string, uncommented.
1898 If KILL-FLAG, then add the unquoted comment to the kill ring."
1899   (let ((buffer (current-buffer))
1900         (obsolete (eq po-entry-type 'obsolete)))
1901     (save-excursion
1902       (goto-char po-start-of-entry)
1903       (if (re-search-forward (if obsolete po-obsolete-comment-regexp
1904                                  po-active-comment-regexp)
1905                              po-end-of-entry t)
1906           (po-with-temp-buffer
1907             (insert-buffer-substring buffer (match-beginning 0) (match-end 0))
1908             (goto-char (point-min))
1909             (while (not (eobp))
1910               (if (looking-at (if obsolete "#~ # ?" "# ?"))
1911                   (replace-match "" t t))
1912               (forward-line 1))
1913             (and kill-flag (copy-region-as-kill (point-min) (point-max)))
1914             (buffer-string))
1915         ""))))
1916
1917 (defun po-set-comment (form)
1918   "Using FORM to get a string, replace the current editable comment.
1919 Evaluating FORM should insert the wanted string in the current buffer.
1920 If FORM is itself a string, then this string is used for insertion.
1921 The string is properly recommented before the replacement occurs."
1922   (let ((obsolete (eq po-entry-type 'obsolete))
1923         string)
1924     (po-with-temp-buffer
1925       (if (stringp form)
1926           (insert form)
1927         (push-mark)
1928         (eval form))
1929       (if (not (or (bobp) (= (preceding-char) ?\n)))
1930           (insert "\n"))
1931       (goto-char (point-min))
1932       (while (not (eobp))
1933         (insert (if (= (following-char) ?\n)
1934                     (if obsolete "#~ #" "#")
1935                   (if obsolete "#~ # " "# ")))
1936         (search-forward "\n"))
1937       (setq string (buffer-string)))
1938     (goto-char po-start-of-entry)
1939     (if (re-search-forward
1940          (if obsolete po-obsolete-comment-regexp po-active-comment-regexp)
1941          po-end-of-entry t)
1942         (if (not (string-equal (po-match-string 0) string))
1943             (let ((buffer-read-only po-read-only))
1944               (replace-match string t t)))
1945       (skip-chars-forward " \t\n")
1946       (let ((buffer-read-only po-read-only))
1947         (insert string))))
1948   (po-current-entry))
1949
1950 (defun po-kill-ring-save-comment ()
1951   "Push the msgstr string from current entry on the kill ring."
1952   (interactive)
1953   (po-find-span-of-entry)
1954   (po-get-comment t))
1955
1956 (defun po-kill-comment ()
1957   "Empty the msgstr string from current entry, pushing it on the kill ring."
1958   (interactive)
1959   (po-kill-ring-save-comment)
1960   (po-set-comment "")
1961   (po-redisplay))
1962
1963 (defun po-yank-comment ()
1964   "Replace the current comment string by the top of the kill ring."
1965   (interactive)
1966   (po-find-span-of-entry)
1967   (po-set-comment (if (eq last-command 'yank) '(yank-pop 1) '(yank)))
1968   (setq this-command 'yank)
1969   (po-redisplay))
1970 \f
1971 ;;; Editing management and submode.
1972
1973 ;; In a string edit buffer, BACK-POINTER points to one of the slots of the
1974 ;; list EDITED-FIELDS kept in the PO buffer.  See its description elsewhere.
1975 ;; Reminder: slots have the form (ENTRY-MARKER EDIT-BUFFER OVERLAY-INFO).
1976
1977 (defvar po-subedit-back-pointer)
1978
1979 (defun po-clean-out-killed-edits ()
1980   "From EDITED-FIELDS, clean out any edit having a killed edit buffer."
1981   (let ((cursor po-edited-fields))
1982     (while cursor
1983       (let ((slot (car cursor)))
1984         (setq cursor (cdr cursor))
1985         (if (buffer-name (nth 1 slot))
1986             nil
1987           (let ((overlay (nth 2 slot)))
1988             (and overlay (po-dehighlight overlay)))
1989           (setq po-edited-fields (delete slot po-edited-fields)))))))
1990
1991 (defun po-check-all-pending-edits ()
1992   "Resume any pending edit.  Return nil if some remains."
1993   (po-clean-out-killed-edits)
1994   (or (null po-edited-fields)
1995       (let ((slot (car po-edited-fields)))
1996         (goto-char (nth 0 slot))
1997         (pop-to-buffer (nth 1 slot))
1998         (let ((overlay (nth 2 slot)))
1999           (and overlay (po-rehighlight overlay)))
2000         (message po-subedit-message)
2001         nil)))
2002
2003 (defun po-check-for-pending-edit (position)
2004   "Resume any pending edit at POSITION.  Return nil if such edit exists."
2005   (po-clean-out-killed-edits)
2006   (let ((marker (make-marker)))
2007     (set-marker marker position)
2008     (let ((slot (assoc marker po-edited-fields)))
2009       (if slot
2010           (progn
2011             (goto-char marker)
2012             (pop-to-buffer (nth 1 slot))
2013             (let ((overlay (nth 2 slot)))
2014               (and overlay (po-rehighlight overlay)))
2015             (message po-subedit-message)))
2016       (not slot))))
2017
2018 (defun po-edit-out-full ()
2019   "Get out of PO mode, leaving PO file buffer in fundamental mode."
2020   (interactive)
2021   (if (and (po-check-all-pending-edits)
2022            (yes-or-no-p (_"Should I let you edit the whole PO file? ")))
2023       (progn
2024         (setq buffer-read-only po-read-only)
2025         (fundamental-mode)
2026         (message (_"Type 'M-x po-mode RET' once done")))))
2027
2028 (defun po-ediff-quit ()
2029   "Quit ediff and exit `recursive-edit'."
2030   (interactive)
2031   (ediff-quit t)
2032   (exit-recursive-edit))
2033
2034 (add-hook 'ediff-keymap-setup-hook
2035           '(lambda ()
2036              (define-key ediff-mode-map "Q" 'po-ediff-quit)))
2037
2038 (defun po-ediff-buffers-exit-recursive (b1 b2 oldbuf end)
2039   "Ediff buffer B1 and B2, pop back to OLDBUF and replace the old variants.
2040 This function will delete the first two variants in OLDBUF, call
2041 `ediff-buffers' to compare both strings and replace the two variants in
2042 OLDBUF with the contents of B2.
2043 Once done kill B1 and B2.
2044
2045 For more info cf. `po-subedit-ediff'."
2046   (ediff-buffers b1 b2)
2047   (recursive-edit)
2048   (pop-to-buffer oldbuf)
2049   (delete-region (point-min) end)
2050   (insert-buffer b2)
2051   (mapc 'kill-buffer `(,b1 ,b2))
2052   (display-buffer entry-buffer t))
2053
2054 (defun po-subedit-ediff ()
2055   "Edit the subedit buffer using `ediff'.
2056 `po-subedit-ediff' calls `po-ediff-buffers-exit-recursive' to edit translation
2057 variants side by side if they are actually different; if variants are equal just
2058 delete the first one.
2059
2060 `msgcat' is able to produce those variants; every variant is marked with:
2061
2062 #-#-#-#-#  file name reference  #-#-#-#-#
2063
2064 Put changes in second buffer.
2065
2066 When done with the `ediff' session press \\[exit-recursive-edit] exit to
2067 `recursive-edit', or call \\[po-ediff-quit] (`Q') in the ediff control panel."
2068   (interactive)
2069   (let* ((marker-regex "^#-#-#-#-#  \\(.*\\)  #-#-#-#-#\n")
2070          (buf1 " *po-msgstr-1") ; default if first marker is missing
2071          buf2 start-1 end-1 start-2 end-2
2072          (back-pointer po-subedit-back-pointer)
2073          (entry-marker (nth 0 back-pointer))
2074          (entry-buffer (marker-buffer entry-marker)))
2075     (goto-char (point-min))
2076     (if (looking-at marker-regex)
2077         (and (setq buf1 (match-string-no-properties 1))
2078              (forward-line 1)))
2079     (setq start-1 (point))
2080     (if (not (re-search-forward marker-regex (point-max) t))
2081         (error "Only 1 msgstr found")
2082       (setq buf2 (match-string-no-properties 1)
2083             end-1 (match-beginning 0))
2084       (let ((oldbuf (current-buffer)))
2085         (save-current-buffer
2086           (set-buffer (get-buffer-create
2087                        (generate-new-buffer-name buf1)))
2088           (setq buffer-read-only nil)
2089           (erase-buffer)
2090           (insert-buffer-substring oldbuf start-1 end-1)
2091           (setq buffer-read-only t))
2092         
2093         (setq start-2 (point))
2094         (save-excursion
2095           ;; check for a third variant; if found ignore it
2096           (if (re-search-forward marker-regex (point-max) t)
2097               (setq end-2 (match-beginning 0))
2098             (setq end-2 (goto-char (1- (point-max))))))
2099         (save-current-buffer
2100           (set-buffer (get-buffer-create
2101                        (generate-new-buffer-name buf2)))
2102           (erase-buffer)
2103           (insert-buffer-substring oldbuf start-2 end-2))
2104
2105         (if (not (string-equal (buffer-substring-no-properties start-1 end-1)
2106                                (buffer-substring-no-properties start-2 end-2)))
2107             (po-ediff-buffers-exit-recursive buf1 buf2 oldbuf end-2)
2108           (message "Variants are equal; delete %s" buf1)
2109           (forward-line -1)
2110           (delete-region (point-min) (point)))))))
2111
2112 (defun po-subedit-abort ()
2113   "Exit the subedit buffer, merely discarding its contents."
2114   (interactive)
2115   (let* ((edit-buffer (current-buffer))
2116          (back-pointer po-subedit-back-pointer)
2117          (entry-marker (nth 0 back-pointer))
2118          (overlay-info (nth 2 back-pointer))
2119          (entry-buffer (marker-buffer entry-marker)))
2120     (if (null entry-buffer)
2121         (error (_"Corresponding PO buffer does not exist anymore"))
2122       (or (one-window-p) (delete-window))
2123       (switch-to-buffer entry-buffer)
2124       (goto-char entry-marker)
2125       (and overlay-info (po-dehighlight overlay-info))
2126       (kill-buffer edit-buffer)
2127       (setq po-edited-fields (delete back-pointer po-edited-fields)))))
2128
2129 (defun po-subedit-exit ()
2130   "Exit the subedit buffer, replacing the string in the PO buffer."
2131   (interactive)
2132   (goto-char (point-max))
2133   (skip-chars-backward " \t\n")
2134   (if (eq (preceding-char) ?<)
2135       (delete-region (1- (point)) (point-max)))
2136   (run-hooks 'po-subedit-exit-hook)
2137   (let ((string (buffer-string)))
2138     (po-subedit-abort)
2139     (po-find-span-of-entry)
2140     (cond ((= (point) po-start-of-msgid)
2141            (po-set-comment string)
2142            (po-redisplay))
2143           ((= (point) po-start-of-msgstr)
2144            (let ((replaced (po-set-msgstr string)))
2145              (if (and replaced
2146                       po-auto-fuzzy-on-edit
2147                       (eq po-entry-type 'translated))
2148                  (progn
2149                    (po-decrease-type-counter)
2150                    (po-add-attribute "fuzzy")
2151                    (po-current-entry)
2152                    (po-increase-type-counter)))))
2153           (t (debug)))))
2154
2155 (defun po-edit-string (string type expand-tabs)
2156   "Prepare a pop up buffer for editing STRING, which is of a given TYPE.
2157 TYPE may be 'comment or 'msgstr.  If EXPAND-TABS, expand tabs to spaces.
2158 Run functions on po-subedit-mode-hook."
2159   (let ((marker (make-marker)))
2160     (set-marker marker (cond ((eq type 'comment) po-start-of-msgid)
2161                              ((eq type 'msgstr) po-start-of-msgstr)))
2162     (if (po-check-for-pending-edit marker)
2163         (let ((edit-buffer (generate-new-buffer
2164                             (concat "*" (buffer-name) "*")))
2165               (edit-coding buffer-file-coding-system)
2166               (buffer (current-buffer))
2167               overlay slot)
2168           (if (and (eq type 'msgstr) po-highlighting)
2169               ;; ;; Try showing all of msgid in the upper window while editing.
2170               ;; (goto-char (1- po-start-of-msgstr))
2171               ;; (recenter -1)
2172               (save-excursion
2173                 (goto-char po-start-of-entry)
2174                 (re-search-forward po-any-msgid-regexp nil t)
2175                 (let ((end (1- (match-end 0))))
2176                   (goto-char (match-beginning 0))
2177                   (re-search-forward "msgid +" nil t)
2178                   (setq overlay (po-create-overlay))
2179                   (po-highlight overlay (point) end buffer))))
2180           (setq slot (list marker edit-buffer overlay)
2181                 po-edited-fields (cons slot po-edited-fields))
2182           (pop-to-buffer edit-buffer)
2183           (set (make-local-variable 'po-subedit-back-pointer) slot)
2184           (set (make-local-variable 'indent-line-function)
2185                'indent-relative)
2186           (setq buffer-file-coding-system edit-coding)
2187           (setq local-abbrev-table po-mode-abbrev-table)
2188           (erase-buffer)
2189           (insert string "<")
2190           (goto-char (point-min))
2191           (and expand-tabs (setq indent-tabs-mode nil))
2192           (use-local-map po-subedit-mode-map)
2193           (if (fboundp 'easy-menu-define)
2194               (progn
2195                 (easy-menu-define po-subedit-mode-menu po-subedit-mode-map ""
2196                   po-subedit-mode-menu-layout)
2197                 (and po-XEMACS (easy-menu-add po-subedit-mode-menu))))
2198           (set-syntax-table po-subedit-mode-syntax-table)
2199           (run-hooks 'po-subedit-mode-hook)
2200           (message po-subedit-message)))))
2201
2202 (defun po-edit-comment ()
2203   "Use another window to edit the current translator comment."
2204   (interactive)
2205   (po-find-span-of-entry)
2206   (po-edit-string (po-get-comment nil) 'comment nil))
2207   
2208 (defun po-edit-comment-and-ediff ()
2209   "Use `ediff' to edit the current translator comment.
2210 This function calls `po-edit-msgstr' and `po-subedit-ediff'; for more info
2211 read `po-subedit-ediff' documentation."
2212   (interactive)
2213   (po-edit-comment)
2214   (po-subedit-ediff))
2215
2216 (defun po-edit-msgstr ()
2217   "Use another window to edit the current msgstr."
2218   (interactive)
2219   (po-find-span-of-entry)
2220   (po-edit-string (if (and po-auto-edit-with-msgid
2221                            (eq po-entry-type 'untranslated))
2222                       (po-get-msgid nil)
2223                     (po-get-msgstr nil))
2224                   'msgstr
2225                   t))
2226
2227 (defun po-edit-msgstr-and-ediff ()
2228   "Use `ediff' to edit the current msgstr.
2229 This function calls `po-edit-msgstr' and `po-subedit-ediff'; for more info
2230 read `po-subedit-ediff' documentation."
2231   (interactive)
2232   (po-edit-msgstr)
2233   (po-subedit-ediff))
2234 \f
2235 ;;; String normalization and searching.
2236
2237 (defun po-normalize-old-style (explain)
2238   "Normalize old gettext style fields using K&R C multiline string syntax.
2239 To minibuffer messages sent while normalizing, add the EXPLAIN string."
2240   (let ((here (point-marker))
2241         (counter 0)
2242         (buffer-read-only po-read-only))
2243     (goto-char (point-min))
2244     (message (_"Normalizing %d, %s") counter explain)
2245     (while (re-search-forward
2246             "\\(^#?[ \t]*msg\\(id\\|str\\)[ \t]*\"\\|[^\" \t][ \t]*\\)\\\\\n"
2247             nil t)
2248       (if (= (% counter 10) 0)
2249           (message (_"Normalizing %d, %s") counter explain))
2250       (replace-match "\\1\"\n\"" t nil)
2251       (setq counter (1+ counter)))
2252     (goto-char here)
2253     (message (_"Normalizing %d...done") counter)))
2254
2255 (defun po-normalize-field (field explain)
2256   "Normalize FIELD of all entries.  FIELD is either the symbol msgid or msgstr.
2257 To minibuffer messages sent while normalizing, add the EXPLAIN string."
2258   (let ((here (point-marker))
2259         (counter 0))
2260     (goto-char (point-min))
2261     (while (re-search-forward po-any-msgstr-regexp nil t)
2262       (if (= (% counter 10) 0)
2263           (message (_"Normalizing %d, %s") counter explain))
2264       (goto-char (match-beginning 0))
2265       (po-find-span-of-entry)
2266       (cond ((eq field 'msgid) (po-set-msgid (po-get-msgid nil)))
2267             ((eq field 'msgstr) (po-set-msgstr (po-get-msgstr nil))))
2268       (goto-char po-end-of-entry)
2269       (setq counter (1+ counter)))
2270     (goto-char here)
2271     (message (_"Normalizing %d...done") counter)))
2272
2273 ;; Normalize, but the British way! :-)
2274 (defsubst po-normalise () (po-normalize))
2275
2276 (defun po-normalize ()
2277   "Normalize all entries in the PO file."
2278   (interactive)
2279   (po-normalize-old-style (_"pass 1/3"))
2280   (po-normalize-field t (_"pass 2/3"))
2281   (po-normalize-field nil (_"pass 3/3"))
2282   ;; The last PO file entry has just been processed.
2283   (if (not (= po-end-of-entry (point-max)))
2284       (let ((buffer-read-only po-read-only))
2285         (kill-region po-end-of-entry (point-max))))
2286   ;; A bizarre format might have fooled the counters, so recompute
2287   ;; them to make sure their value is dependable.
2288   (po-compute-counters nil))
2289 \f
2290 ;;; Multiple PO files.
2291
2292 (defun po-show-auxiliary-list ()
2293   "Echo the current auxiliary list in the message area."
2294   (if po-auxiliary-list
2295       (let ((cursor po-auxiliary-cursor)
2296             string)
2297         (while cursor
2298           (setq string (concat string (if string " ") (car (car cursor)))
2299                 cursor (cdr cursor)))
2300         (setq cursor po-auxiliary-list)
2301         (while (not (eq cursor po-auxiliary-cursor))
2302           (setq string (concat string (if string " ") (car (car cursor)))
2303                 cursor (cdr cursor)))
2304         (message string))
2305     (message (_"No auxiliary files."))))
2306
2307 (defun po-consider-as-auxiliary ()
2308   "Add the current PO file to the list of auxiliary files."
2309   (interactive)
2310   (if (member (list buffer-file-name) po-auxiliary-list)
2311       nil
2312     (setq po-auxiliary-list
2313           (nconc po-auxiliary-list (list (list buffer-file-name))))
2314     (or po-auxiliary-cursor
2315         (setq po-auxiliary-cursor po-auxiliary-list)))
2316   (po-show-auxiliary-list))
2317
2318 (defun po-ignore-as-auxiliary ()
2319   "Delete the current PO file from the list of auxiliary files."
2320   (interactive)
2321   (setq po-auxiliary-list (delete (list buffer-file-name) po-auxiliary-list)
2322         po-auxiliary-cursor po-auxiliary-list)
2323   (po-show-auxiliary-list))
2324
2325 (defun po-seek-equivalent-translation (name string)
2326   "Search a PO file NAME for a 'msgid' STRING having a non-empty 'msgstr'.
2327 STRING is the full quoted msgid field, including the 'msgid' keyword.  When
2328 found, display the file over the current window, with the 'msgstr' field
2329 possibly highlighted, the cursor at start of msgid, then return 't'.
2330 Otherwise, move nothing, and just return 'nil'."
2331   (let ((current (current-buffer))
2332         (buffer (find-file-noselect name)))
2333     (set-buffer buffer)
2334     (let ((start (point))
2335           found)
2336       (goto-char (point-min))
2337       (while (and (not found) (search-forward string nil t))
2338         ;; Screen out longer 'msgid's.
2339         (if (looking-at "^msgstr ")
2340             (progn
2341               (po-find-span-of-entry)
2342               ;; Ignore an untranslated entry.
2343               (or (string-equal
2344                    (buffer-substring po-start-of-msgstr po-end-of-entry)
2345                    "msgstr \"\"\n")
2346                   (setq found t)))))
2347       (if found
2348           (progn
2349             (switch-to-buffer buffer)
2350             (po-find-span-of-entry)
2351             (if po-highlighting
2352                 (progn
2353                   (goto-char po-start-of-entry)
2354                   (re-search-forward po-any-msgstr-regexp nil t)
2355                   (let ((end (1- (match-end 0))))
2356                     (goto-char (match-beginning 0))
2357                     (re-search-forward "msgstr +" nil t)
2358                     ;; Just "borrow" the marking overlay.
2359                     (po-highlight po-marking-overlay (point) end))))
2360             (goto-char po-start-of-msgid))
2361         (goto-char start)
2362         (po-find-span-of-entry)
2363         (set-buffer current))
2364       found)))
2365
2366 (defun po-cycle-auxiliary ()
2367   "Select the next auxiliary file having an entry with same 'msgid'."
2368   (interactive)
2369   (po-find-span-of-entry)
2370   (if po-auxiliary-list
2371       (let ((string (buffer-substring po-start-of-msgid po-start-of-msgstr))
2372             (cursor po-auxiliary-cursor)
2373             found name)
2374         (while (and (not found) cursor)
2375           (setq name (car (car cursor)))
2376           (if (and (not (string-equal buffer-file-name name))
2377                    (po-seek-equivalent-translation name string))
2378               (setq found t
2379                     po-auxiliary-cursor cursor))
2380           (setq cursor (cdr cursor)))
2381         (setq cursor po-auxiliary-list)
2382         (while (and (not found) cursor)
2383           (setq name (car (car cursor)))
2384           (if (and (not (string-equal buffer-file-name name))
2385                    (po-seek-equivalent-translation name string))
2386               (setq found t
2387                     po-auxiliary-cursor cursor))
2388           (setq cursor (cdr cursor)))
2389         (or found (message (_"No other translation found")))
2390         found)))
2391
2392 (defun po-subedit-cycle-auxiliary ()
2393   "Cycle auxiliary file, but from the translation edit buffer."
2394   (interactive)
2395   (let* ((entry-marker (nth 0 po-subedit-back-pointer))
2396          (entry-buffer (marker-buffer entry-marker))
2397          (buffer (current-buffer)))
2398     (pop-to-buffer entry-buffer)
2399     (po-cycle-auxiliary)
2400     (pop-to-buffer buffer)))
2401
2402 (defun po-select-auxiliary ()
2403   "Select one of the available auxiliary files and locate an equivalent entry.
2404 If an entry having the same 'msgid' cannot be found, merely select the file
2405 without moving its cursor."
2406   (interactive)
2407   (po-find-span-of-entry)
2408   (if po-auxiliary-list
2409       (let ((string (buffer-substring po-start-of-msgid po-start-of-msgstr))
2410             (name (car (assoc (completing-read (_"Which auxiliary file? ")
2411                                                po-auxiliary-list nil t)
2412                               po-auxiliary-list))))
2413         (po-consider-as-auxiliary)
2414         (or (po-seek-equivalent-translation name string)
2415             (find-file name)))))
2416 \f
2417 ;;; Original program sources as context.
2418
2419 (defun po-show-source-path ()
2420   "Echo the current source search path in the message area."
2421   (if po-search-path
2422       (let ((cursor po-search-path)
2423             string)
2424         (while cursor
2425           (setq string (concat string (if string " ") (car (car cursor)))
2426                 cursor (cdr cursor)))
2427         (message string))
2428     (message (_"Empty source path."))))
2429
2430 (defun po-consider-source-path (directory)
2431   "Add a given DIRECTORY, requested interactively, to the source search path."
2432   (interactive "DDirectory for search path: ")
2433   (setq po-search-path (cons (list (if (string-match "/$" directory)
2434                                          directory
2435                                        (concat directory "/")))
2436                              po-search-path))
2437   (setq po-reference-check 0)
2438   (po-show-source-path))
2439
2440 (defun po-ignore-source-path ()
2441   "Delete a directory, selected with completion, from the source search path."
2442   (interactive)
2443   (setq po-search-path
2444         (delete (list (completing-read (_"Directory to remove? ")
2445                                        po-search-path nil t))
2446                 po-search-path))
2447   (setq po-reference-check 0)
2448   (po-show-source-path))
2449
2450 (defun po-ensure-source-references ()
2451   "Extract all references into a list, with paths resolved, if necessary."
2452   (po-find-span-of-entry)
2453   (if (= po-start-of-entry po-reference-check)
2454       nil
2455     (setq po-reference-alist nil)
2456     (save-excursion
2457       (goto-char po-start-of-entry)
2458       (if (re-search-forward "^#:" po-start-of-msgid t)
2459           (let (current name line path file)
2460             (while (looking-at "\\(\n#:\\)? *\\([^: ]*\\):\\([0-9]+\\)")
2461               (goto-char (match-end 0))
2462               (setq name (po-match-string 2)
2463                     line (po-match-string 3)
2464                     path po-search-path)
2465               (if (string-equal name "")
2466                   nil
2467                 (while (and (not (file-exists-p
2468                                   (setq file (concat (car (car path)) name))))
2469                             path)
2470                   (setq path (cdr path)))
2471                 (setq current (and path file)))
2472               (if current
2473                   (setq po-reference-alist
2474                         (cons (list (concat current ":" line)
2475                                     current
2476                                     (string-to-number line))
2477                               po-reference-alist)))))))
2478     (setq po-reference-alist (nreverse po-reference-alist)
2479           po-reference-cursor po-reference-alist
2480           po-reference-check po-start-of-entry)))
2481
2482 (defun po-show-source-context (triplet)
2483   "Show the source context given a TRIPLET which is (PROMPT FILE LINE)."
2484   (find-file-other-window (car (cdr triplet)))
2485   (goto-line (car (cdr (cdr triplet))))
2486   (other-window 1)
2487   (let ((maximum 0)
2488         position
2489         (cursor po-reference-alist))
2490     (while (not (eq triplet (car cursor)))
2491       (setq maximum (1+ maximum)
2492             cursor (cdr cursor)))
2493     (setq position (1+ maximum)
2494           po-reference-cursor cursor)
2495     (while cursor
2496       (setq maximum (1+ maximum)
2497             cursor (cdr cursor)))
2498     (message (_"Displaying %d/%d: \"%s\"") position maximum (car triplet))))
2499
2500 (defun po-cycle-source-reference ()
2501   "Display some source context for the current entry.
2502 If the command is repeated many times in a row, cycle through contexts."
2503   (interactive)
2504   (po-ensure-source-references)
2505   (if po-reference-cursor
2506       (po-show-source-context
2507        (car (if (eq last-command 'po-cycle-source-reference)
2508                 (or (cdr po-reference-cursor) po-reference-alist)
2509               po-reference-cursor)))
2510     (error (_"No resolved source references"))))
2511
2512 (defun po-select-source-reference ()
2513   "Select one of the available source contexts for the current entry."
2514   (interactive)
2515   (po-ensure-source-references)
2516   (if po-reference-alist
2517       (po-show-source-context
2518        (assoc
2519         (completing-read (_"Which source context? ") po-reference-alist nil t)
2520         po-reference-alist))
2521     (error (_"No resolved source references"))))
2522 \f
2523 ;;; String marking in program sources, through TAGS table.
2524
2525 ;; Globally defined within tags.el.
2526 (defvar tags-loop-operate)
2527 (defvar tags-loop-scan)
2528
2529 ;; Locally set in each program source buffer.
2530 (defvar po-find-string-function)
2531 (defvar po-mark-string-function)
2532
2533 ;; Dynamically set within po-tags-search for po-tags-loop-operate.
2534 (defvar po-current-po-buffer)
2535 (defvar po-current-po-keywords)
2536
2537 (defun po-tags-search (restart)
2538   "Find an unmarked translatable string through all files in tags table.
2539 Disregard some simple strings which are most probably non-translatable.
2540 With prefix argument, restart search at first file."
2541   (interactive "P")
2542   (require 'etags)
2543   ;; Ensure there is no highlighting, in case the search fails.
2544   (if po-highlighting
2545       (po-dehighlight po-marking-overlay))
2546   (setq po-string-contents nil)
2547   ;; Search for a string which might later be marked for translation.
2548   (let ((po-current-po-buffer (current-buffer))
2549         (po-current-po-keywords po-keywords))
2550     (pop-to-buffer po-string-buffer)
2551     (if (and (not restart)
2552              (eq (car tags-loop-operate) 'po-tags-loop-operate))
2553         ;; Continue last po-tags-search.
2554         (tags-loop-continue nil)
2555       ;; Start or restart po-tags-search all over.
2556       (setq tags-loop-scan '(po-tags-loop-scan)
2557             tags-loop-operate '(po-tags-loop-operate))
2558       (tags-loop-continue t))
2559     (select-window (get-buffer-window po-current-po-buffer)))
2560   (if po-string-contents
2561       (let ((window (selected-window))
2562             (buffer po-string-buffer)
2563             (start po-string-start)
2564             (end po-string-end))
2565         ;; Try to fit the string in the displayed part of its window.
2566         (select-window (get-buffer-window buffer))
2567         (goto-char start)
2568         (or (pos-visible-in-window-p start)
2569             (recenter '(nil)))
2570         (if (pos-visible-in-window-p end)
2571             (goto-char end)
2572           (goto-char end)
2573           (recenter -1))
2574         (select-window window)
2575         ;; Highlight the string as found.
2576         (and po-highlighting
2577              (po-highlight po-marking-overlay start end buffer)))))
2578
2579 (defun po-tags-loop-scan ()
2580   "Decide if the current buffer is still interesting for PO mode strings."
2581   ;; We have little choice, here.  The major mode is needed to dispatch to the
2582   ;; proper scanner, so we declare all files as interesting, to force Emacs
2583   ;; tags module to revisit files fully.  po-tags-loop-operate sets point at
2584   ;; end of buffer when it is done with a file.
2585   (not (eobp)))
2586
2587 (defun po-tags-loop-operate ()
2588   "Find an acceptable tag in the current buffer, according to mode.
2589 Disregard some simple strings which are most probably non-translatable."
2590   (po-preset-string-functions)
2591   (let ((continue t)
2592         data)
2593     (while continue
2594       (setq data (apply po-find-string-function po-current-po-keywords nil))
2595       (if data
2596           ;; Push the string just found into a work buffer for study.
2597           (po-with-temp-buffer
2598            (insert (nth 0 data))
2599            (goto-char (point-min))
2600            ;; Accept if at least three letters in a row.
2601            (if (re-search-forward "[A-Za-z][A-Za-z][A-Za-z]" nil t)
2602                (setq continue nil)
2603              ;; Disregard if single letters or no letters at all.
2604              (if (re-search-forward "[A-Za-z][A-Za-z]" nil t)
2605                  ;; Here, we have two letters in a row, but never more.
2606                  ;; Accept only if more letters than punctuations.
2607                  (let ((total (buffer-size)))
2608                    (goto-char (point-min))
2609                    (while (re-search-forward "[A-Za-z]+" nil t)
2610                      (replace-match "" t t))
2611                    (if (< (* 2 (buffer-size)) total)
2612                        (setq continue nil))))))
2613         ;; No string left in this buffer.
2614         (setq continue nil)))
2615     (if data
2616         ;; Save information for marking functions.
2617         (let ((buffer (current-buffer)))
2618           (save-excursion
2619             (set-buffer po-current-po-buffer)
2620             (setq po-string-contents (nth 0 data)
2621                   po-string-buffer buffer
2622                   po-string-start (nth 1 data)
2623                   po-string-end (nth 2 data))))
2624       (goto-char (point-max)))
2625     ;; If nothing was found, trigger scanning of next file.
2626     (not data)))
2627
2628 (defun po-mark-found-string (keyword)
2629   "Mark last found string in program sources as translatable, using KEYWORD."
2630   (if (not po-string-contents)
2631     (error (_"No such string")))
2632   (and po-highlighting (po-dehighlight po-marking-overlay))
2633   (let ((contents po-string-contents)
2634         (buffer po-string-buffer)
2635         (start po-string-start)
2636         (end po-string-end)
2637         line string)
2638     ;; Mark string in program sources.
2639     (save-excursion
2640       (set-buffer buffer)
2641       (setq line (count-lines (point-min) start))
2642       (apply po-mark-string-function start end keyword nil))
2643     ;; Add PO file entry.
2644     (let ((buffer-read-only po-read-only))
2645       (goto-char (point-max))
2646       (insert "\n" (format "#: %s:%d\n"
2647                            (buffer-file-name po-string-buffer)
2648                            line))
2649       (save-excursion
2650         (insert (po-eval-requoted contents "msgid" nil) "msgstr \"\"\n"))
2651       (setq po-untranslated-counter (1+ po-untranslated-counter))
2652       (po-update-mode-line-string))
2653     (setq po-string-contents nil)))
2654
2655 (defun po-mark-translatable ()
2656   "Mark last found string in program sources as translatable, using '_'."
2657   (interactive)
2658   (po-mark-found-string "_"))
2659
2660 (defun po-select-mark-and-mark (arg)
2661   "Mark last found string in program sources as translatable, ask for keywoard,
2662 using completion.  With prefix argument, just ask the name of a preferred
2663 keyword for subsequent commands, also added to possible completions."
2664   (interactive "P")
2665   (if arg
2666       (let ((keyword (list (read-from-minibuffer (_"Keyword: ")))))
2667         (setq po-keywords (cons keyword (delete keyword po-keywords))))
2668     (or po-string-contents (error (_"No such string")))
2669     (let* ((default (car (car po-keywords)))
2670            (keyword (completing-read (format (_"Mark with keywoard? [%s] ")
2671                                              default)
2672                                      po-keywords nil t )))
2673       (if (string-equal keyword "") (setq keyword default))
2674       (po-mark-found-string keyword))))
2675 \f
2676 ;;; Unknown mode specifics.
2677
2678 (defun po-preset-string-functions ()
2679   "Preset FIND-STRING-FUNCTION and MARK-STRING-FUNCTION according to mode.
2680 These variables are locally set in source buffer only when not already bound."
2681   (let ((pair (cond ((string-equal mode-name "AWK")
2682                      '(po-find-awk-string . po-mark-awk-string))
2683                     ((member mode-name '("C" "C++"))
2684                      '(po-find-c-string . po-mark-c-string))
2685                     ((string-equal mode-name "Emacs-Lisp")
2686                      '(po-find-emacs-lisp-string . po-mark-emacs-lisp-string))
2687                     ((string-equal mode-name "Python")
2688                      '(po-find-python-string . po-mark-python-string))
2689                     ((and (string-equal mode-name "Shell-script")
2690                           (string-equal mode-line-process "[bash]"))
2691                      '(po-find-bash-string . po-mark-bash-string))
2692                     (t '(po-find-unknown-string . po-mark-unknown-string)))))
2693     (or (boundp 'po-find-string-function)
2694         (set (make-local-variable 'po-find-string-function) (car pair)))
2695     (or (boundp 'po-mark-string-function)
2696         (set (make-local-variable 'po-mark-string-function) (cdr pair)))))
2697
2698 (defun po-find-unknown-string (keywords)
2699   "Dummy function to skip over a file, finding no string in it."
2700   nil)
2701
2702 (defun po-mark-unknown-string (start end keyword)
2703   "Dummy function to mark a given string.  May not be called."
2704   (error (_"Dummy function called")))
2705 \f
2706 ;;; Awk mode specifics.
2707
2708 (defun po-find-awk-string (keywords)
2709   "Find the next Awk string, excluding those marked by any of KEYWORDS.
2710 Return (CONTENTS START END) for the found string, or nil if none found."
2711   (let (start end)
2712     (while (and (not start)
2713                 (re-search-forward "[#/\"]" nil t))
2714       (cond ((= (preceding-char) ?#)
2715              ;; Disregard comments.
2716              (or (search-forward "\n" nil t)
2717                  (goto-char (point-max))))
2718             ((= (preceding-char) ?/)
2719              ;; Skip regular expressions.
2720              (while (not (= (following-char) ?/))
2721                (skip-chars-forward "^/\\\\")
2722                (if (= (following-char) ?\\) (forward-char 2)))
2723              (forward-char 1))
2724             ;; Else find the end of the string.
2725             (t (setq start (1- (point)))
2726                (while (not (= (following-char) ?\"))
2727                  (skip-chars-forward "^\"\\\\")
2728                  (if (= (following-char) ?\\) (forward-char 2)))
2729                (forward-char 1)
2730                (setq end (point))
2731                ;; Check before string either for underline, or for keyword
2732                ;; and opening parenthesis.
2733                (save-excursion
2734                  (goto-char start)
2735                  (cond ((= (preceding-char) ?_)
2736                         ;; Disregard already marked strings.
2737                         (setq start nil
2738                               end nil))
2739                        ((= (preceding-char) ?\()
2740                         (backward-char 1)
2741                         (let ((end-keyword (point)))
2742                           (skip-chars-backward "_A-Za-z0-9")
2743                           (if (member (list (po-buffer-substring
2744                                              (point) end-keyword))
2745                                       keywords)
2746                               ;; Disregard already marked strings.
2747                               (setq start nil
2748                                     end nil)))))))))
2749     (and start end
2750          (list (po-extract-unquoted (current-buffer) start end) start end))))
2751
2752 (defun po-mark-awk-string (start end keyword)
2753   "Mark the Awk string, from START to END, with KEYWORD.
2754 Leave point after marked string."
2755   (if (string-equal keyword "_")
2756       (progn
2757         (goto-char start)
2758         (insert "_")
2759         (goto-char (1+ end)))
2760     (goto-char end)
2761     (insert ")")
2762     (save-excursion
2763       (goto-char start)
2764       (insert keyword "("))))
2765 \f
2766 ;;; Bash mode specifics.
2767
2768 (defun po-find-bash-string (keywords)
2769   "Find the next unmarked Bash string.  KEYWORDS are merely ignored.
2770 Return (CONTENTS START END) for the found string, or nil if none found."
2771   (let (start end)
2772     (while (and (not start)
2773                 (re-search-forward "[#'\"]" nil t))
2774       (cond ((= (preceding-char) ?#)
2775              ;; Disregard comments.
2776              (or (search-forward "\n" nil t)
2777                  (goto-char (point-max))))
2778             ((= (preceding-char) ?')
2779              ;; Skip single quoted strings.
2780              (while (not (= (following-char) ?'))
2781                (skip-chars-forward "^'\\\\")
2782                (if (= (following-char) ?\\) (forward-char 2)))
2783              (forward-char 1))
2784             ;; Else find the end of the double quoted string.
2785             (t (setq start (1- (point)))
2786                (while (not (= (following-char) ?\"))
2787                  (skip-chars-forward "^\"\\\\")
2788                  (if (= (following-char) ?\\) (forward-char 2)))
2789                (forward-char 1)
2790                (setq end (point))
2791                ;; Check before string for dollar sign.
2792                (save-excursion
2793                  (goto-char start)
2794                  (if (= (preceding-char) ?$)
2795                      ;; Disregard already marked strings.
2796                      (setq start nil
2797                            end nil))))))
2798     (and start end
2799          (list (po-extract-unquoted (current-buffer) start end) start end))))
2800
2801 (defun po-mark-bash-string (start end keyword)
2802   "Mark the Bash string, from START to END, with '$'.  KEYWORD is ignored.
2803 Leave point after marked string."
2804   (goto-char start)
2805   (insert "$")
2806   (goto-char (1+ end)))
2807 \f
2808 ;;; C or C++ mode specifics.
2809
2810 ;;; A few long string cases (submitted by Ben Pfaff).
2811
2812 ;; #define string "This is a long string " \
2813 ;; "that is continued across several lines " \
2814 ;; "in a macro in order to test \\ quoting\\" \
2815 ;; "\\ with goofy strings.\\"
2816
2817 ;; char *x = "This is just an ordinary string "
2818 ;; "continued across several lines without needing "
2819 ;; "to use \\ characters at end-of-line.";
2820
2821 ;; char *y = "Here is a string continued across \
2822 ;; several lines in the manner that was sanctioned \
2823 ;; in K&R C compilers and still works today, \
2824 ;; even though the method used above is more esthetic.";
2825
2826 ;;; End of long string cases.
2827
2828 (defun po-find-c-string (keywords)
2829   "Find the next C string, excluding those marked by any of KEYWORDS.
2830 Returns (CONTENTS START END) for the found string, or nil if none found."
2831   (let (start end)
2832     (while (and (not start)
2833                 (re-search-forward "\\([\"']\\|/\\*\\|//\\)" nil t))
2834       (cond ((= (preceding-char) ?*)
2835              ;; Disregard comments.
2836              (search-forward "*/"))
2837             ((= (preceding-char) ?/)
2838              ;; Disregard C++ comments.
2839              (end-of-line)
2840              (forward-char 1))
2841             ((= (preceding-char) ?\')
2842              ;; Disregard character constants.
2843              (forward-char (if (= (following-char) ?\\) 3 2)))
2844             ((save-excursion
2845                (beginning-of-line)
2846                (looking-at "^# *\\(include\\|line\\)"))
2847              ;; Disregard lines being #include or #line directives.
2848              (end-of-line))
2849             ;; Else, find the end of the (possibly concatenated) string.
2850             (t (setq start (1- (point))
2851                      end nil)
2852                (while (not end)
2853                  (cond ((= (following-char) ?\")
2854                         (if (looking-at "\"[ \t\n\\\\]*\"")
2855                             (goto-char (match-end 0))
2856                           (forward-char 1)
2857                           (setq end (point))))
2858                        ((= (following-char) ?\\) (forward-char 2))
2859                        (t (skip-chars-forward "^\"\\\\"))))
2860                ;; Check before string for keyword and opening parenthesis.
2861                (goto-char start)
2862                (skip-chars-backward " \n\t")
2863                (if (= (preceding-char) ?\()
2864                    (progn
2865                      (backward-char 1)
2866                      (skip-chars-backward " \n\t")
2867                      (let ((end-keyword (point)))
2868                        (skip-chars-backward "_A-Za-z0-9")
2869                        (if (member (list (po-buffer-substring (point)
2870                                                               end-keyword))
2871                                    keywords)
2872                            ;; Disregard already marked strings.
2873                            (progn
2874                              (goto-char end)
2875                              (setq start nil
2876                                    end nil))
2877                          ;; String found.  Prepare to resume search.
2878                          (goto-char end))))
2879                  ;; String found.  Prepare to resume search.
2880                  (goto-char end)))))
2881     ;; Return the found string, if any.
2882     (and start end
2883          (list (po-extract-unquoted (current-buffer) start end) start end))))
2884
2885 (defun po-mark-c-string (start end keyword)
2886   "Mark the C string, from START to END, with KEYWORD.
2887 Leave point after marked string."
2888   (goto-char end)
2889   (insert ")")
2890   (save-excursion
2891     (goto-char start)
2892     (insert keyword)
2893     (or (string-equal keyword "_") (insert " "))
2894     (insert "(")))
2895 \f
2896 ;;; Emacs LISP mode specifics.
2897
2898 (defun po-find-emacs-lisp-string (keywords)
2899   "Find the next Emacs LISP string, excluding those marked by any of KEYWORDS.
2900 Returns (CONTENTS START END) for the found string, or nil if none found."
2901   (let (start end)
2902     (while (and (not start)
2903                 (re-search-forward "[;\"?]" nil t))
2904       (cond ((= (preceding-char) ?\;)
2905              ;; Disregard comments.
2906              (search-forward "\n"))
2907             ((= (preceding-char) ?\?)
2908              ;; Disregard character constants.
2909              (forward-char (if (= (following-char) ?\\) 2 1)))
2910             ;; Else, find the end of the string.
2911             (t (setq start (1- (point)))
2912                (while (not (= (following-char) ?\"))
2913                  (skip-chars-forward "^\"\\\\")
2914                  (if (= (following-char) ?\\) (forward-char 2)))
2915                (forward-char 1)
2916                (setq end (point))
2917                ;; Check before string for keyword and opening parenthesis.
2918                (goto-char start)
2919                (skip-chars-backward " \n\t")
2920                (let ((end-keyword (point)))
2921                  (skip-chars-backward "-_A-Za-z0-9")
2922                  (if (and (= (preceding-char) ?\()
2923                           (member (list (po-buffer-substring (point)
2924                                                              end-keyword))
2925                                   keywords))
2926                      ;; Disregard already marked strings.
2927                      (progn
2928                        (goto-char end)
2929                        (setq start nil
2930                              end nil)))))))
2931     ;; Return the found string, if any.
2932     (and start end
2933          (list (po-extract-unquoted (current-buffer) start end) start end))))
2934
2935 (defun po-mark-emacs-lisp-string (start end keyword)
2936   "Mark the Emacs LISP string, from START to END, with KEYWORD.
2937 Leave point after marked string."
2938   (goto-char end)
2939   (insert ")")
2940   (save-excursion
2941     (goto-char start)
2942     (insert "(" keyword)
2943     (or (string-equal keyword "_") (insert " "))))
2944 \f
2945 ;;; Python mode specifics.
2946
2947 (defun po-find-python-string (keywords)
2948   "Find the next Python string, excluding those marked by any of KEYWORDS.
2949 Also disregard strings when preceded by an empty string of the other type.
2950 Returns (CONTENTS START END) for the found string, or nil if none found."
2951   (let (contents start end)
2952     (while (and (not contents)
2953                 (re-search-forward "[#\"']" nil t))
2954       (forward-char -1)
2955       (cond ((= (following-char) ?\#)
2956              ;; Disregard comments.
2957              (search-forward "\n"))
2958             ((looking-at "\"\"'")
2959              ;; Quintuple-quoted string
2960              (po-skip-over-python-string))
2961             ((looking-at "''\"")
2962              ;; Quadruple-quoted string
2963              (po-skip-over-python-string))
2964             (t
2965              ;; Simple-, double-, triple- or sextuple-quoted string.
2966              (if (memq (preceding-char) '(?r ?R))
2967                  (forward-char -1))
2968              (setq start (point)
2969                    contents (po-skip-over-python-string)
2970                    end (point))
2971              (goto-char start)
2972              (skip-chars-backward " \n\t")
2973              (cond ((= (preceding-char) ?\[)
2974                     ;; Disregard a string used as a dictionary index.
2975                     (setq contents nil))
2976                    ((= (preceding-char) ?\()
2977                     ;; Isolate the keyword which precedes string.
2978                     (backward-char 1)
2979                     (skip-chars-backward " \n\t")
2980                     (let ((end-keyword (point)))
2981                       (skip-chars-backward "_A-Za-z0-9")
2982                       (if (member (list (po-buffer-substring (point)
2983                                                              end-keyword))
2984                                   keywords)
2985                           ;; Disregard already marked strings.
2986                           (setq contents nil)))))
2987              (goto-char end))))
2988     ;; Return the found string, if any.
2989     (and contents (list contents start end))))
2990
2991 (defun po-skip-over-python-string ()
2992   "Skip over a Python string, possibly made up of many concatenated parts.
2993 Leave point after string.  Return unquoted overall string contents."
2994   (let ((continue t)
2995         (contents "")
2996         raw start end resume)
2997     (while continue
2998       (skip-chars-forward " \t\n")      ; whitespace
2999       (cond ((= (following-char) ?#)    ; comment
3000              (setq start nil)
3001              (search-forward "\n"))
3002             ((looking-at "\\\n")        ; escaped newline
3003              (setq start nil)
3004              (forward-char 2))
3005             ((looking-at "[rR]?\"\"\"") ; sextuple-quoted string
3006              (setq raw (memq (following-char) '(?r ?R))
3007                    start (match-end 0))
3008              (goto-char start)
3009              (search-forward "\"\"\"")
3010              (setq resume (point)
3011                    end (- resume 3)))
3012             ((looking-at "[rr]?'''")    ; triple-quoted string
3013              (setq raw (memq (following-char) '(?r ?R))
3014                    start (match-end 0))
3015              (goto-char start)
3016              (search-forward "'''")
3017              (setq resume (point)
3018                    end (- resume 3)))
3019             ((looking-at "[rR]?\"")     ; double-quoted string
3020              (setq raw (memq (following-char) '(?r ?R))
3021                    start (match-end 0))
3022              (goto-char start)
3023              (while (not (memq (following-char) '(0 ?\")))
3024                (skip-chars-forward "^\"\\\\")
3025                (if (= (following-char) ?\\) (forward-char 2)))
3026              (if (eobp)
3027                  (setq contents nil
3028                        start nil)
3029                (setq end (point))
3030                (forward-char 1))
3031              (setq resume (point)))
3032             ((looking-at "[rR]?'")      ; single-quoted string
3033              (setq raw (memq (following-char) '(?r ?R))
3034                    start (match-end 0))
3035              (goto-char start)
3036              (while (not (memq (following-char) '(0 ?\')))
3037                (skip-chars-forward "^'\\\\")
3038                (if (= (following-char) ?\\) (forward-char 2)))
3039              (if (eobp)
3040                  (setq contents nil
3041                        start nil)
3042                (setq end (point))
3043                (forward-char 1))
3044              (setq resume (point)))
3045             (t                          ; no string anymore
3046              (setq start nil
3047                    continue nil)))
3048       (if start
3049           (setq contents (concat contents
3050                                  (if raw
3051                                      (buffer-substring start end)
3052                                    (po-extract-part-unquoted (current-buffer)
3053                                                              start end))))))
3054     (goto-char resume)
3055     contents))
3056
3057 (defun po-mark-python-string (start end keyword)
3058   "Mark the Python string, from START to END, with KEYWORD.
3059 If KEYWORD is '.', prefix the string with an empty string of the other type.
3060 Leave point after marked string."
3061   (cond ((string-equal keyword ".")
3062          (goto-char end)
3063          (save-excursion
3064            (goto-char start)
3065            (insert (cond ((= (following-char) ?\') "\"\"")
3066                          ((= (following-char) ?\") "''")
3067                          (t "??")))))
3068         (t (goto-char end)
3069            (insert ")")
3070            (save-excursion
3071              (goto-char start)
3072              (insert keyword "(")))))
3073 \f
3074 ;;; Miscellaneous features.
3075
3076 (defun po-help ()
3077   "Provide an help window for PO mode."
3078   (interactive)
3079   (po-with-temp-buffer
3080    (insert po-help-display-string)
3081    (goto-char (point-min))
3082    (save-window-excursion
3083      (switch-to-buffer (current-buffer))
3084      (delete-other-windows)
3085      (message (_"Type any character to continue"))
3086      (po-read-event))))
3087
3088 (defun po-undo ()
3089   "Undo the last change to the PO file."
3090   (interactive)
3091   (let ((buffer-read-only po-read-only))
3092     (undo))
3093   (po-compute-counters nil))
3094
3095 (defun po-statistics ()
3096   "Say how many entries in each category, and the current position."
3097   (interactive)
3098   (po-compute-counters t))
3099
3100 (defun po-validate ()
3101   "Use 'msgfmt' for validating the current PO file contents."
3102   (interactive)
3103   (let* ((dev-null
3104           (cond ((boundp 'null-device) null-device) ; since Emacs 20.3
3105                 ((memq system-type '(windows-nt windows-95)) "NUL")
3106                 (t "/dev/null")))
3107          (compilation-buffer-name-function
3108           (function (lambda (mode-name)
3109                       (concat "*" mode-name " validation*"))))
3110          (compile-command (concat po-msgfmt-program
3111                                  " --statistics -c -v -o " dev-null " "
3112                                  buffer-file-name)))
3113     (po-msgfmt-version-check)
3114     (compile compile-command)))
3115
3116 (defvar po-msgfmt-version-checked nil)
3117 (defun po-msgfmt-version-check ()
3118   "'msgfmt' from GNU gettext 0.10.36 or greater is required."
3119   (po-with-temp-buffer
3120     (or
3121      ;; Don't bother checking again.
3122      po-msgfmt-version-checked
3123
3124      (and
3125       ;; Make sure 'msgfmt' is available.
3126       (condition-case nil
3127           (call-process po-msgfmt-program
3128                         nil t nil "--verbose" "--version")
3129         (file-error nil))
3130
3131       ;; Make sure there's a version number in the output:
3132       ;; 0.11 or 0.10.36 or 0.11-pre1
3133       (progn (goto-char (point-min))
3134              (or (looking-at ".* \\([0-9]+\\)\\.\\([0-9]+\\)$")
3135                  (looking-at ".* \\([0-9]+\\)\\.\\([0-9]+\\)\\.\\([0-9]+\\)$")
3136                  (looking-at ".* \\([0-9]+\\)\\.\\([0-9]+\\)[-_A-Za-z0-9]+$")))
3137
3138       ;; Make sure the version is recent enough.
3139       (>= (string-to-number
3140            (format "%d%03d%03d"
3141                    (string-to-number (match-string 1))
3142                    (string-to-number (match-string 2))
3143                    (string-to-number (or (match-string 3) "0"))))
3144           010036)
3145
3146       ;; Remember the outcome.
3147       (setq po-msgfmt-version-checked t))
3148
3149      (error (_"'msgfmt' from GNU gettext 0.10.36 or greater is required")))))
3150
3151 (defun po-guess-archive-name ()
3152   "Return the ideal file name for this PO file in the central archives."
3153   (let ((filename (file-name-nondirectory buffer-file-name))
3154         start-of-header end-of-header package version team)
3155     (save-excursion
3156       ;; Find the PO file header entry.
3157       (goto-char (point-min))
3158       (re-search-forward po-any-msgstr-regexp)
3159       (setq start-of-header (match-beginning 0)
3160             end-of-header (match-end 0))
3161       ;; Get the package and version.
3162       (goto-char start-of-header)
3163       (if (re-search-forward "\n\
3164 \"Project-Id-Version: \\(GNU \\|Free \\)?\\([^\n ]+\\) \\([^\n ]+\\)\\\\n\"$"
3165            end-of-header t)
3166           (setq package (po-match-string 2)
3167                 version (po-match-string 3)))
3168       (if (or (not package) (string-equal package "PACKAGE")
3169               (not version) (string-equal version "VERSION"))
3170           (error (_"Project-Id-Version field does not have a proper value")))
3171       ;; File name version and Project-Id-Version must match
3172       (cond (;; A `filename' w/o package and version info at all
3173              (string-match "^[^\\.]*\\.po\\'" filename))
3174             (;; TP Robot compatible `filename': PACKAGE-VERSION.LL.po
3175              (string-match (concat (regexp-quote package)
3176                                    "-\\(.*\\)\\.[^\\.]*\\.po\\'") filename)
3177              (if (not (equal version (po-match-string 1 filename)))
3178                  (error (_"\
3179 Version mismatch: file name: %s; header: %s.\n\
3180 Adjust Project-Id-Version field to match file name and try again")
3181                         (po-match-string 1 filename) version))))
3182       ;; Get the team.
3183       (if (stringp po-team-name-to-code)
3184           (setq team po-team-name-to-code)
3185         (goto-char start-of-header)
3186         (if (re-search-forward "\n\
3187 \"Language-Team: \\([^ ].*[^ ]\\) <.+@.+>\\\\n\"$"
3188                                end-of-header t)
3189             (let ((name (po-match-string 1)))
3190               (if name
3191                   (let ((pair (assoc name po-team-name-to-code)))
3192                     (if pair
3193                         (setq team (cdr pair))
3194                       (setq team (read-string (format "\
3195 Team name '%s' unknown.  What is the team code? "
3196                                                       name)))))))))
3197       (if (or (not team) (string-equal team "LL"))
3198           (error (_"Language-Team field does not have a proper value")))
3199       ;; Compose the name.
3200       (concat package "-" version "." team ".po"))))
3201
3202 (defun po-guess-team-address ()
3203   "Return the team address related to this PO file."
3204   (let (team)
3205     (save-excursion
3206       (goto-char (point-min))
3207       (re-search-forward po-any-msgstr-regexp)
3208       (goto-char (match-beginning 0))
3209       (if (re-search-forward
3210            "\n\"Language-Team: +\\(.*<\\(.*\\)@.*>\\)\\\\n\"$"
3211            (match-end 0) t)
3212           (setq team (po-match-string 2)))
3213       (if (or (not team) (string-equal team "LL"))
3214           (error (_"Language-Team field does not have a proper value")))
3215       (po-match-string 1))))
3216
3217 (defun po-send-mail ()
3218   "Start composing a letter, possibly including the current PO file."
3219   (interactive)
3220   (let* ((team-flag (y-or-n-p
3221                      (_"\
3222 Write to your team?  ('n' if writing to the Translation Project robot) ")))
3223          (address (if team-flag
3224                       (po-guess-team-address)
3225                     po-translation-project-address)))
3226     (if (not (y-or-n-p (_"Include current PO file in mail? ")))
3227         (apply po-compose-mail-function address
3228                (read-string (_"Subject? ")) nil)
3229       (if (buffer-modified-p)
3230           (error (_"The file is not even saved, you did not validate it.")))
3231       (if (and (y-or-n-p (_"You validated ('V') this file, didn't you? "))
3232                (or (zerop po-untranslated-counter)
3233                    (y-or-n-p
3234                     (format (_"%d entries are untranslated, include anyway? ")
3235                             po-untranslated-counter)))
3236                (or (zerop po-fuzzy-counter)
3237                    (y-or-n-p
3238                     (format (_"%d entries are still fuzzy, include anyway? ")
3239                             po-fuzzy-counter)))
3240                (or (zerop po-obsolete-counter)
3241                    (y-or-n-p
3242                     (format (_"%d entries are obsolete, include anyway? ")
3243                             po-obsolete-counter))))
3244           (let ((buffer (current-buffer))
3245                 (name (po-guess-archive-name))
3246                 (transient-mark-mode nil)
3247                 (coding-system-for-read buffer-file-coding-system)
3248                 (coding-system-for-write buffer-file-coding-system))
3249             (apply po-compose-mail-function address
3250                    (if team-flag
3251                        (read-string (_"Subject? "))
3252                      (format "%s %s" po-translation-project-mail-label name))
3253                    nil)
3254             (goto-char (point-min))
3255             (re-search-forward
3256              (concat "^" (regexp-quote mail-header-separator) "\n"))
3257             (save-excursion
3258               (insert-buffer buffer)
3259               (shell-command-on-region
3260                (region-beginning) (region-end)
3261                (concat po-gzip-uuencode-command " " name ".gz") t))))))
3262   (message ""))
3263
3264 (defun po-confirm-and-quit ()
3265   "Confirm if quit should be attempted and then, do it.
3266 This is a failsafe.  Confirmation is asked if only the real quit would not."
3267   (interactive)
3268   (if (po-check-all-pending-edits)
3269       (progn
3270         (if (or (buffer-modified-p)
3271                 (> po-untranslated-counter 0)
3272                 (> po-fuzzy-counter 0)
3273                 (> po-obsolete-counter 0)
3274                 (y-or-n-p (_"Really quit editing this PO file? ")))
3275             (po-quit))
3276         (message ""))))
3277
3278 (defun po-quit ()
3279   "Save the PO file and kill buffer.
3280 However, offer validation if appropriate and ask confirmation if untranslated
3281 strings remain."
3282   (interactive)
3283   (if (po-check-all-pending-edits)
3284       (let ((quit t))
3285         ;; Offer validation of newly modified entries.
3286         (if (and (buffer-modified-p)
3287                  (not (y-or-n-p
3288                        (_"File was modified; skip validation step? "))))
3289             (progn
3290               (message "")
3291               (po-validate)
3292               ;; If we knew that the validation was all successful, we should
3293               ;; just quit.  But since we do not know yet, as the validation
3294               ;; might be asynchronous with PO mode commands, the safest is to
3295               ;; stay within PO mode, even if this implies that another
3296               ;; 'po-quit' command will be later required to exit for true.
3297               (setq quit nil)))
3298         ;; Offer to work on untranslated entries.
3299         (if (and quit
3300                  (or (> po-untranslated-counter 0)
3301                      (> po-fuzzy-counter 0)
3302                      (> po-obsolete-counter 0))
3303                  (not (y-or-n-p
3304                        (_"Unprocessed entries remain; quit anyway? "))))
3305             (progn
3306               (setq quit nil)
3307               (po-auto-select-entry)))
3308         ;; Clear message area.
3309         (message "")
3310         ;; Or else, kill buffers and quit for true.
3311         (if quit
3312             (progn
3313               (save-buffer)
3314               (kill-buffer (current-buffer)))))))
3315
3316 ;; XEmacs addition
3317 ;; When `po-mode' sometime is autoloaded, change this to autoload-only.
3318 (add-to-list 'auto-mode-alist '("\\.po\\'\\|\\.po\\." . po-mode))
3319
3320 (provide 'po-mode)
3321
3322 ;;; po-mode.el ends here