-
Notifications
You must be signed in to change notification settings - Fork 7
/
cat2rtf.l
447 lines (373 loc) · 12.1 KB
/
cat2rtf.l
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/*
cat2rtf.l: cat to RTF converter specification
(c) 1993 by Harald Schlangmann
Permission is granted to use this code. Send additions
and bug reports to my address below.
v1.0 Harald Schlangmann, July 20 1993
schlangm@informatik.uni-muenchen.de
v1.1 Bold style x^H{x^H}* implemented.
v2.0 Carl Lindberg lindberg@mac.com
Added blank line suppressing.
v2.1 Added links.
v2.2 Added RTF hyperlinks
*/
#include <string.h>
#if defined(__APPLE__) && !defined(NeXT)
#define RTF_HYPERLINKS
#endif
#define BOLDFLAG 1
#define ULINEFLAG 2
int flags = 0, neededflags = 0;
#define SETB neededflags |= BOLDFLAG
#define UNSETB neededflags &= ~BOLDFLAG
#define SETU neededflags |= ULINEFLAG
#define UNSETU neededflags &= ~ULINEFLAG
/*
* Default settings, may be changed using options...
*/
static char *startBold = "\n\\b ";
static char *stopBold = "\n\\b0 ";
static char *startULine = "\n\\ul ";
static char *stopULine = "\n\\ulnone ";
static char *startHeader = "\n\\f1 ";
static char *stopHeader = "\n\\f0 ";
static int addLinks = 0;
static int markHeaders = 0; /* Mark headers with Helvetica */
/*
* 'lineCount' is here to squeeze multiple-blank lines (like 'more -s'
* does with the traditional nroff output). By default, a max of 3
* consecutive blank lines are allowed. A value of -1 means to not
* squeeze lines at all. -CEL
*/
static int lineCount = 0;
static int maxLineCount = 3;
/* Decode a UTF8 sequence to return the unicode number */
static unsigned decodeUTF8(unsigned char *buf, yy_size_t len)
{
int n = buf[0] & (0x7f >> len);
yy_size_t i;
for (i=1; i<len; i++)
n = (n << 6) | (buf[i] & 0x3f);
return (unsigned)n;
}
static void emitPreamble(void) {
fputs("{\\rtf0\\ansi{\\fonttbl\\f0\\fmodern Courier;\\f1"
"\\fswiss Helvetica;}\n" "\\paperw14640\n" "\\paperh9600\n"
"\\margl120\n" "\\margr120\n"
"{\\colortbl;\\red0\\green0\\blue0;}\n"
"\\pard\\tx1140\\tx2300\\tx3440\\tx4600"
"\\tx5760\\tx6900\\tx8060\\tx9200"
"\\tx10360\\tx11520\\f0\\b0\\i0\\ulnone"
"\\fs24\\fc1\\cf1 ",stdout);
}
static void emitPostamble(void) {
fputs("\n}\n",stdout);
}
#define adjust() if( neededflags!=flags ) _adjust()
static void _adjust(void) {
if( (flags^neededflags)&ULINEFLAG )
fputs(neededflags&ULINEFLAG?
startULine:stopULine,stdout);
if( (flags^neededflags)&BOLDFLAG )
fputs(neededflags&BOLDFLAG?
startBold:stopBold,stdout);
flags = neededflags;
}
/*
* emitChar escapes RTF-special characters...
*/
static void emitChar(int ch) {
adjust();
if (ch=='\n') {
if (maxLineCount > 0 && lineCount > maxLineCount)
{
// Squeeze the blank line -- don't output it.
return;
}
lineCount++;
}
else lineCount = 0;
if( ch=='\n'||ch=='{'||ch=='}'||ch=='\\' )
fputc('\\',stdout);
fputc(ch,stdout);
}
static void emitChars(char *string, yy_size_t len)
{
yy_size_t i;
for (i=0; i<len; i++)
emitChar(string[i]);
}
/*
* ...emitString doesn't!
*/
static void emitString(char *string) {
adjust();
lineCount = 0;
fputs(string,stdout);
}
static void emitBackspacedLetters(char *charblock, yy_size_t lengthLeft, int doBold)
{
/* If there's a trailing backspace, then both letters are deleted, so print nothing */
if (lengthLeft >= 4 && charblock[3] == '\010')
return;
/* If the characters are equal, they are printed on top of each other, so make it bold */
if( charblock[0] == charblock[2] ) {
if (doBold) SETB;
emitChar(charblock[0]);
if (doBold) UNSETB;
}
/* Otherwise, just emit the second character. */
else {
#ifdef DEBUGBACKSPACE
fprintf(stderr, "Unknown backspace pair %c and %c\n", charblock[0], charblock[2]);
#endif
emitChar(charblock[2]);
}
}
static void emitBackspacedText(char *text, yy_size_t length)
{
yy_size_t i=0;
while (i < length) {
if ((i < (length-1)) && text[i+1] == '\010') {
emitBackspacedLetters(&text[i], 3, 0);
i+=3;
}
else {
emitChar(text[i]);
i++;
}
}
}
/*
* RTF has a "u" directive, which is followed by the unicode number
* (as a signed 16-bit value). For compatibility with readers that
* do not support this, a "uc" directive is supported, where the
* argument specifies the number of characters after the "u" to
* ignore. The idea is to put it alternate text, so that readers
* which do not know "uc" or "u" will show the other (ASCII) text
* instead. We just show a '?'. Put both inside a {...} section
* so that the scope of the "uc" setting is limited.
*/
static void emitUnicode(unsigned charNum)
{
short rtfVal = charNum;
char rtfBuf[20];
sprintf(rtfBuf, "{\\uc1\\u%hd?}", rtfVal);
emitString(rtfBuf);
}
ALLBUTUL [^\n_\010]
NEEDQUOTE [\\{}]
VERBATIM [^\n_\010\x1B( \t\\{}\xC2-\xF4]
UPPER [A-Z]
UPPERCONT [-/A-Z0-9 \t()]
UPPERBS {UPPER}\010{UPPER}
UPPERBSCONT ({UPPERBS}|[ \t()])
UTF8START [\xC2-\xF4]
UTF8CONT [\x80-\xBF]
UTF8SEQ {UTF8START}({UTF8CONT}{1,3})
SGRSTART \x1B\[
%option 8bit
%option debug
%option noyywrap
%option noinput
%option prefix="cat2rtf"
%x FIRSTLINE
%%
/*
* Start state FIRSTLINE is used to treat the first non-empty
* line special. (First line contains header).
*/
/* Some X.org X11 pages have a weird #pragma at the start; strip it out. */
<FIRSTLINE>"#pragma".*\n {}
<FIRSTLINE>. SETB; emitChar(yytext[0]);
<FIRSTLINE>.\n {
SETB;
emitChar(yytext[0]);
emitChar('\n');
BEGIN(INITIAL);
UNSETB;
}
<FIRSTLINE>\n UNSETB; emitChar('\n');
/* Part of the X11 thing gets put on a separate line by nroff, sigh. */
^"vate/var/tmp/X11".*\n {}
/*
* Put a NeXTHelpLink next to likely looking links to other man pages if desired
*/
[_a-zA-Z][-a-zA-Z0-9._]*(-[ \t\n]+[-a-zA-Z0-9._]+)?[ \t\n]*"("[1-9n][a-zA-Z]?")" {
if (addLinks)
{
char namebuf[yyleng+1];
int i;
strcpy(namebuf, yytext);
for (i=0; i<yyleng; i++)
if (namebuf[i] == '\n') namebuf[i] = ' ';
#ifdef RTF_HYPERLINKS
emitString("{\\field{\\*\\fldinst{HYPERLINK \"manpage:");
emitString(namebuf);
emitString("\"}}{\\fldrslt ");
emitChars(yytext, yyleng);
emitString("}}");
#else
{
static int linkNum = 763; //seems to start around here
char numbuf[10];
emitChars(yytext, yyleng);
sprintf(numbuf, "%d", linkNum+=3); //for some reason, Edit.app increments by 3
emitString("{{\\NeXTHelpLink");
emitString(numbuf);
emitString(" \\markername ");
emitString(";\\linkFilename manpage:"); // linkFilename is the parameter to set
emitString(namebuf);
emitString(";\\linkMarkername ");
emitString(";}\n\\254}");
}
#endif
}
}
/*
* Non-empty, all-uppercase lines are treated as headers
*/
^{UPPER}{UPPERCONT}*$ {
SETB;
if (markHeaders) emitString(startHeader);
emitString(yytext);
emitString("\\\n");
if (markHeaders) emitString(stopHeader);
UNSETB;
}
/* Similar for all-uppercase lines that use backspace for bolding */
^{UPPERBS}{UPPERBSCONT}*$ {
SETB;
if (markHeaders) emitString(startHeader);
emitBackspacedText(yytext, yyleng);
emitString("\\\n");
if (markHeaders) emitString(stopHeader);
UNSETB;
emitChar('\n');
}
/*
* nroff +-
*/
"+"\010_ emitChar('\321');
/*
* underline (part 1)
*/
{ALLBUTUL}\010_ {
SETU;
emitChar(yytext[0]);
UNSETU;
}
/*
* nroff bullets
*/
o\010"+" emitChar('\267');
"+"\010o emitChar('\267');
o\010o\010"+"\010"+" emitChar('\267');
"+"\010"+\010"o\010o emitChar('\267');
/*
* underline (part 2)
*/
_\010{ALLBUTUL} {
SETU;
emitChar(yytext[2]);
UNSETU;
}
/*
* handle further BS combinations
*/
.\010.\010? {
emitBackspacedLetters(yytext, yyleng, 1);
}
/* Same idea but with UTF-8 characters */
{UTF8SEQ}\010{UTF8SEQ}\010? {
if (yytext[yyleng-1] != '\010') {
char *backspace = index(yytext, '\010');
if (backspace != NULL) {
emitUnicode(decodeUTF8((unsigned char *)backspace+1, (yyleng - (backspace-yytext) - 1)));
}
}
}
/* If we find a UTF8 sequence, decode it */
{UTF8SEQ} {
emitUnicode(decodeUTF8((unsigned char *)yytext, yyleng));
}
/* Some versions of nroff/grotty use SGR (ANSI) escape sequences instead of the backspace hacks */
{SGRSTART}0?m UNSETU;UNSETB;
{SGRSTART}1m SETB;
{SGRSTART}[347]m SETU;
{SGRSTART}(21|22)m UNSETB;
{SGRSTART}(23|24|27)m UNSETU;
{SGRSTART}[0-9;]+m {/*ignore any other codes*/}
/*
group characters in VERBATIM to make this
filter faster...
*/
[ \t]+ emitString(yytext);
{VERBATIM}+/[^\010] emitString(yytext);
/*
remaining specials
*/
\n emitChar('\n');
. emitChar(yytext[0]);
%%
static void usage() {
fprintf(stderr,"Usage: cat2rtf [-gil] [-s <num>| -S] [<filename>]\n"
"\tTranslate output of (g)nroff to RTF. If no\n"
"\t<filename> is given, cat2rtf reads stdin.\n"
"\tOption -g uses gray for bold characters,\n"
"\toption -i uses italic characters for underlining.\n"
"\toption -l will add NeXT help link buttons.\n"
"\toption -s will allow only <num> consecutive blank lines,\n"
"\toption -S will not do any squeezing of blank lines.\n"
"\tRTF output is sent to stdout.\n");
exit(1);
}
int main(int argc, char *argv[])
{
int c;
yy_flex_debug = 0;
while ((c = getopt(argc, argv, "dgGiISs:lH")) != EOF)
{
switch( c ) {
case 'd':
yy_flex_debug = 1;
break;
case 'g':
case 'G':
startBold = "\n\\gray333 ";
stopBold = "\n\\gray0 ";
break;
case 'i':
case 'I':
startULine = "\n\\i ";
stopULine = "\n\\i0 ";
break;
case 's':
maxLineCount = atoi(optarg);
break;
case 'S':
maxLineCount = -1;
break;
case 'l':
addLinks = 1;
break;
case 'H':
markHeaders = 1;
break;
case '?':
default:
usage();
}
}
if( optind < argc )
yyin = fopen(argv[optind], "r");
else
yyin = stdin;
emitPreamble();
BEGIN(FIRSTLINE);
yylex();
emitPostamble();
/* Shuts up a compiler warning */
if (0) unput('h');
return 0;
}