-
Notifications
You must be signed in to change notification settings - Fork 0
/
txt2tags-1.2.py
executable file
·2120 lines (1812 loc) · 66.6 KB
/
txt2tags-1.2.py
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# txt2tags - generic text conversion tool
# http://txt2tags.sf.net
#
# Copyright 2001, 2002 Aurélio Marinho Jargas
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You have received a copy of the GNU General Public License along
# with this program, on the COPYING file.
#
# please, don't look at this code, it's ugly!
# i'll try to make it better on the next releases
import re, string, os, sys, getopt, traceback
from time import strftime,time,localtime
my_url = 'http://txt2tags.sf.net'
my_email = '[email protected]'
my_version = '1.2'
DEBUG = 0 # do not edit here, please use --debug
targets = ['txt', 'sgml', 'html', 'pm6', 'mgp', 'moin', 'man', 'tex']
FLAGS = {'noheaders':0,'enumtitle':0,'maskemail':0, 'stdout':0,
'toconly' :0,'toc' :0,'gui' :0, 'fixme' :0}
regex = {}
TAGS = {}
rules = {}
CMDLINE = ''
currdate = strftime('%Y%m%d',localtime(time())) # ISO current date
splitlevel = '' ; lang = 'english'
doctype = outfile = ''
pipefileid = '-'
has_obsolete = has_fixed = 0
#my_version = my_version + '-dev' + currdate[4:] # devel!
# global vars for doClose*()
quotedepth = []
listindent = []
listids = []
subarea = None
tableborder = 0
versionstr = "txt2tags version %s <%s>"%(my_version,my_url)
usage = """
%s
usage: txt2tags -t <type> [OPTIONS] file.t2t
txt2tags -t html -s <split level> -l <lang> file.t2t
-t, --type target document type. actually supported:
%s
--stdout by default, the output is written to file.<type>
with this option, STDOUT is used (no files written)
--noheaders suppress header, title and footer information
--enumtitle enumerate all title lines as 1, 1.1, 1.1.1, etc
--maskemail hide email from spam robots. [email protected] turns to <x (a) y z>
--toc add TOC (Table of Contents) to target document
--toconly print document TOC and exit
--gui invoke Graphical Tk Interface
--fixme temporary option to fix obsoleted structures
-h, --help print this help information and exit
-V, --version print program version and exit
extra options for HTML target (needs sgml-tools):
--split split documents. values: 0, 1, 2 (default 0)
--lang document language (default english)
"""%(versionstr, re.sub(r"[]'[]",'',repr(targets)))
# here is all the target's templates
# you may edit them to fit your needs
# - the %(HEADERn)s strings represent the Header lines
# - use %% to represent a literal %
#
HEADER_TEMPLATE = {
'txt': """\
%(HEADER1)s
%(HEADER2)s
%(HEADER3)s
""",
'sgml': """\
<!doctype linuxdoc system>
<article>
<title>%(HEADER1)s
<author>%(HEADER2)s
<date>%(HEADER3)s
""",
#TODO (peter valach) <meta http-equiv="Content-Type"
# content="text/html; charset=iso-8859-2">
'html': """\
<HTML>
<HEAD><TITLE>%(HEADER1)s</TITLE></HEAD>
<BODY BGCOLOR="white" TEXT="black">
<P ALIGN="center"><CENTER><H1>%(HEADER1)s</H1>
<FONT SIZE=4>
<I>%(HEADER2)s</I><BR>
%(HEADER3)s
</FONT></CENTER>
""",
# TODO man section 1 is hardcoded...
'man': """\
.TH "%(HEADER1)s" 1 %(HEADER3)s "%(HEADER2)s"
""",
# TODO style to <HR>
'pm6': """\
<PMTags1.0 win><C-COLORTABLE ("Preto" 1 0 0 0)
><@Normal=
<FONT "Times New Roman"><CCOLOR "Preto"><SIZE 11>
<HORIZONTAL 100><LETTERSPACE 0><CTRACK 127><CSSIZE 70><C+SIZE 58.3>
<C-POSITION 33.3><C+POSITION 33.3><P><CBASELINE 0><CNOBREAK 0><CLEADING -0.05>
<GGRID 0><GLEFT 7.2><GRIGHT 0><GFIRST 0><G+BEFORE 7.2><G+AFTER 0>
<GALIGNMENT "justify"><GMETHOD "proportional"><G& "ENGLISH">
<GPAIRS 12><G%% 120><GKNEXT 0><GKWIDOW 0><GKORPHAN 0><GTABS $>
<GHYPHENATION 2 34 0><GWORDSPACE 75 100 150><GSPACE -5 0 25>
><@Bullet=<@-PARENT "Normal"><FONT "Abadi MT Condensed Light">
<GLEFT 14.4><G+BEFORE 2.15><G%% 110><GTABS(25.2 l "")>
><@PreFormat=<@-PARENT "Normal"><FONT "Lucida Console"><SIZE 8><CTRACK 0>
<GLEFT 0><G+BEFORE 0><GALIGNMENT "left"><GWORDSPACE 100 100 100><GSPACE 0 0 0>
><@Title1=<@-PARENT "Normal"><FONT "Arial"><SIZE 14><B>
<GCONTENTS><GLEFT 0><G+BEFORE 0><GALIGNMENT "left">
><@Title2=<@-PARENT "Title1"><SIZE 12><G+BEFORE 3.6>
><@Title3=<@-PARENT "Title1"><SIZE 10><GLEFT 7.2><G+BEFORE 7.2>
><@Title4=<@-PARENT "Title3">
><@Title5=<@-PARENT "Title3">
><@Quote=<@-PARENT "Normal"><SIZE 10><I>>
%(HEADER1)s
%(HEADER2)s
%(HEADER3)s
""",
#TODO escape lines beginning with %% after all formatting
'mgp': """\
#!/usr/X11R6/bin/mgp -t 90
%%deffont "normal" xfont "utopia-medium-r", charset "iso8859-1"
%%deffont "normal-i" xfont "utopia-medium-i", charset "iso8859-1"
%%deffont "normal-b" xfont "utopia-bold-r" , charset "iso8859-1"
%%deffont "normal-bi" xfont "utopia-bold-i" , charset "iso8859-1"
%%deffont "mono" xfont "courier-medium-r", charset "iso8859-1"
%%default 1 size 5
%%default 2 size 8, fore "yellow", font "normal-b", center
%%default 3 size 5, fore "white", font "normal", left, prefix " "
%%tab 1 size 4, vgap 30, prefix " ", icon arc "red" 40, leftfill
%%tab 2 prefix " ", icon arc "orange" 40, leftfill
%%tab 3 prefix " ", icon arc "brown" 40, leftfill
%%tab 4 prefix " ", icon arc "darkmagenta" 40, leftfill
%%tab 5 prefix " ", icon arc "magenta" 40, leftfill
%%%%------------------------- end of headers -----------------------------
%%page
%%size 10, center, fore "yellow"
%(HEADER1)s
%%font "normal-i", size 6, fore "white", center
%(HEADER2)s
%%font "mono", size 7, center
%(HEADER3)s
""",
# TODO please, improve me!
'moin': """\
%(HEADER1)s
%(HEADER2)s
%(HEADER3)s
""",
#TODO how to make acrobat left-side pages count?
# \includepackage{graphics}
# --lang matters! \usepackage[brazil]{babel}
# local links seems to be \label, \ref, \pageref
'tex': \
r"""\documentclass[11pt,a4paper]{article}
\usepackage{amsfonts,amssymb,graphicx,url}
\usepackage[latin1]{inputenc} %% for accented chars
\pagestyle{plain} %% do page numbering ('empty' turns off)
\frenchspacing %% no aditional spaces after periods
%% all paragraph must be indented equaly
\setlength{\parskip}{8pt}\parindent=0pt
%% uncomment next line for fancy PDF output on Adobe Acrobat Reader
%%\usepackage[pdfstartview=FitV,colorlinks=true,bookmarks=true]{hyperref}
\newcommand\email{\begingroup \urlstyle{tt}\Url} %% for email
\title{%(HEADER1)s}
\author{%(HEADER2)s}
\begin{document}
\date{%(HEADER3)s}
\maketitle
"""
}
#-----------------------------------------------------------------------
def Quit(msg, exitcode=0): print msg ; sys.exit(exitcode)
def Error(msg): print "ERROR: %s"%msg ; sys.exit()
def Debug(msg,i=0,linenr=None):
if i > DEBUG: return
if linenr is not None:
print "(%d) %04d:%s"%(i,linenr,msg)
else:
print "(%d) %s"%(i,msg)
def Readfile(file):
if file == '-':
try: data = sys.stdin.readlines()
except: Error('You must feed me with data on STDIN!')
else:
try: f = open(file); data = f.readlines() ; f.close()
except: Error("Cannot read file:\n %s"%file)
return data
def Savefile(file, contents):
try: f = open(file, 'w')
except: Error("Cannot open file for writing:\n %s"%file)
if type(contents) == type([]): doit = f.writelines
else: doit = f.write
doit(contents) ; f.close()
def NewArea(new, linenr):
if new not in ['head', 'conf', 'body']:
Error("Invalid new AREA '%s' on line '%s'"%(new,linenr))
Debug('NEW AREA: %s'%new, 1, linenr)
return new
def Obsoleted(n, old, new, ver):
global has_obsolete
has_obsolete = 1
print 'OBSOLETE WARNING: line %04d'%n
print ' The %s is now obsoleted and will be removed'%old
print ' on txt2tags version %s. Please use %s instead.'%(ver,new)
def Fixed(n, old, new):
global has_fixed
has_fixed = 1
print 'FIXED: line %04d: %15s ---> %s'%(n,old,new)
def FixTable(tabline):
new = string.replace(tabline,'\t',' ',1) # del 1st TAB
new = string.replace(new,'\t',' | ') # change TABs by spaced pipes
new = re.sub('(.*[^\n\r])', '\\1 |', new) # add last pipe (for border)
return new
def FixFile(file, newcontent):
Savefile(file+'.OLD', Readfile(file)) # copy to .old
Savefile(file, newcontent)
print "\nFile '%s' correctly updated and saved."%(infile)
print "The old contents were saved to '%s.OLD'."%(infile)
def ObsoletedInstructions(infile):
print """\n
ATTENTION:
Some obsoleted txt2tags structures were found on your source document.
Please correct them by hand, or just run:
txt2tags --fixme %s
To update (rewrite) this file automatically.
Please don't ignore this message.
On next releases of txt2tags, these old structures will not be valid.
\n"""%infile
def reset_flags():
global FLAGS
for flag in FLAGS.keys(): FLAGS[flag] = 0
def set_outfile_name(infile, doctype):
"dirname is the same for {in,out}file"
if not infile: return
if infile == pipefileid or FLAGS['toconly'] or FLAGS['stdout']:
outfile = pipefileid
else:
outfile = "%s.%s"%(re.sub('\.(txt|t2t)$','',infile), doctype)
Debug(" infile: '%s'"% infile, 1)
Debug("outfile: '%s'"%outfile, 1)
return outfile
def finish_him(outlist, outfile):
"writing output to screen or file"
if outfile == pipefileid:
for line in outlist: print line
else:
Savefile(outfile, addLineBreaks(outlist))
if not FLAGS['gui']: print 'wrote %s'%(outfile)
if splitlevel:
print "--- html..."
os.system('sgml2html --language=%s --split=%s %s'%(
lang,splitlevel,outfile))
def ParseCmdline(cmdline=sys.argv):
"return a dic with all options:value found"
global CMDLINE ; CMDLINE = cmdline # save for dofooter()
Debug("cmdline: %s"%cmdline, 1)
options = {'infile': '', 'infiles':''}
# get cmdline options
longopt = ['help', 'version', 'type=', 'split=', 'lang=']+FLAGS.keys()
try: (opt, args) = getopt.getopt(cmdline[1:], 'hVt:', longopt)
except getopt.GetoptError:
Error('Bad option or missing argument (try --help)')
# get infile, if any
if args:
options['infile'] = args[0]
options['infiles'] = args # multi
for name,val in opt:
# parse information options
if name in ['-h','--help' ]: Quit(usage)
elif name in ['-V','--version']: Quit(versionstr)
# parse short/long options
elif name in ['-t','--type']:
options['doctype'] = val
continue
# just long options
options[name[2:]] = val # del --
Debug("cmdline options: %s"%options, 1)
return options
def ParseCmdlineOptions(optdic):
"set vars and flags according to options dic"
global FLAGS, splitlevel, lang
# store flags and vars
myflags = [] # for debug msg
for flag in FLAGS.keys():
if optdic.has_key(flag):
FLAGS[flag] = 1
myflags.append(flag)
doctype = optdic.get('doctype')
infile = optdic.get('infile')
splitlevel = optdic.get('split')
lang = optdic.get('lang')
Debug("cmdline flags: %s"%string.join(myflags,', '), 1)
if FLAGS['fixme']:
if not infile: Quit(usage, 1)
doctype = 'moin' # bogus, not used at all
if not doctype and FLAGS['toconly']: doctype = 'txt' # toconly dft type
if not infile or not doctype: Quit(usage, 1) # no filename/doctype
# sanity check: validate target type
if not targets.count(doctype):
Error("Invalid document type '%s' (try --help)"%(doctype))
outfile = set_outfile_name(infile, doctype)
# sanity check: validate split level
if doctype != 'html': splitlevel = '' # only valid for HTML target
if splitlevel:
# checkings
if outfile == pipefileid:
Error('You need to provide a FILE (not STDIN) '
'when using --split')
if splitlevel[0] not in '012':
Error('Option --split must be 0, 1 or 2')
# check for sgml-tools
#TODO how to test (in a clever way) if an executable is in path?
#TODO os.system() return code? sgml2html w/out --help exit 0?
#TODO bah! implement sgml2html split natively and we're done
# Error("Sorry, you must have 'sgml2html' to use --split")
# set things
FLAGS['stdout'] = 0 # no --stdout
doctype = 'sgml' # 1st do a sgml, then sgml2html
outfile = set_outfile_name(infile, doctype)
# sanity check: source loss!
if infile != pipefileid and infile == outfile:
Error("SUICIDE WARNING!!! (try --stdout)\n source"+\
" and target files has the same name: %s"%outfile)
### yes, i've got my sample.t2t file deleted before add this test... :/
return infile,outfile,doctype
#TODO splitlevel, lang
#---End of ParseCmdlineOptions
def toc_master(doctype, header, doc, toc):
"decide to include TOC or not on the outlist"
# deal with the TOC options
if FLAGS['toc'] or FLAGS['toconly']:
# format TOC lines
### here we do toc as a valid t2t marked text (list type)
FLAGS['noheaders'] = 1
x,y,toc = convert(['']+toc+['',''], doctype)
# TOC between bars (not for --toconly)
if FLAGS['toc']:
para = TAGS['paragraph']
tocbar = [para, regex['x'].sub('-'*72,TAGS['bar1']), para]
toc = tocbar + toc + tocbar
if FLAGS['toconly']: header = doc = []
else:
toc = []
# on tex, \tableofcontents do it all - see doHeader()
if doctype == 'tex' and not FLAGS['toconly']:
toc = []
return header + toc + doc
def doitall(cmdlinedic):
global outfile
infile,outfile,doctype = ParseCmdlineOptions(cmdlinedic)
header,toc,doc = convert(Readfile(infile), doctype)
outlist = toc_master(doctype,header,doc,toc)
if has_obsolete: ObsoletedInstructions(infile)
return doctype, outfile, outlist
# set the Line Break across platforms
LB = '\n' # default
if sys.platform[:3] == 'win': LB = '\r\n'
#elif sys.platform[:3] == 'cyg': LB = '\r\n' # not sure if it's best :(
elif sys.platform[:3] == 'mac': LB = '\r'
def getTags(doctype):
keys = [
'paragraph','title1','title2','title3','title4','title5',
'areaPreOpen','areaPreClose',
'areaQuoteOpen','areaQuoteClose',
'fontMonoOpen','fontMonoClose',
'fontBoldOpen','fontBoldClose',
'fontItalicOpen','fontItalicClose',
'fontBolditalicOpen','fontBolditalicClose',
'fontUnderlineOpen','fontUnderlineClose',
'listOpen','listClose','listItem',
'numlistOpen','numlistClose','numlistItem',
'deflistOpen','deflistClose','deflistItem1','deflistItem2',
'bar1','bar2',
'url','urlMark','email','emailMark',
'img','imgsolo',
'tableOpen','tableClose','tableLineOpen','tableLineClose',
'tableCellOpen','tableCellClose',
'tableTitleCellOpen','tableTitleCellClose',
'anchor','comment',
'EOD'
]
if doctype == "txt":
tags = {
'title1' : ' \a' ,
'title2' : '\t\a' ,
'title3' : '\t\t\a' ,
'title4' : '\t\t\t\a' ,
'title5' : '\t\t\t\t\a',
'areaQuoteOpen' : ' ' ,
'listItem' : '- ' ,
'numlistItem' : '\a. ' ,
'bar1' : '\a' ,
'bar2' : '\a' ,
'url' : '\a' ,
'urlMark' : '\a (\a)' ,
'email' : '\a' ,
'emailMark' : '\a (\a)' ,
'img' : '[\a]' ,
}
elif doctype == "html":
tags = {
'paragraph' : '<P>' ,
'title1' : '<H1>\a</H1>' ,
'title2' : '<H2>\a</H2>' ,
'title3' : '<H3>\a</H3>' ,
'title4' : '<H4>\a</H4>' ,
'title5' : '<H5>\a</H5>' ,
'areaPreOpen' : '<PRE>' ,
'areaPreClose' : '</PRE>' ,
'areaQuoteOpen' : '<BLOCKQUOTE>' ,
'areaQuoteClose' : '</BLOCKQUOTE>' ,
'fontMonoOpen' : '<CODE>' ,
'fontMonoClose' : '</CODE>' ,
'fontBoldOpen' : '<B>' ,
'fontBoldClose' : '</B>' ,
'fontItalicOpen' : '<I>' ,
'fontItalicClose' : '</I>' ,
'fontBolditalicOpen' : '<B><I>' ,
'fontBolditalicClose': '</I></B>' ,
'fontUnderlineOpen' : '<U>' ,
'fontUnderlineClose' : '</U>' ,
'listOpen' : '<UL>' ,
'listClose' : '</UL>' ,
'listItem' : '<LI>' ,
'numlistOpen' : '<OL>' ,
'numlistClose' : '</OL>' ,
'numlistItem' : '<LI>' ,
'deflistOpen' : '<DL>' ,
'deflistClose' : '</DL>' ,
'deflistItem1' : '<DT>\a</DT>' ,
'deflistItem2' : '<DD>' ,
'bar1' : '<HR NOSHADE SIZE=1>' ,
'bar2' : '<HR NOSHADE SIZE=5>' ,
'url' : '<A HREF="\a">\a</A>' ,
'urlMark' : '<A HREF="\a">\a</A>' ,
'email' : '<A HREF="mailto:\a">\a</A>' ,
'emailMark' : '<A HREF="mailto:\a">\a</A>' ,
'img' : '<IMG ALIGN="\a" SRC="\a" BORDER="0">',
'imgsolo' : '<P ALIGN="center">\a</P>' ,
'tableOpen' : '<table align=center cellpadding=4 border=\a>',
'tableClose' : '</table>' ,
'tableLineOpen' : '<tr>' ,
'tableLineClose' : '</tr>' ,
'tableCellOpen' : '<td>' ,
'tableCellClose' : '</td>' ,
'tableTitleCellOpen' : '<th>' ,
'tableTitleCellClose': '</th>' ,
'anchor' : '<a name="\a">' ,
'comment' : '<!-- \a -->' ,
'EOD' : '</BODY></HTML>'
}
elif doctype == "sgml":
tags = {
'paragraph' : '<p>' ,
'title1' : '<sect>\a<p>' ,
'title2' : '<sect1>\a<p>' ,
'title3' : '<sect2>\a<p>' ,
'title4' : '<sect3>\a<p>' ,
'title5' : '<sect4>\a<p>' ,
'areaPreOpen' : '<tscreen><verb>' ,
'areaPreClose' : '</verb></tscreen>' ,
'areaQuoteOpen' : '<quote>' ,
'areaQuoteClose' : '</quote>' ,
'fontMonoOpen' : '<tt>' ,
'fontMonoClose' : '</tt>' ,
'fontBoldOpen' : '<bf>' ,
'fontBoldClose' : '</bf>' ,
'fontItalicOpen' : '<em>' ,
'fontItalicClose' : '</em>' ,
'fontBolditalicOpen' : '<bf><em>' ,
'fontBolditalicClose': '</em></bf>' ,
'fontUnderlineOpen' : '<bf><em>' ,
'fontUnderlineClose' : '</em></bf>' ,
'listOpen' : '<itemize>' ,
'listClose' : '</itemize>' ,
'listItem' : '<item>' ,
'numlistOpen' : '<enum>' ,
'numlistClose' : '</enum>' ,
'numlistItem' : '<item>' ,
'bar1' : '<!-- \a -->' ,
'bar2' : '<!-- \a -->' ,
'url' : '<htmlurl url="\a" name="\a">' ,
'urlMark' : '<htmlurl url="\a" name="\a">' ,
'email' : '<htmlurl url="mailto:\a" name="\a">' ,
'emailMark' : '<htmlurl url="mailto:\a" name="\a">' ,
'img' : '<figure><ph vspace=""><img src="\a"></figure>',
'tableOpen' : '<table><tabular ca="c">' ,
'tableClose' : '</tabular></table>' ,
'tableLineClose' : '<rowsep>' ,
'tableCellClose' : '<colsep>' ,
'tableTitleCellClose': '<colsep>' ,
'comment' : '<!-- \a -->' ,
'EOD' : '</article>'
}
elif doctype == "tex":
tags = {
'title1' : '\n\\newpage\section{\a}',
'title2' : '\\subsection{\a}' ,
'title3' : '\\subsubsection{\a}' ,
# title 4/5: DIRTY: para+BF+\\+\n
'title4' : '\\paragraph{}\\textbf{\a}\\\\\\\n' ,
'title5' : '\\paragraph{}\\textbf{\a}\\\\\\\n' ,
'areaPreOpen' : '\\begin{verbatim}' ,
'areaPreClose' : '\\end{verbatim}' ,
'areaQuoteOpen' : '\\begin{quotation}' ,
'areaQuoteClose' : '\\end{quotation}' ,
'fontMonoOpen' : '\\texttt{' ,
'fontMonoClose' : '}' ,
'fontBoldOpen' : '\\textbf{' ,
'fontBoldClose' : '}' ,
'fontItalicOpen' : '\\textit{' ,
'fontItalicClose' : '}' ,
'fontBolditalicOpen' : '\\textbf{\\textit{' ,
'fontBolditalicClose': '}}' ,
'fontUnderlineOpen' : '\\underline{' ,
'fontUnderlineClose' : '}' ,
'listOpen' : '\\begin{itemize}' ,
'listClose' : '\\end{itemize}' ,
'listItem' : '\\item ' ,
'numlistOpen' : '\\begin{enumerate}' ,
'numlistClose' : '\\end{enumerate}' ,
'numlistItem' : '\\item ' ,
'deflistOpen' : '\\begin{description}' ,
'deflistClose' : '\\end{description}' ,
'deflistItem1' : '\\item[\a]' ,
'bar1' : '\n\\hrulefill{}\n' ,
'bar2' : '\n\\rule{\linewidth}{1mm}\n' ,
'url' : '\\url{\a}' ,
'urlMark' : '\\textit{\a} (\\url{\a})' ,
'email' : '\\email{\a}' ,
'emailMark' : '\\textit{\a} (\\email{\a})' ,
'img' : '(\a)' ,
'tableOpen' : '\\begin{center}\\begin{tabular}',
'tableClose' : '\\end{tabular}\\end{center}' ,
'tableLineOpen' : '\\hline ' ,
'tableLineClose' : ' \\\\' ,
'tableCellClose' : ' & ' ,
'tableTitleCellOpen' : '\\textbf{' ,
'tableTitleCellClose': '} & ' ,
'comment' : '% \a' ,
'EOD' : '\\end{document}'
}
elif doctype == "moin":
tags = {
'title1' : '= \a =' ,
'title2' : '== \a ==' ,
'title3' : '=== \a ===' ,
'title4' : '==== \a ====' ,
'title5' : '===== \a =====' ,
'areaPreOpen' : '{{{' ,
'areaPreClose' : '}}}' ,
'areaQuoteOpen' : ' ' ,
'fontMonoOpen' : '{{{' ,
'fontMonoClose' : '}}}' ,
'fontBoldOpen' : "'''" ,
'fontBoldClose' : "'''" ,
'fontItalicOpen' : "''" ,
'fontItalicClose' : "''" ,
'fontBolditalicOpen' : "'''''" ,
'fontBolditalicClose': "'''''" ,
'fontUnderlineOpen' : "'''''" ,
'fontUnderlineClose' : "'''''" ,
'listItem' : '* ' ,
'numlistItem' : '\a. ' ,
'bar1' : '----' ,
'bar2' : '----' ,
'url' : '[\a]' ,
'urlMark' : '[\a \a]' ,
'email' : '[\a]' ,
'emailMark' : '[\a \a]' ,
'img' : '[\a]' ,
'tableLineOpen' : '||' ,
'tableCellClose' : '||' ,
'tableTitleCellClose': '||' ,
}
elif doctype == "mgp":
tags = {
'paragraph' : '%font "normal", size 5\n' ,
'title1' : '%page\n\n\a' ,
'title2' : '%page\n\n\a' ,
'title3' : '%page\n\n\a' ,
'title4' : '%page\n\n\a' ,
'title5' : '%page\n\n\a' ,
'areaPreOpen' : '\n%font "mono"' ,
'areaPreClose' : '%font "normal"' ,
'areaQuoteOpen' : '%prefix " "' ,
'areaQuoteClose' : '%prefix " "' ,
'fontMonoOpen' : '\n%cont, font "mono"\n' ,
'fontMonoClose' : '\n%cont, font "normal"\n' ,
'fontBoldOpen' : '\n%cont, font "normal-b"\n' ,
'fontBoldClose' : '\n%cont, font "normal"\n' ,
'fontItalicOpen' : '\n%cont, font "normal-i"\n' ,
'fontItalicClose' : '\n%cont, font "normal"\n' ,
'fontBolditalicOpen' : '\n%cont, font "normal-bi"\n' ,
'fontBolditalicClose': '\n%cont, font "normal"\n' ,
'fontUnderlineOpen' : '\n%cont, fore "cyan"\n' ,
'fontUnderlineClose' : '\n%cont, fore "white"\n' ,
'numlistItem' : '\a. ' ,
'bar1' : '%bar "white" 5' ,
'bar2' : '%pause' ,
'url' : '\n%cont, fore "cyan"\n\a\n%cont, fore "white"\n',
'urlMark' : '\a \n%cont, fore "cyan"\n\a\n%cont, fore "white"\n',
'email' : '\n%cont, fore "cyan"\n\a\n%cont, fore "white"\n',
'emailMark' : '\a \n%cont, fore "cyan"\n\a\n%cont, fore "white"\n',
'img' : '\n%center\n%newimage "\a", left\n',
'comment' : '%% \a' ,
'EOD' : '%%EOD'
}
elif doctype == "man":
tags = {
'paragraph' : '.P' ,
'title1' : '.SH \a' ,
'title2' : '.SS \a' ,
'title3' : '.SS \a' ,
'title4' : '.SS \a' ,
'title5' : '.SS \a' ,
'areaPreOpen' : '.nf' ,
'areaPreClose' : '.fi\n' ,
'areaQuoteOpen' : '\n' ,
'areaQuoteClose' : '\n' ,
'fontBoldOpen' : '\\fB' ,
'fontBoldClose' : '\\fP' ,
'fontItalicOpen' : '\\fI' ,
'fontItalicClose' : '\\fP' ,
'fontBolditalicOpen' : '\n.BI ' ,
'fontBolditalicClose': '\n\\&' ,
'listOpen' : '\n.nf' , # pre
'listClose' : '.fi\n' ,
'listItem' : '* ' ,
'numlistOpen' : '\n.nf' , # pre
'numlistClose' : '.fi\n' ,
'numlistItem' : '\a. ' ,
'bar1' : '\n\n' ,
'bar2' : '\n\n' ,
'url' : '\a' ,
'urlMark' : '\a (\a)' ,
'email' : '\a' ,
'emailMark' : '\a (\a)' ,
'img' : '\a' ,
'comment' : '.\\" \a'
}
elif doctype == "pm6":
tags = {
'paragraph' : '<@Normal:>' ,
'title1' : '\n<@Title1:>\a' ,
'title2' : '\n<@Title2:>\a' ,
'title3' : '\n<@Title3:>\a' ,
'title4' : '\n<@Title4:>\a' ,
'title5' : '\n<@Title5:>\a' ,
'areaPreOpen' : '<@PreFormat:>' ,
'areaQuoteOpen' : '<@Quote:>' ,
'fontMonoOpen' : '<FONT "Lucida Console"><SIZE 9>' ,
'fontMonoClose' : '<SIZE$><FONT$>' ,
'fontBoldOpen' : '<B>' ,
'fontBoldClose' : '<P>' ,
'fontItalicOpen' : '<I>' ,
'fontItalicClose' : '<P>' ,
'fontBolditalicOpen' : '<B><I>' ,
'fontBolditalicClose': '<P>' ,
'fontUnderlineOpen' : '<U>' ,
'fontUnderlineClose' : '<P>' ,
'listOpen' : '<@Bullet:>' ,
'listItem' : '\x95 ' , # \x95 == ~U
'numlistOpen' : '<@Bullet:>' ,
'numlistItem' : '\x95 ' ,
'bar1' : '\a' ,
'bar2' : '\a' ,
'url' : '<U>\a<P>' , # underline
'urlMark' : '\a <U>\a<P>' ,
'email' : '\a' ,
'emailMark' : '\a \a' ,
'img' : '\a' ,
}
# create empty tags keys
for key in keys:
if not tags.has_key(key):
tags[key] = ''
else:
# drawback of using re.sub() - double escape some specials
# see also: 'force_re' marks on the code
specials = {'1':'ntsrful', '2':'ntsrf'}
specials = specials[sys.version[0]]
tags[key] = re.sub(r'(\\[%s])'%specials,r'\\\1',tags[key])
return tags
def getRules(doctype):
ret = {}
allrules = [
# target rules (ON/OFF)
'linkable', # target supports external links
'tableable', # target supports tables
'imgalignable', # target supports image alignment
'listcountable', # target supports numbered lists natively
'tablecellsplit', # place delimiters only *between* cells
'listnotnested', # lists cannot be nested
'quotenotnested', # quotes cannot be nested
'preareanotescaped', # don't escape specials in PRE area
# target code beautify (ON/OFF)
'indentprearea', # add leading spaces to PRE area lines
'breaktablecell', # break lines after any table cell
'breaktablelineopen', # break line after opening table line
'keepquoteindent', # don't remove the leading TABs on quotes
# value settings
'listmaxdepth', # maximum depth for lists
]
rules = {
'txt' : {
'indentprearea':1
},
'html': {
'indentprearea':1,
'linkable':1,
'imgalignable':1,
'listcountable':1,
'tableable':1,
'breaktablecell':1,
'breaktablelineopen':1,
'keepquoteindent':1
},
'sgml': {
'linkable':1,
'listcountable':1,
'tableable':1,
'tablecellsplit':1,
'quotenotnested':1,
'keepquoteindent':1
},
'mgp' : {
},
'tex' : {
'listcountable':1,
'tableable':1,
'tablecellsplit':1,
'preareanotescaped':1,
'listmaxdepth':4
},
'moin': {
'linkable':1,
'tableable':1
},
'man' : {
'indentprearea':1,
'listnotnested':1
},
'pm6' : {
}
}
# populate return dictionary
myrules = rules[doctype]
for key in allrules : ret[key] = 0 # reset all
for key in myrules.keys(): ret[key] = myrules[key] # turn ON
return ret
def getRegexes():
regex = {
# extra at end: (\[(?P<label>\w+)\])?
'title':
re.compile(r'^\s*(?P<tag>={1,5})(?P<txt>[^=].*[^=])\1$'),
'areaPreOpen':
re.compile(r'^---$'),
'areaPreClose':
re.compile(r'^---$'),
'quote':
re.compile(r'^\t+'),
'1linePreOld':
re.compile(r'^ {4}([^\s-])'),
'1linePre':
re.compile(r'^--- '),
'fontMono':
re.compile(r'`([^`]+)`'),
'fontBold':
re.compile(r'\*\*([^\s*].*?)\*\*'),
'fontItalic':
re.compile(r'(^|[^:])//([^ /].*?)//'),
'fontUnderline':
re.compile(r'__([^_].*?)__'), # underline lead/trailing blank
'fontBolditalic':
re.compile(r'\*/([^/].*?)/\*'),
'list':
re.compile(r'^( *)([+-]) ([^ ])'),
'deflist':
re.compile(r'^( *)(=) ([^:]+):'),
'bar':
re.compile(r'^\s*([_=-]{20,})\s*$'),
'table':
re.compile(r'^ *\|\|?[<:>]*\s'),
'blankline':
re.compile(r'^\s*$'),
'comment':
re.compile(r'^(//|%)')
}
# special char to place data on TAGs contents (\a == bell)
regex['x'] = re.compile('\a')
# %%date [ (formatting) ]
regex['date'] = re.compile(r'%%date\b(\((?P<fmt>.*?)\))?', re.I)
### complicated regexes begin here ;)
#
# textual descriptions on --help's style: [...] is optional, | is OR
### first, some auxiliar variables
#
# [image.EXT]
patt_img = r'\[([\w_,.+%$#@!?+~/-]+\.(png|jpe?g|gif|eps|bmp))\]'
# link things
urlskel = {
'proto' : r'(https?|ftp|news|telnet|gopher|wais)://',
'guess' : r'(www[23]?|ftp)\.', # w/out proto, try to guess
'login' : r'A-Za-z0-9_.-', # for ftp://[email protected]
'pass' : r'[^ @]*', # for ftp://login:[email protected]
'chars' : r'A-Za-z0-9%._/~:,=-', # %20(space), :80(port)
'anchor': r'A-Za-z0-9%._-', # %nn(encoded)
'form' : r'A-Za-z0-9/%&=+.@*_-',# .@*_-(as is)
'punct' : r'.,;:!?'
}
# username [ :password ] @
patt_url_login = r'([%s]+(:%s)?@)?'%(urlskel['login'],urlskel['pass'])
# [ http:// ] [ username:password@ ] domain.com [ / ] [ #anchor | ?form=data ]
retxt_url = r'\b(%s%s|%s)[%s]+\b/*(\?[%s]+)?(#[%s]+)?'%(
urlskel['proto'],patt_url_login, urlskel['guess'],
urlskel['chars'],urlskel['form'],urlskel['anchor'])
# filename | [ filename ] #anchor
retxt_url_local = r'[%s]+|[%s]*(#[%s]+)'%(
urlskel['chars'],urlskel['chars'],urlskel['anchor'])
# user@domain [ ?form=data ]
patt_email = r'\b[%s]+@([A-Za-z0-9_-]+\.)+[A-Za-z]{2,4}\b(\?[%s]+)?'%(
urlskel['login'],urlskel['form'])
# saving for future use
regex['_urlskel'] = urlskel
### and now the real regexes
#
regex['email'] = re.compile(patt_email,re.I)
# email | url
regex['link'] = \
re.compile(r'%s|%s'%(retxt_url,patt_email), re.I)
# \[ label | imagetag url | email | filename \]
regex['linkmark'] = \
re.compile(r'\[(?P<label>%s|[^]]+) (?P<link>%s|%s|%s)\]'%(
patt_img, retxt_url, patt_email, retxt_url_local),
re.L+re.I)
# image
regex['img'] = re.compile(patt_img, re.L+re.I)
# all macros
regex['macro'] = regex['date']
# Settings are still in development stage - DON'T USE THIS
#regex['setting'] = re.compile(r'^%\s*Document \s*(Encoding|Toc)\s*:\s*(.*)$',re.I)
return regex
### END OF regex nightmares
class SubareaMaster:
def __init__(self) : self.x = []
def __call__(self) :
if not self.x: return ''
return self.x[-1]
def add(self, area):
if not self.x or (self.x and self.x[-1] != area):
self.x.append(area)
Debug('subarea ++ (%s): %s' % (area,self.x), 1)
def pop(self, area=None):
if area and self.x[-1] == area: self.x.pop()
Debug('subarea -- (%s): %s' % (area,self.x), 1)
def doHeader(doctype, headdic):
if not HEADER_TEMPLATE.has_key(doctype):
Error("doheader: Unknow doctype '%s'"%doctype)
Debug('HEADER data: %s'%headdic, 1)
template = string.split(HEADER_TEMPLATE[doctype], '\n')
# scan for empty dictionary keys
# if found, scan template lines for that key reference
# if found, remove the reference
# if there aren't any other key reference on the same line, remove it