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