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