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