Fix the fix to really close 181
[sxemacs] / lib-src / make-msgfile.c
1 /*
2
3    PROPOSAL FOR HOW THIS ALL OUGHT TO WORK
4    this isn't implemented yet, but this is the plan-in-progress
5
6    In general, it's accepted that the best way to internationalize is for all
7    messages to be referred to by a symbolic name (or number) and come out of a
8    table or tables, which are easy to change.
9
10    However, with Emacs, we've got the task of internationalizing a huge body
11    of existing code, which already contains messages internally.
12
13    For the C code we've got two options:
14
15     - Use a Sun-like gettext() form, which takes an "english" string which
16       appears literally in the source, and uses that as a hash key to find
17       a translated string;
18     - Rip all of the strings out and put them in a table.
19
20    In this case, it's desirable to make as few changes as possible to the C
21    code, to make it easier to merge the code with the FSF version of emacs
22    which won't ever have these changes made to it.  So we should go with the
23    former option.
24
25    The way it has been done (between 19.8 and 19.9) was to use gettext(), but
26    *also* to make massive changes to the source code.  The goal now is to use
27    gettext() at run-time and yet not require a textual change to every line
28    in the C code which contains a string constant.  A possible way to do this
29    is described below.
30
31    (gettext() can be implemented in terms of catgets() for non-Sun systems, so
32    that in itself isn't a problem.)
33
34    For the Lisp code, we've got basically the same options: put everything in
35    a table, or translate things implicitly.
36
37    Another kink that lisp code introduces is that there are thousands of third-
38    party packages, so changing the source for all of those is simply not an
39    option.
40
41    Is it a goal that if some third party package displays a message which is
42    one we know how to translate, then we translate it?  I think this is a
43    worthy goal.  It remains to be seen how well it will work in practice.
44
45    So, we should endeavor to minimize the impact on the lisp code.  Certain
46    primitive lisp routines (the stuff in lisp/prim/, and especially in
47    cmdloop.el and minibuf.el) may need to be changed to know about translation,
48    but that's an ideologically clean thing to do because those are considered
49    a part of the emacs substrate.
50
51    However, if we find ourselves wanting to make changes to, say, RMAIL, then
52    something has gone wrong.  (Except to do things like remove assumptions
53    about the order of words within a sentence, or how pluralization works.)
54
55    There are two parts to the task of displaying translated strings to the
56    user: the first is to extract the strings which need to be translated from
57    the sources; and the second is to make some call which will translate those
58    strings before they are presented to the user.
59
60    The old way was to use the same form to do both, that is, GETTEXT() was both
61    the tag that we searched for to build a catalog, and was the form which did
62    the translation.  The new plan is to separate these two things more: the
63    tags that we search for to build the catalog will be stuff that was in there
64    already, and the translation will get done in some more centralized, lower
65    level place.
66
67    This program (make-msgfile.c) addresses the first part, extracting the
68    strings.
69
70    For the emacs C code, we need to recognize the following patterns:
71
72      message ("string" ... )
73      error ("string")
74      report_file_error ("string" ... )
75      signal_simple_error ("string" ... )
76      signal_simple_error_2 ("string" ... )
77
78      build_translated_string ("string")
79      #### add this and use it instead of build_string() in some places.
80
81      yes_or_no_p ("string" ... )
82      #### add this instead of funcalling Qyes_or_no_p directly.
83
84      barf_or_query_if_file_exists       #### restructure this
85      check all callers of Fsignal       #### restructure these
86      signal_error (Qerror ... )         #### change all of these to error()
87
88      And we also parse out the `interactive' prompts from DEFUN() forms.
89
90      #### When we've got a string which is a candidate for translation, we
91      should ignore it if it contains only format directives, that is, if
92      there are no alphabetic characters in it that are not a part of a `%'
93      directive.  (Careful not to translate either "%s%s" or "%s: ".)
94
95    For the emacs Lisp code, we need to recognize the following patterns:
96
97      (message "string" ... )
98      (error "string" ... )
99      (format "string" ... )
100      (read-from-minibuffer "string" ... )
101      (read-shell-command "string" ... )
102      (y-or-n-p "string" ... )
103      (yes-or-no-p "string" ... )
104      (read-file-name "string" ... )
105      (temp-minibuffer-message "string")
106      (query-replace-read-args "string" ... )
107
108    I expect there will be a lot like the above; basically, any function which
109    is a commonly used wrapper around an eventual call to `message' or
110    `read-from-minibuffer' needs to be recognized by this program.
111
112      (dgettext "domain-name" "string")          #### do we still need this?
113
114      things that should probably be restructured:
115        `princ' in cmdloop.el
116        `insert' in debug.el
117        face-interactive
118        help.el, syntax.el all messed up
119
120    Menu descriptors: one way to extract the strings in menu labels would be
121    to teach this program about "^(defvar .*menu\n" forms; that's probably
122    kind of hard, though, so perhaps a better approach would be to make this
123    program recognize lines of the form
124
125      "string" ... ;###translate
126
127    where the magic token ";###translate" on a line means that the string
128    constant on this line should go into the message catalog.  This is analogous
129    to the magic ";###autoload" comments, and to the magic comments used in the
130    EPSF structuring conventions.
131
132   -----
133   So this program manages to build up a catalog of strings to be translated.
134   To address the second part of the problem, of actually looking up the
135   translations, there are hooks in a small number of low level places in
136   emacs.
137
138   Assume the existence of a C function gettext(str) which returns the
139   translation of `str' if there is one, otherwise returns `str'.
140
141   - message() takes a char* as its argument, and always filters it through
142     gettext() before displaying it.
143
144   - errors are printed by running the lisp function `display-error' which
145     doesn't call `message' directly (it princ's to streams), so it must be
146     carefully coded to translate its arguments.  This is only a few lines
147     of code.
148
149   - Fread_minibuffer_internal() is the lowest level interface to all minibuf
150     interactions, so it is responsible for translating the value that will go
151     into Vminibuf_prompt.
152
153   - Fpopup_menu filters the menu titles through gettext().
154
155     The above take care of 99% of all messages the user ever sees.
156
157   - The lisp function temp-minibuffer-message translates its arg.
158
159   - query-replace-read-args is funny; it does
160       (setq from (read-from-minibuffer (format "%s: " string) ... ))
161       (setq to (read-from-minibuffer (format "%s %s with: " string from) ... ))
162
163     What should we do about this?  We could hack query-replace-read-args to
164     translate its args, but might this be a more general problem?  I don't
165     think we ought to translate all calls to format.  We could just change
166     the calling sequence, since this is odd in that the first %s wants to be
167     translated but the second doesn't.
168
169   Solving the "translating too much" problem:
170   The concern has been raised that in this situation:
171    - "Help" is a string for which we know a translation;
172    - someone visits a file called Help, and someone does something
173      contrived like (error buffer-file-name)
174   then we would display the translation of Help, which would not be correct.
175   We can solve this by adding a bit to Lisp_String objects which identifies
176   them as having been read as literal constants from a .el or .elc file (as
177   opposed to having been constructed at run time as it would in the above
178   case.)  To solve this:
179
180     - Fmessage() takes a lisp string as its first argument.
181       If that string is a constant, that is, was read from a source file
182       as a literal, then it calls message() with it, which translates.
183       Otherwise, it calls message_no_translate(), which does not translate.
184
185     - Ferror() (actually, Fsignal() when condition is Qerror) works similarly.
186 */
187
188 /* Scan specified C and Lisp files, extracting the following messages:
189
190      C files:
191         GETTEXT (...)
192         DEFER_GETTEXT (...)
193         DEFUN interactive prompts
194      Lisp files:
195         (gettext ...)
196         (dgettext "domain-name" ...)
197         (defer-gettext ...)
198         (interactive ...)
199
200   The arguments given to this program are all the C and Lisp source files
201   of GNU Emacs.  .el and .c files are allowed.  There is no support for .elc
202   files at this time, but they may be specified; the corresponding .el file
203   will be used.  Similarly, .o files can also be specified, and the corresponding
204   .c file will be used.  This helps the makefile pass the correct list of files.
205
206   The results, which go to standard output or to a file specified with -a or -o
207   (-a to append, -o to start from nothing), are quoted strings wrapped in
208   gettext(...).  The results can be passed to xgettext to produce a .po message
209   file.
210 */
211
212 #include <stdio.h>
213 #include <string.h>
214
215 #define LINESIZE 256
216 #define GET_LINE        fgets (line, LINESIZE, infile)
217 #define CHECK_EOL(p)    if (*(p) == '\0')  (p) = GET_LINE
218 #define SKIP_BLANKS(p)  while ((*p) == ' ' || (*p) == '\t')  (p)++
219
220 enum filetype { C_FILE, LISP_FILE, INVALID_FILE };
221 /* some brain-dead headers define this ... */
222 #undef FALSE
223 #undef TRUE
224 enum boolean { FALSE, TRUE };
225
226 FILE *infile;
227 FILE *outfile;
228 char line[LINESIZE];
229
230 void scan_file(char *filename);
231 void process_C_file(void);
232 void process_Lisp_file(void);
233 char *copy_up_to_paren(register char *p);
234 char *copy_quoted_string(register char *p);
235 enum boolean no_interactive_prompt(register char *q);
236 char *skip_blanks(register char *p);
237
238 main(int argc, char *argv[])
239 {
240         register int i;
241
242         outfile = stdout;
243
244         /* If first two args are -o FILE, output to FILE. */
245         i = 1;
246         if (argc > i + 1 && strcmp(argv[i], "-o") == 0) {
247                 outfile = fopen(argv[++i], "w");
248                 ++i;
249         }
250         /* ...Or if args are -a FILE, append to FILE. */
251         if (argc > i + 1 && strcmp(argv[i], "-a") == 0) {
252                 outfile = fopen(argv[++i], "a");
253                 ++i;
254         }
255         if (!outfile) {
256                 fprintf(stderr, "Unable to open output file %s\n", argv[--i]);
257                 return;
258         }
259
260         for (; i < argc; i++)
261                 scan_file(argv[i]);
262
263         return 0;
264 }
265
266 void scan_file(char *filename)
267 {
268         enum filetype type = INVALID_FILE;
269         register char *p = filename + strlen(filename);
270
271         if (strcmp(p - 4, ".elc") == 0) {
272                 *--p = '\0';    /* Use .el file instead */
273                 type = LISP_FILE;
274         } else if (strcmp(p - 3, ".el") == 0)
275                 type = LISP_FILE;
276         else if (strcmp(p - 2, ".o") == 0) {
277                 *--p = 'c';     /* Use .c file instead */
278                 type = C_FILE;
279         } else if (strcmp(p - 2, ".c") == 0)
280                 type = C_FILE;
281
282         if (type == INVALID_FILE) {
283                 fprintf(stderr, "File %s being ignored\n", filename);
284                 return;
285         }
286         infile = fopen(filename, "r");
287         if (!infile) {
288                 fprintf(stderr, "Unable to open input file %s\n", filename);
289                 return;
290         }
291
292         fprintf(outfile, "/* %s */\n", filename);
293         if (type == C_FILE)
294                 process_C_file();
295         else
296                 process_Lisp_file();
297         fputc('\n', outfile);
298
299         fclose(infile);
300 }
301
302 void process_C_file(void)
303 {
304         register char *p;
305         char *gettext, *defun;
306
307         while (p = GET_LINE) {
308                 gettext = strstr(p, "GETTEXT");
309                 defun = strstr(p, "DEFUN");
310                 if (gettext || defun) {
311                         if (gettext) {
312                                 p = gettext;
313                                 p += 7; /* Skip over "GETTEXT" */
314                         } else if (defun) {
315                                 p = defun;
316                                 p += 5; /* Skip over "DEFUN" */
317                         }
318
319                         p = skip_blanks(p);
320                         if (*p++ != '(')
321                                 continue;
322
323                         if (defun) {
324                                 register int i;
325
326                                 for (i = 0; i < 5; i++) /* Skip over commas to doc string */
327                                         while (*p++ != ',')
328                                                 CHECK_EOL(p);
329                                 if (*p == '\n')
330                                         p = GET_LINE;
331                         }
332
333                         p = skip_blanks(p);
334                         if (*p != '\"') /* Make sure there is a quoted string */
335                                 continue;
336
337                         if (defun && no_interactive_prompt(p))
338                                 continue;
339
340                         fprintf(outfile, "gettext(");
341                         if (gettext)
342                                 p = copy_up_to_paren(p);
343                         else
344                                 p = copy_quoted_string(p);
345                         fprintf(outfile, ")\n");
346                 }
347         }
348 }
349
350 void process_Lisp_file(void)
351 {
352         register char *p;
353         char *gettext, *interactive;
354         enum boolean dgettext = FALSE;
355
356         while (p = GET_LINE) {
357                 gettext = strstr(p, "gettext");
358                 interactive = strstr(p, "(interactive");
359                 if (gettext || interactive) {
360                         if (!interactive)
361                                 p = gettext;
362                         else if (!gettext)
363                                 p = interactive;
364                         else if (gettext < interactive) {
365                                 p = gettext;
366                                 interactive = NULL;
367                         } else {
368                                 p = interactive;
369                                 gettext = NULL;
370                         }
371
372                         if (gettext) {
373                                 if (p > line && *(p - 1) == 'd')
374                                         dgettext = TRUE;
375                                 p += 7; /* Skip over "gettext" */
376                         } else
377                                 p += 12;        /* Skip over "(interactive" */
378
379                         p = skip_blanks(p);
380                         if (*p != '\"') /* Make sure there is a quoted string */
381                                 continue;
382
383                         if (dgettext) { /* Skip first quoted string (domain name) */
384                                 while (*++p != '"') ;   /* null statement */
385                                 ++p;
386                                 p = skip_blanks(p);
387                                 if (*p != '\"') /* Check for second quoted string (message) */
388                                         continue;
389                         }
390
391                         if (interactive && no_interactive_prompt(p))
392                                 continue;
393
394                         fprintf(outfile, "gettext(");
395                         p = copy_up_to_paren(p);
396                         fprintf(outfile, ")\n");
397                 }
398         }
399 }
400
401 /* Assuming p points to some character beyond an opening parenthesis, copy
402    everything to outfile up to but not including the closing parenthesis.
403 */
404 char *copy_up_to_paren(register char *p)
405 {
406         for (;;) {
407                 SKIP_BLANKS(p); /* We don't call skip_blanks() in order to */
408                 CHECK_EOL(p);   /* preserve blanks at the beginning of the line */
409                 if (*p == ')')
410                         break;
411
412                 if (*p == '\"')
413                         p = copy_quoted_string(p);
414                 else
415                         fputc(*p++, outfile);
416         }
417         return p;
418 }
419
420 /* Assuming p points to a quote character, copy the quoted string to outfile.
421 */
422 char *copy_quoted_string(register char *p)
423 {
424         do {
425                 if (*p == '\\')
426                         fputc(*p++, outfile);
427                 fputc(*p++, outfile);
428                 CHECK_EOL(p);
429         } while (*p != '\"');
430
431         fputc(*p++, outfile);
432         return p;
433 }
434
435 /* Return TRUE if the interactive specification consists only
436    of code letters and no prompt.
437 */
438 enum boolean no_interactive_prompt(register char *q)
439 {
440         while (++q, *q == '*' || *q == '@') ;   /* null statement */
441         if (*q == '\"')
442                 return TRUE;
443       skip_code_letter:
444         if (*++q == '\"')
445                 return TRUE;
446         if (*q == '\\' && *++q == 'n') {
447                 ++q;
448                 goto skip_code_letter;
449         }
450         return FALSE;
451 }
452
453 char *skip_blanks(register char *p)
454 {
455         while (*p == ' ' || *p == '\t' || *p == '\n') {
456                 p++;
457                 CHECK_EOL(p);
458         }
459         return p;
460 }