PageRenderTime 54ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/old/txt2tags-1.6.py

http://txt2tags.googlecode.com/
Python | 2542 lines | 2502 code | 10 blank | 30 comment | 9 complexity | 04ccb57d7ce5ada49fd8c0233f13047c MD5 | raw file
Possible License(s): GPL-2.0, GPL-3.0, WTFPL

Large files files are truncated, but you can click here to view the full file

  1. #!/usr/bin/env python
  2. # txt2tags - generic text conversion tool
  3. # http://txt2tags.sf.net
  4. #
  5. # Copyright 2001, 2002, 2003 Aurelio Marinho Jargas
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, version 2.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You have received a copy of the GNU General Public License along
  17. # with this program, on the COPYING file.
  18. #
  19. # the code is better, even readable now, but needs more improvements
  20. # please wait for the upcoming 2.0 series for a cleaner one
  21. #XXX Python coding warning
  22. # Avoid common mistakes:
  23. # - do NOT use newlist=list instead newlist=list[:]
  24. # - do NOT use newdic=dic instead newdic=dic.copy()
  25. # - do NOT use dic[key] instead dic.get(key)
  26. import re, string, os, sys, getopt, traceback
  27. from time import strftime,time,localtime
  28. my_url = 'http://txt2tags.sf.net'
  29. my_email = 'verde@aurelio.net'
  30. my_version = '1.6' #-betaMMDD
  31. DEBUG = 0 # do not edit here, please use --debug
  32. targets = ['txt', 'sgml', 'html', 'pm6', 'mgp', 'moin', 'man', 'tex']
  33. FLAGS = {'noheaders':0,'enumtitle':0 ,'maskemail':0 ,'stdout' :0,
  34. 'toconly' :0,'toc' :0 ,'gui' :0 ,'included':0}
  35. OPTIONS = {'toclevel' :3,'style' :'','type' :'','outfile' :'',
  36. 'split':0, 'lang':''}
  37. CONFIG_KEYWORDS = ['encoding', 'style', 'cmdline','preproc','postproc']
  38. CONF = {}
  39. regex = {}
  40. TAGS = {}
  41. rules = {}
  42. currdate = strftime('%Y%m%d',localtime(time())) # ISO current date
  43. lang = 'english'
  44. doctype = outfile = ''
  45. STDIN = STDOUT = '-'
  46. ESCCHAR = '\x00'
  47. LINEBREAK = {'default':'\n', 'win':'\r\n', 'mac':'\r'}
  48. #my_version = my_version + '-dev' + currdate[4:] # devel!
  49. # global vars for doClose*()
  50. quotedepth = []
  51. listindent = []
  52. listids = []
  53. subarea = None
  54. tableborder = 0
  55. # set the Line Break across platforms
  56. LB = LINEBREAK.get(sys.platform[:3]) or LINEBREAK['default']
  57. versionstr = "txt2tags version %s <%s>"%(my_version,my_url)
  58. usage = """
  59. %s
  60. Usage: txt2tags -t <type> [OPTIONS] file.t2t
  61. -t, --type set target document type. actually supported:
  62. %s
  63. -o, --outfile=FILE set FILE as the output filename ('-' for STDOUT)
  64. --stdout same as '-o -' or '--outfile -' (deprecated option)
  65. -H, --noheaders suppress header, title and footer information
  66. -n, --enumtitle enumerate all title lines as 1, 1.1, 1.1.1, etc
  67. --maskemail hide email from spam robots. x@y.z turns <x (a) y z>
  68. --toc add TOC (Table of Contents) to target document
  69. --toconly print document TOC and exit
  70. --toclevel=N set maximum TOC level (deepness) to N
  71. --gui invoke Graphical Tk Interface
  72. --style=FILE use FILE as the document style (like Html CSS)
  73. -h, --help print this help information and exit
  74. -V, --version print program version and exit
  75. Extra options for HTML target (needs sgml-tools):
  76. --split split documents. values: 0, 1, 2 (default 0)
  77. --lang document language (default english)
  78. By default, converted output is saved to 'file.<type>'.
  79. Use --outfile to force an output filename.
  80. If input file is '-', reads from STDIN.
  81. If outfile is '-', dumps output to STDOUT.\
  82. """%(versionstr, re.sub(r"[]'[]",'',repr(targets)))
  83. # here is all the target's templates
  84. # you may edit them to fit your needs
  85. # - the %(HEADERn)s strings represent the Header lines
  86. # - use %% to represent a literal %
  87. #
  88. HEADER_TEMPLATE = {
  89. 'txt': """\
  90. %(HEADER1)s
  91. %(HEADER2)s
  92. %(HEADER3)s
  93. """,
  94. 'sgml': """\
  95. <!doctype linuxdoc system>
  96. <article>
  97. <title>%(HEADER1)s
  98. <author>%(HEADER2)s
  99. <date>%(HEADER3)s
  100. """,
  101. 'html': """\
  102. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  103. <HTML>
  104. <HEAD>
  105. <META NAME="generator" CONTENT="http://txt2tags.sf.net">
  106. <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=%(ENCODING)s">
  107. <LINK REL="stylesheet" TYPE="text/css" HREF="%(STYLE)s">
  108. <TITLE>%(HEADER1)s</TITLE>
  109. </HEAD><BODY BGCOLOR="white" TEXT="black">
  110. <P ALIGN="center"><CENTER><H1>%(HEADER1)s</H1>
  111. <FONT SIZE=4>
  112. <I>%(HEADER2)s</I><BR>
  113. %(HEADER3)s
  114. </FONT></CENTER>
  115. """,
  116. # TODO man section 1 is hardcoded...
  117. 'man': """\
  118. .TH "%(HEADER1)s" 1 %(HEADER3)s "%(HEADER2)s"
  119. """,
  120. # TODO style to <HR>
  121. 'pm6': """\
  122. <PMTags1.0 win><C-COLORTABLE ("Preto" 1 0 0 0)
  123. ><@Normal=
  124. <FONT "Times New Roman"><CCOLOR "Preto"><SIZE 11>
  125. <HORIZONTAL 100><LETTERSPACE 0><CTRACK 127><CSSIZE 70><C+SIZE 58.3>
  126. <C-POSITION 33.3><C+POSITION 33.3><P><CBASELINE 0><CNOBREAK 0><CLEADING -0.05>
  127. <GGRID 0><GLEFT 7.2><GRIGHT 0><GFIRST 0><G+BEFORE 7.2><G+AFTER 0>
  128. <GALIGNMENT "justify"><GMETHOD "proportional"><G& "ENGLISH">
  129. <GPAIRS 12><G%% 120><GKNEXT 0><GKWIDOW 0><GKORPHAN 0><GTABS $>
  130. <GHYPHENATION 2 34 0><GWORDSPACE 75 100 150><GSPACE -5 0 25>
  131. ><@Bullet=<@-PARENT "Normal"><FONT "Abadi MT Condensed Light">
  132. <GLEFT 14.4><G+BEFORE 2.15><G%% 110><GTABS(25.2 l "")>
  133. ><@PreFormat=<@-PARENT "Normal"><FONT "Lucida Console"><SIZE 8><CTRACK 0>
  134. <GLEFT 0><G+BEFORE 0><GALIGNMENT "left"><GWORDSPACE 100 100 100><GSPACE 0 0 0>
  135. ><@Title1=<@-PARENT "Normal"><FONT "Arial"><SIZE 14><B>
  136. <GCONTENTS><GLEFT 0><G+BEFORE 0><GALIGNMENT "left">
  137. ><@Title2=<@-PARENT "Title1"><SIZE 12><G+BEFORE 3.6>
  138. ><@Title3=<@-PARENT "Title1"><SIZE 10><GLEFT 7.2><G+BEFORE 7.2>
  139. ><@Title4=<@-PARENT "Title3">
  140. ><@Title5=<@-PARENT "Title3">
  141. ><@Quote=<@-PARENT "Normal"><SIZE 10><I>>
  142. %(HEADER1)s
  143. %(HEADER2)s
  144. %(HEADER3)s
  145. """,
  146. 'mgp': """\
  147. #!/usr/X11R6/bin/mgp -t 90
  148. %%deffont "normal" xfont "utopia-medium-r", charset "iso8859-1"
  149. %%deffont "normal-i" xfont "utopia-medium-i", charset "iso8859-1"
  150. %%deffont "normal-b" xfont "utopia-bold-r" , charset "iso8859-1"
  151. %%deffont "normal-bi" xfont "utopia-bold-i" , charset "iso8859-1"
  152. %%deffont "mono" xfont "courier-medium-r", charset "iso8859-1"
  153. %%default 1 size 5
  154. %%default 2 size 8, fore "yellow", font "normal-b", center
  155. %%default 3 size 5, fore "white", font "normal", left, prefix " "
  156. %%tab 1 size 4, vgap 30, prefix " ", icon arc "red" 40, leftfill
  157. %%tab 2 prefix " ", icon arc "orange" 40, leftfill
  158. %%tab 3 prefix " ", icon arc "brown" 40, leftfill
  159. %%tab 4 prefix " ", icon arc "darkmagenta" 40, leftfill
  160. %%tab 5 prefix " ", icon arc "magenta" 40, leftfill
  161. %%%%------------------------- end of headers -----------------------------
  162. %%page
  163. %%size 10, center, fore "yellow"
  164. %(HEADER1)s
  165. %%font "normal-i", size 6, fore "white", center
  166. %(HEADER2)s
  167. %%font "mono", size 7, center
  168. %(HEADER3)s
  169. """,
  170. # TODO please, improve me!
  171. 'moin': """\
  172. %(HEADER1)s
  173. %(HEADER2)s
  174. %(HEADER3)s
  175. """,
  176. 'tex': \
  177. r"""\documentclass[11pt,a4paper]{article}
  178. \usepackage{amsfonts,amssymb,graphicx,url}
  179. \usepackage[%(ENCODING)s]{inputenc} %% char encoding
  180. \pagestyle{plain} %% do page numbering ('empty' turns off)
  181. \frenchspacing %% no aditional spaces after periods
  182. \setlength{\parskip}{8pt}\parindent=0pt %% no paragraph indentation
  183. %% uncomment next line for fancy PDF output on Adobe Acrobat Reader
  184. %%\usepackage[pdfstartview=FitV,colorlinks=true,bookmarks=true]{hyperref}
  185. \title{%(HEADER1)s}
  186. \author{%(HEADER2)s}
  187. \begin{document}
  188. \date{%(HEADER3)s}
  189. \maketitle
  190. """
  191. }
  192. #-----------------------------------------------------------------------
  193. def Quit(msg, exitcode=0): print msg ; sys.exit(exitcode)
  194. def Error(msg): print "ERROR: %s"%msg ; sys.exit()
  195. def echo(msg): print '\033[32;1m%s\033[m'%msg # quick debug
  196. def Debug(msg,i=0,linenr=None):
  197. if i > DEBUG: return
  198. if linenr is not None:
  199. print "(%d) %04d:%s"%(i,linenr,msg)
  200. else:
  201. print "(%d) %s"%(i,msg)
  202. def Readfile(file):
  203. if file == '-':
  204. try: data = sys.stdin.readlines()
  205. except: Error('You must feed me with data on STDIN!')
  206. else:
  207. try: f = open(file); data = f.readlines() ; f.close()
  208. except: Error("Cannot read file:\n %s"%file)
  209. return data
  210. def Savefile(file, contents):
  211. try: f = open(file, 'wb')
  212. except: Error("Cannot open file for writing:\n %s"%file)
  213. if type(contents) == type([]): doit = f.writelines
  214. else: doit = f.write
  215. doit(contents) ; f.close()
  216. def ParseConfig(text='',name='', target=''):
  217. ret = {}
  218. if not text: return ret
  219. re_name = name or '[a-z]+'
  220. re_target = target or '[a-z]*'
  221. cfgregex = re.compile("""
  222. ^%%!\s* # leading id with opt spaces
  223. (?P<name>%s)\s* # config name
  224. (\((?P<target>%s)\))? # optional target spec inside ()
  225. \s*:\s* # key:value delimiter with opt spaces
  226. (?P<value>\S.+?) # config value
  227. \s*$ # rstrip() spaces and hit EOL
  228. """%(re_name,re_target), re.I+re.VERBOSE)
  229. prepostregex = re.compile("""
  230. # ---[ PATTERN ]---
  231. ^( "([^"]*)" # "double quoted" or
  232. | '([^']*)' # 'single quoted' or
  233. | ([^\s]+) # single_word
  234. )
  235. \s+ # separated by spaces
  236. # ---[ REPLACE ]---
  237. ( "([^"]*)" # "double quoted" or
  238. | '([^']*)' # 'single quoted' or
  239. | (.*) # anything
  240. )
  241. \s*$
  242. """, re.VERBOSE)
  243. match = cfgregex.match(text)
  244. if match:
  245. ret = {'name' :string.lower(match.group('name') or ''),
  246. 'target':string.lower(match.group('target') or 'all'),
  247. 'value' :match.group('value') }
  248. # Special config with two quoted values (%!preproc: "foo" 'bar')
  249. if ret['name'] in ['preproc','postproc']:
  250. valmatch = prepostregex.search(ret['value'])
  251. if not valmatch: return None
  252. getval = valmatch.group
  253. patt = getval(2) or getval(3) or getval(4) or ''
  254. repl = getval(6) or getval(7) or getval(8) or ''
  255. ret['value'] = (patt, repl)
  256. return ret
  257. class Cmdline:
  258. def __init__(self, cmdline=[], nocheck=0):
  259. self.conf = {}
  260. self.cmdline = cmdline
  261. self.cmdline_conf = {}
  262. self.dft_options = OPTIONS.copy()
  263. self.dft_flags = FLAGS.copy()
  264. self.all_options = self.dft_options.keys()
  265. self.all_flags = self.dft_flags.keys()
  266. self.defaults = self._get_empty_conf()
  267. self.nocheck = nocheck
  268. if cmdline: self.parse()
  269. #TODO protect quotes contents
  270. def _tokenize(self, cmd_string):
  271. return string.split(cmd_string)
  272. def parse(self):
  273. "return a dic with all options:value found"
  274. if not self.cmdline: return {}
  275. Debug("cmdline: %s"%self.cmdline, 1)
  276. options = {'infile': '', 'infiles':''}
  277. # compose valid options list
  278. longopts = ['help','version'] + self.all_flags + \
  279. map(lambda x:x+'=', self.all_options) # add =
  280. cmdline = self.cmdline[1:] # del prog name
  281. # get cmdline options
  282. try: (opt, args) = getopt.getopt(cmdline, 'hVnHt:o:', longopts)
  283. except getopt.GetoptError:
  284. Error('Bad option or missing argument (try --help)')
  285. # get infile, if any
  286. if args:
  287. options['infile'] = args[0]
  288. options['infiles'] = args # multi
  289. # parse all options
  290. for name,val in opt:
  291. if name in ['-h','--help' ]: Quit(usage)
  292. elif name in ['-V','--version']: Quit(versionstr)
  293. elif name in ['-t','--type' ]: options['type'] = val
  294. elif name in ['-o','--outfile' ]: options['outfile'] = val
  295. elif name in ['-n','--enumtitle']: options['enumtitle'] = 1
  296. elif name in ['-H','--noheaders']: options['noheaders'] = 1
  297. elif name in ['--stdout']: options['outfile'] = STDOUT
  298. else: options[name[2:]] = val or 1 # del --
  299. # save results
  300. Debug("cmdline arguments: %s"%options, 1)
  301. self.cmdline_conf = options
  302. def compose(self, conf={}):
  303. "compose full command line from CONF dict"
  304. if not conf: return ''
  305. args = []
  306. cfg = conf.copy()
  307. valid_opts = self.all_options + self.all_flags
  308. use_short = {'noheaders':'H', 'enumtitle':'n'}
  309. # remove useless options
  310. if cfg.get('toconly'):
  311. del cfg['noheaders']
  312. del cfg['outfile'] # defaults to STDOUT
  313. if cfg.get('type') == 'txt':
  314. del cfg['type'] # already default
  315. args.append('--toconly') # must be the first
  316. del cfg['toconly']
  317. # add target type
  318. if cfg.has_key('type'):
  319. args.append('-t '+cfg['type'])
  320. del cfg['type']
  321. # add other options
  322. for key in cfg.keys():
  323. if key not in valid_opts: continue # must be a %!setting
  324. if key == 'outfile': continue # later
  325. val = cfg[key]
  326. if not val: continue
  327. # default values are useless on cmdline
  328. if val == self.dft_options.get(key): continue
  329. # -short format
  330. if key in use_short.keys():
  331. args.append('-'+use_short[key])
  332. continue
  333. # --long format
  334. if key in self.all_flags: # add --option
  335. args.append('--'+key)
  336. else: # add --option=value
  337. args.append('--%s=%s'%(key,val))
  338. # the outfile using -o
  339. if cfg.has_key('outfile') and \
  340. cfg['outfile'] != self.dft_options.get('outfile'):
  341. args.append('-o '+cfg['outfile'])
  342. # the input file is always at the end
  343. if cfg.has_key('infile'):
  344. args.append(cfg['infile'])
  345. # return as a single string
  346. ret = string.join(args,' ')
  347. Debug("Diet command line: %s"%ret, 1)
  348. return ret
  349. def merge(self, extraopts=''):
  350. "insert cmdline portion BEFORE current cmdline"
  351. if not extraopts: return
  352. if type(extraopts) == type(''):
  353. extraopts = self._tokenize(extraopts)
  354. if not self.cmdline: self.cmdline = extraopts
  355. else: self.cmdline = ['t2t-merged'] +extraopts +self.cmdline[1:]
  356. self.parse()
  357. def _get_outfile_name(self, conf):
  358. "dirname is the same for {in,out}file"
  359. infile = conf['infile']
  360. if not infile: return ''
  361. if infile == STDIN or conf['outfile'] == STDOUT:
  362. outfile = STDOUT
  363. else:
  364. basename = re.sub('\.(txt|t2t)$','',infile)
  365. outfile = "%s.%s"%(basename, conf['type'])
  366. self.dft_options['outfile'] = outfile # save for self.compose()
  367. Debug(" infile: '%s'"%infile , 1)
  368. Debug("outfile: '%s'"%outfile, 1)
  369. return outfile
  370. def _sanity(self, dic):
  371. "basic cmdline syntax checkings"
  372. if not dic: return {}
  373. if not dic['infile'] or not dic['type']:
  374. Quit(usage, 1) # no filename/doctype
  375. if not targets.count(dic['type']): # check target
  376. Error("Invalid document type '%s' (try --help)"%(
  377. dic['type']))
  378. #DISABLED: conflicting with %!cmdline: -o foo
  379. #if len(dic['infiles']) > 1 and dic['outfile']: # -o FILE *.t2t
  380. # Error("--outfile can't be used with multiple files")
  381. for opt in self.all_options: # check numeric options
  382. opttype = type(self.dft_options[opt])
  383. if dic.get(opt) and opttype == type(9):
  384. try: dic[opt] = int(dic.get(opt)) # save
  385. except: Error('--%s value must be a number'%opt)
  386. if dic['split'] not in [0,1,2]: # check split level
  387. Error('Option --split must be 0, 1 or 2')
  388. return dic
  389. def merge_conf(self, newconfs={}, override=0):
  390. "include Config Area settings into self.conf"
  391. if not self.conf: self.get_conf()
  392. if not newconfs: return self.conf
  393. for key in newconfs.keys():
  394. if key == 'cmdline': continue # already done
  395. # filters are always accumulative
  396. if key in ['preproc','postproc']:
  397. if not self.conf.has_key(key):
  398. self.conf[key] = []
  399. self.conf[key].extend(newconfs[key])
  400. continue
  401. # add anyway
  402. if override:
  403. self.conf[key] = newconfs[key]
  404. continue
  405. # just update if still 'virgin'
  406. if self.conf.has_key(key) and \
  407. self.conf[key] == self.defaults.get(key):
  408. self.conf[key] = newconfs[key]
  409. # add new
  410. if not self.conf.has_key(key):
  411. self.conf[key] = newconfs[key]
  412. Debug("Merged CONF (override=%s): %s"%(override,self.conf), 1)
  413. return self.conf
  414. def _get_empty_conf(self):
  415. econf = self.dft_options.copy()
  416. for k in self.dft_flags.keys(): econf[k] = self.dft_flags[k]
  417. return econf
  418. def get_conf(self):
  419. "set vars and flags according to options dic"
  420. if not self.cmdline_conf:
  421. if not self.cmdline: return {}
  422. self.parse()
  423. dic = self.cmdline_conf
  424. conf = self.defaults.copy()
  425. ## store flags & options
  426. for flag in self.all_flags:
  427. if dic.has_key(flag): conf[flag] = 1
  428. for opt in self.all_options + ['infile', 'infiles']:
  429. if dic.has_key(opt): conf[opt] = dic.get(opt)
  430. if not conf['type'] and conf['toconly']: conf['type'] = 'txt'
  431. if not self.nocheck: conf = self._sanity(conf)
  432. ## some gotchas for specific issues
  433. doctype = conf['type']
  434. infile = conf['infile']
  435. # toconly is stronger than others
  436. if conf['toconly']:
  437. conf['noheaders'] = 1
  438. conf['toc'] = 0
  439. conf['split'] = 0
  440. conf['gui'] = 0
  441. conf['outfile'] = STDOUT
  442. conf['toclevel'] = conf['toclevel'] or \
  443. self.dft_options['toclevel']
  444. # split: just HTML, no stdout, 1st do a sgml, then sgml2html
  445. if conf['split']:
  446. if doctype != 'html':
  447. conf['split'] = 0
  448. else:
  449. conf['type'] = 'sgml'
  450. if conf['outfile'] == STDOUT:
  451. conf['outfile'] = ''
  452. outfile = conf['outfile'] or self._get_outfile_name(conf)
  453. # final checkings
  454. if conf['split'] and outfile == STDOUT:
  455. Error('--split: You must provide a FILE (not STDIN)')
  456. if infile == outfile and outfile != STDOUT:
  457. Error("SUICIDE WARNING!!! (see --outfile)\n source"+\
  458. " and target files has the same name: "+outfile)
  459. ### author's note: "yes, i've got my sample.t2t file deleted
  460. ### before add this test... :/"
  461. conf['outfile'] = outfile
  462. conf['cmdline'] = self.cmdline
  463. Debug("CONF data: %s\n"%conf, 1)
  464. self.conf = conf
  465. return self.conf
  466. #
  467. ### End of Cmdline class
  468. class Proprierties:
  469. def __init__(self, filename=''):
  470. self.buffer = [''] # text start at pos 1
  471. self.areas = ['head','conf','body']
  472. self.arearef = []
  473. self.headers = ['','','']
  474. self.config = self.get_empty_config()
  475. self.lastline = 0
  476. self.filename = filename
  477. self.conflines = []
  478. self.bodylines = []
  479. if filename:
  480. self.read_file(filename)
  481. self.find_areas()
  482. self.set_headers()
  483. self.set_config()
  484. def read_file(self, file):
  485. lines = Readfile(file)
  486. if not lines: Error('Empty file! %s'%file)
  487. self.buffer.extend(lines)
  488. def get_empty_config(self):
  489. empty = {}
  490. for targ in targets+['all']: empty[targ] = {}
  491. return empty
  492. def find_areas(self):
  493. "Run through buffer and identify head/conf/body areas"
  494. buf = self.buffer ; ref = [1,4,0] # defaults
  495. if not string.strip(buf[1]): # no header
  496. ref[0] = 0 ; ref[1] = 2
  497. for i in range(ref[1],len(buf)): # find body init
  498. if string.strip(buf[i]) and buf[i][0] != '%':
  499. ref[2] = i ; break # !blank, !comment
  500. if ref[1] == ref[2]: ref[1] = 0 # no conf area
  501. for i in 0,1,2: # del !existent
  502. if not ref[i]: self.areas[i] = ''
  503. self.arearef = ref # save results
  504. self.lastline = len(self.buffer)-1
  505. Debug('Head,Conf,Body start line: %s'%ref, 1)
  506. # store CONF and BODY lines found
  507. cfgend = ref[2] or len(buf)
  508. self.conflines = buf[ref[1]:cfgend]
  509. if ref[2]: self.bodylines = buf[ref[2]:]
  510. def set_headers(self):
  511. "Extract and save headers contents"
  512. if not self.arearef: self.find_areas()
  513. if not self.areas.count('head'): return
  514. if self.lastline < 3:
  515. #TODO on gui this checking is !working
  516. Error(
  517. "Premature end of Headers on '%s'."%self.filename +\
  518. '\n\nFile has %s line(s), but '%self.lastline +\
  519. 'Headers should be composed by 3 lines. ' +\
  520. '\nMaybe you should left the first line blank? ' +\
  521. '(for no headers)')
  522. for i in 0,1,2:
  523. self.headers[i] = string.strip(self.buffer[i+1])
  524. Debug("Headers found: %s"%self.headers, 1, i+1)
  525. def set_config(self):
  526. "Extract and save config contents (including includes)"
  527. if not self.arearef: self.find_areas()
  528. if not self.areas.count('conf'): return
  529. keywords = string.join(CONFIG_KEYWORDS, '|')
  530. linenr = self.arearef[1]-1 # for debug messages
  531. for line in self.conflines:
  532. linenr = linenr + 1
  533. if len(line) < 3: continue
  534. if line[:2] != '%!': continue
  535. cfg = ParseConfig(line, keywords)
  536. # any _valid_ config found?
  537. if not cfg:
  538. Debug('Bogus Config Line',1,linenr)
  539. continue
  540. # get data
  541. targ, key, val = cfg['target'],cfg['name'], cfg['value']
  542. # check config target specification
  543. if targ not in targets+['all']:
  544. Debug("Config Error: Invalid target '%s', ignoring"%targ,
  545. 1,linenr)
  546. continue
  547. # filters are multiple config
  548. if key in ['preproc','postproc']:
  549. if not self.config['all'].has_key(key): # 1st one
  550. self.config['all'][key] = []
  551. # all filters are saved to target 'all'
  552. # finish_him will decide what to consider
  553. self.config['all'][key].append((targ,)+val)
  554. else:
  555. self.config[targ][key] = val
  556. Debug("Found config for target '%s': '%s', value '%s'"%(
  557. targ,key,val),1,linenr)
  558. Debug("All %%!CONFIG: %s"%self.config, 1)
  559. def get_file_body(file):
  560. "Returns all the document BODY lines (including includes)"
  561. prop = Proprierties()
  562. prop.read_file(file)
  563. prop.find_areas()
  564. return prop.bodylines
  565. def finish_him(outlist, CONF):
  566. "Writing output to screen or file"
  567. outfile = CONF['outfile']
  568. outlist = unmaskEscapeChar(outlist)
  569. # do PostProc
  570. if CONF['postproc']:
  571. postoutlist = []
  572. for line in outlist:
  573. for targ,patt,repl in CONF['postproc']:
  574. if targ not in [CONF['type'], 'all']: continue
  575. line = re.sub(patt, repl, line)
  576. postoutlist.append(line)
  577. outlist = postoutlist[:]
  578. if outfile == STDOUT:
  579. for line in outlist: print line
  580. else:
  581. Savefile(outfile, addLineBreaks(outlist))
  582. if not CONF['gui']: print 'wrote %s'%(outfile)
  583. if CONF['split']:
  584. print "--- html..."
  585. sgml2html = 'sgml2html -s %s -l %s %s'%(
  586. CONF['split'],CONF['lang'] or lang,outfile)
  587. print "Running system command:", sgml2html
  588. os.system(sgml2html)
  589. def toc_maker(toc, conf):
  590. "Compose TOC list 'by hand'"
  591. # TOC is a tag, so there's nothing to do here
  592. if TAGS['TOC']: return []
  593. # toc is a valid t2t marked text (list type), that is converted
  594. if conf['toc'] or conf['toconly']:
  595. fakeconf = conf.copy()
  596. fakeconf['noheaders'] = 1
  597. fakeconf['toconly'] = 0
  598. fakeconf['maskemail'] = 0
  599. fakeconf['preproc'] = []
  600. fakeconf['postproc'] = []
  601. toc,foo = convert(toc, fakeconf)
  602. # TOC between bars (not for --toconly)
  603. if conf['toc']:
  604. para = TAGS['paragraph']
  605. tocbar = [para, regex['x'].sub('-'*72,TAGS['bar1']), para]
  606. toc = tocbar + toc + tocbar
  607. return toc
  608. def getTags(doctype):
  609. keys = [
  610. 'paragraph','title1','title2','title3','title4','title5',
  611. 'numtitle1','numtitle2','numtitle3','numtitle4','numtitle5',
  612. 'areaPreOpen','areaPreClose',
  613. 'areaQuoteOpen','areaQuoteClose',
  614. 'fontMonoOpen','fontMonoClose',
  615. 'fontBoldOpen','fontBoldClose',
  616. 'fontItalicOpen','fontItalicClose',
  617. 'fontBolditalicOpen','fontBolditalicClose',
  618. 'fontUnderlineOpen','fontUnderlineClose',
  619. 'listOpen','listClose','listItem',
  620. 'numlistOpen','numlistClose','numlistItem',
  621. 'deflistOpen','deflistClose','deflistItem1','deflistItem2',
  622. 'bar1','bar2',
  623. 'url','urlMark','email','emailMark',
  624. 'img','imgsolo',
  625. 'tableOpen','tableClose','tableLineOpen','tableLineClose',
  626. 'tableCellOpen','tableCellClose',
  627. 'tableTitleCellOpen','tableTitleCellClose',
  628. 'anchor','comment','TOC',
  629. 'EOD'
  630. ]
  631. alltags = {
  632. 'txt': {
  633. 'title1' : ' \a' ,
  634. 'title2' : '\t\a' ,
  635. 'title3' : '\t\t\a' ,
  636. 'title4' : '\t\t\t\a' ,
  637. 'title5' : '\t\t\t\t\a',
  638. 'areaQuoteOpen' : ' ' ,
  639. 'listItem' : '- ' ,
  640. 'numlistItem' : '\a. ' ,
  641. 'bar1' : '\a' ,
  642. 'bar2' : '\a' ,
  643. 'url' : '\a' ,
  644. 'urlMark' : '\a (\a)' ,
  645. 'email' : '\a' ,
  646. 'emailMark' : '\a (\a)' ,
  647. 'img' : '[\a]' ,
  648. },
  649. 'html': {
  650. 'paragraph' : '<P>' ,
  651. 'title1' : '<H1>\a</H1>' ,
  652. 'title2' : '<H2>\a</H2>' ,
  653. 'title3' : '<H3>\a</H3>' ,
  654. 'title4' : '<H4>\a</H4>' ,
  655. 'title5' : '<H5>\a</H5>' ,
  656. 'areaPreOpen' : '<PRE>' ,
  657. 'areaPreClose' : '</PRE>' ,
  658. 'areaQuoteOpen' : '<BLOCKQUOTE>' ,
  659. 'areaQuoteClose' : '</BLOCKQUOTE>' ,
  660. 'fontMonoOpen' : '<CODE>' ,
  661. 'fontMonoClose' : '</CODE>' ,
  662. 'fontBoldOpen' : '<B>' ,
  663. 'fontBoldClose' : '</B>' ,
  664. 'fontItalicOpen' : '<I>' ,
  665. 'fontItalicClose' : '</I>' ,
  666. 'fontBolditalicOpen' : '<B><I>' ,
  667. 'fontBolditalicClose' : '</I></B>' ,
  668. 'fontUnderlineOpen' : '<U>' ,
  669. 'fontUnderlineClose' : '</U>' ,
  670. 'listOpen' : '<UL>' ,
  671. 'listClose' : '</UL>' ,
  672. 'listItem' : '<LI>' ,
  673. 'numlistOpen' : '<OL>' ,
  674. 'numlistClose' : '</OL>' ,
  675. 'numlistItem' : '<LI>' ,
  676. 'deflistOpen' : '<DL>' ,
  677. 'deflistClose' : '</DL>' ,
  678. 'deflistItem1' : '<DT>\a</DT>' ,
  679. 'deflistItem2' : '<DD>' ,
  680. 'bar1' : '<HR NOSHADE SIZE=1>' ,
  681. 'bar2' : '<HR NOSHADE SIZE=5>' ,
  682. 'url' : '<A HREF="\a">\a</A>' ,
  683. 'urlMark' : '<A HREF="\a">\a</A>' ,
  684. 'email' : '<A HREF="mailto:\a">\a</A>' ,
  685. 'emailMark' : '<A HREF="mailto:\a">\a</A>' ,
  686. 'img' : '<IMG ALIGN="\a" SRC="\a" BORDER="0">',
  687. 'imgsolo' : '<P ALIGN="center">\a</P>' ,
  688. 'tableOpen' : '<table\a cellpadding=4 border=\a>',
  689. 'tableClose' : '</table>' ,
  690. 'tableLineOpen' : '<tr>' ,
  691. 'tableLineClose' : '</tr>' ,
  692. 'tableCellOpen' : '<td\a>' ,
  693. 'tableCellClose' : '</td>' ,
  694. 'tableTitleCellOpen' : '<th>' ,
  695. 'tableTitleCellClose' : '</th>' ,
  696. 'tableAlignLeft' : '' ,
  697. 'tableAlignCenter' : ' align="center"',
  698. 'tableCellAlignLeft' : '' ,
  699. 'tableCellAlignRight' : ' align="right"' ,
  700. 'tableCellAlignCenter': ' align="center"',
  701. 'anchor' : '<a name="\a"></a>',
  702. 'comment' : '<!-- \a -->' ,
  703. 'EOD' : '</BODY></HTML>'
  704. },
  705. 'sgml': {
  706. 'paragraph' : '<p>' ,
  707. 'title1' : '<sect>\a<p>' ,
  708. 'title2' : '<sect1>\a<p>' ,
  709. 'title3' : '<sect2>\a<p>' ,
  710. 'title4' : '<sect3>\a<p>' ,
  711. 'title5' : '<sect4>\a<p>' ,
  712. 'areaPreOpen' : '<tscreen><verb>' ,
  713. 'areaPreClose' : '</verb></tscreen>' ,
  714. 'areaQuoteOpen' : '<quote>' ,
  715. 'areaQuoteClose' : '</quote>' ,
  716. 'fontMonoOpen' : '<tt>' ,
  717. 'fontMonoClose' : '</tt>' ,
  718. 'fontBoldOpen' : '<bf>' ,
  719. 'fontBoldClose' : '</bf>' ,
  720. 'fontItalicOpen' : '<em>' ,
  721. 'fontItalicClose' : '</em>' ,
  722. 'fontBolditalicOpen' : '<bf><em>' ,
  723. 'fontBolditalicClose' : '</em></bf>' ,
  724. 'fontUnderlineOpen' : '<bf><em>' ,
  725. 'fontUnderlineClose' : '</em></bf>' ,
  726. 'listOpen' : '<itemize>' ,
  727. 'listClose' : '</itemize>' ,
  728. 'listItem' : '<item>' ,
  729. 'numlistOpen' : '<enum>' ,
  730. 'numlistClose' : '</enum>' ,
  731. 'numlistItem' : '<item>' ,
  732. 'deflistOpen' : '<descrip>' ,
  733. 'deflistClose' : '</descrip>' ,
  734. 'deflistItem1' : '<tag>\a</tag>' ,
  735. 'bar1' : '<!-- \a -->' ,
  736. 'bar2' : '<!-- \a -->' ,
  737. 'url' : '<htmlurl url="\a" name="\a">' ,
  738. 'urlMark' : '<htmlurl url="\a" name="\a">' ,
  739. 'email' : '<htmlurl url="mailto:\a" name="\a">' ,
  740. 'emailMark' : '<htmlurl url="mailto:\a" name="\a">' ,
  741. 'img' : '<figure><ph vspace=""><img src="\a">'+\
  742. '</figure>' ,
  743. 'tableOpen' : '<table><tabular ca="\a">' ,
  744. 'tableClose' : '</tabular></table>' ,
  745. 'tableLineClose' : '<rowsep>' ,
  746. 'tableCellClose' : '<colsep>' ,
  747. 'tableTitleCellClose' : '<colsep>' ,
  748. 'tableColAlignLeft' : 'l' ,
  749. 'tableColAlignRight' : 'r' ,
  750. 'tableColAlignCenter' : 'c' ,
  751. 'comment' : '<!-- \a -->' ,
  752. 'TOC' : '<toc>' ,
  753. 'EOD' : '</article>'
  754. },
  755. 'tex': {
  756. 'title1' : '\n\\newpage\section*{\a}',
  757. 'title2' : '\\subsection*{\a}' ,
  758. 'title3' : '\\subsubsection*{\a}' ,
  759. # title 4/5: DIRTY: para+BF+\\+\n
  760. 'title4' : '\\paragraph{}\\textbf{\a}\\\\\n',
  761. 'title5' : '\\paragraph{}\\textbf{\a}\\\\\n',
  762. 'numtitle1' : '\n\\newpage\section{\a}',
  763. 'numtitle2' : '\\subsection{\a}' ,
  764. 'numtitle3' : '\\subsubsection{\a}' ,
  765. 'areaPreOpen' : '\\begin{verbatim}' ,
  766. 'areaPreClose' : '\\end{verbatim}' ,
  767. 'areaQuoteOpen' : '\\begin{quotation}' ,
  768. 'areaQuoteClose' : '\\end{quotation}' ,
  769. 'fontMonoOpen' : '\\texttt{' ,
  770. 'fontMonoClose' : '}' ,
  771. 'fontBoldOpen' : '\\textbf{' ,
  772. 'fontBoldClose' : '}' ,
  773. 'fontItalicOpen' : '\\textit{' ,
  774. 'fontItalicClose' : '}' ,
  775. 'fontBolditalicOpen' : '\\textbf{\\textit{' ,
  776. 'fontBolditalicClose' : '}}' ,
  777. 'fontUnderlineOpen' : '\\underline{' ,
  778. 'fontUnderlineClose' : '}' ,
  779. 'listOpen' : '\\begin{itemize}' ,
  780. 'listClose' : '\\end{itemize}' ,
  781. 'listItem' : '\\item ' ,
  782. 'numlistOpen' : '\\begin{enumerate}' ,
  783. 'numlistClose' : '\\end{enumerate}' ,
  784. 'numlistItem' : '\\item ' ,
  785. 'deflistOpen' : '\\begin{description}',
  786. 'deflistClose' : '\\end{description}' ,
  787. 'deflistItem1' : '\\item[\a]' ,
  788. 'bar1' : '\n\\hrulefill{}\n' ,
  789. 'bar2' : '\n\\rule{\linewidth}{1mm}\n',
  790. 'url' : '\\url{\a}' ,
  791. 'urlMark' : '\\textit{\a} (\\url{\a})' ,
  792. 'email' : '\\url{\a}' ,
  793. 'emailMark' : '\\textit{\a} (\\url{\a})' ,
  794. 'img' : '\\begin{figure}\\includegraphics{\a}'+\
  795. '\\end{figure}',
  796. 'tableOpen' : '\\begin{center}\\begin{tabular}{\a|}',
  797. 'tableClose' : '\\end{tabular}\\end{center}',
  798. 'tableLineOpen' : '\\hline ' ,
  799. 'tableLineClose' : ' \\\\' ,
  800. 'tableCellClose' : ' & ' ,
  801. 'tableTitleCellOpen' : '\\textbf{',
  802. 'tableTitleCellClose' : '} & ' ,
  803. 'tableColAlignLeft' : '|l' ,
  804. 'tableColAlignRight' : '|r' ,
  805. 'tableColAlignCenter' : '|c' ,
  806. 'comment' : '% \a' ,
  807. 'TOC' : '\\newpage\\tableofcontents',
  808. 'EOD' : '\\end{document}'
  809. },
  810. 'moin': {
  811. 'title1' : '= \a =' ,
  812. 'title2' : '== \a ==' ,
  813. 'title3' : '=== \a ===' ,
  814. 'title4' : '==== \a ====' ,
  815. 'title5' : '===== \a =====',
  816. 'areaPreOpen' : '{{{' ,
  817. 'areaPreClose' : '}}}' ,
  818. 'areaQuoteOpen' : ' ' ,
  819. 'fontMonoOpen' : '{{{' ,
  820. 'fontMonoClose' : '}}}' ,
  821. 'fontBoldOpen' : "'''" ,
  822. 'fontBoldClose' : "'''" ,
  823. 'fontItalicOpen' : "''" ,
  824. 'fontItalicClose' : "''" ,
  825. 'fontBolditalicOpen' : "'''''" ,
  826. 'fontBolditalicClose' : "'''''" ,
  827. 'fontUnderlineOpen' : "'''''" ,
  828. 'fontUnderlineClose' : "'''''" ,
  829. 'listItem' : '* ' ,
  830. 'numlistItem' : '\a. ' ,
  831. 'bar1' : '----' ,
  832. 'bar2' : '----' ,
  833. 'url' : '[\a]' ,
  834. 'urlMark' : '[\a \a]' ,
  835. 'email' : '[\a]' ,
  836. 'emailMark' : '[\a \a]' ,
  837. 'img' : '[\a]' ,
  838. 'tableLineOpen' : '||' ,
  839. 'tableCellClose' : '||' ,
  840. 'tableTitleCellClose' : '||'
  841. },
  842. 'mgp': {
  843. 'paragraph' : '%font "normal", size 5\n' ,
  844. 'title1' : '%page\n\n\a' ,
  845. 'title2' : '%page\n\n\a' ,
  846. 'title3' : '%page\n\n\a' ,
  847. 'title4' : '%page\n\n\a' ,
  848. 'title5' : '%page\n\n\a' ,
  849. 'areaPreOpen' : '\n%font "mono"' ,
  850. 'areaPreClose' : '%font "normal"' ,
  851. 'areaQuoteOpen' : '%prefix " "' ,
  852. 'areaQuoteClose' : '%prefix " "' ,
  853. 'fontMonoOpen' : '\n%cont, font "mono"\n' ,
  854. 'fontMonoClose' : '\n%cont, font "normal"\n' ,
  855. 'fontBoldOpen' : '\n%cont, font "normal-b"\n' ,
  856. 'fontBoldClose' : '\n%cont, font "normal"\n' ,
  857. 'fontItalicOpen' : '\n%cont, font "normal-i"\n' ,
  858. 'fontItalicClose' : '\n%cont, font "normal"\n' ,
  859. 'fontBolditalicOpen' : '\n%cont, font "normal-bi"\n',
  860. 'fontBolditalicClose' : '\n%cont, font "normal"\n' ,
  861. 'fontUnderlineOpen' : '\n%cont, fore "cyan"\n' ,
  862. 'fontUnderlineClose' : '\n%cont, fore "white"\n' ,
  863. 'numlistItem' : '\a. ' ,
  864. 'bar1' : '%bar "white" 5' ,
  865. 'bar2' : '%pause' ,
  866. 'url' : '\n%cont, fore "cyan"\n\a' +\
  867. '\n%cont, fore "white"\n' ,
  868. 'urlMark' : '\a \n%cont, fore "cyan"\n\a'+\
  869. '\n%cont, fore "white"\n' ,
  870. 'email' : '\n%cont, fore "cyan"\n\a' +\
  871. '\n%cont, fore "white"\n' ,
  872. 'emailMark' : '\a \n%cont, fore "cyan"\n\a'+\
  873. '\n%cont, fore "white"\n' ,
  874. 'img' : '\n%center\n%newimage "\a", left\n',
  875. 'comment' : '%% \a' ,
  876. 'EOD' : '%%EOD'
  877. },
  878. 'man': {
  879. 'paragraph' : '.P' ,
  880. 'title1' : '.SH \a' ,
  881. 'title2' : '.SS \a' ,
  882. 'title3' : '.SS \a' ,
  883. 'title4' : '.SS \a' ,
  884. 'title5' : '.SS \a' ,
  885. 'areaPreOpen' : '.nf' ,
  886. 'areaPreClose' : '.fi\n' ,
  887. 'areaQuoteOpen' : '\n' ,
  888. 'areaQuoteClose' : '\n' ,
  889. 'fontBoldOpen' : '\\fB' ,
  890. 'fontBoldClose' : '\\fP' ,
  891. 'fontItalicOpen' : '\\fI' ,
  892. 'fontItalicClose' : '\\fP' ,
  893. 'fontBolditalicOpen' : '\\fI' ,
  894. 'fontBolditalicClose' : '\\fP' ,
  895. 'listOpen' : '\n.nf' , # pre
  896. 'listClose' : '.fi\n' ,
  897. 'listItem' : '* ' ,
  898. 'numlistOpen' : '\n.nf' , # pre
  899. 'numlistClose' : '.fi\n' ,
  900. 'numlistItem' : '\a. ' ,
  901. 'bar1' : '\n\n' ,
  902. 'bar2' : '\n\n' ,
  903. 'url' : '\a' ,
  904. 'urlMark' : '\a (\a)',
  905. 'email' : '\a' ,
  906. 'emailMark' : '\a (\a)',
  907. 'img' : '\a' ,
  908. 'comment' : '.\\" \a'
  909. },
  910. 'pm6': {
  911. 'paragraph' : '<@Normal:>' ,
  912. 'title1' : '\n<@Title1:>\a',
  913. 'title2' : '\n<@Title2:>\a',
  914. 'title3' : '\n<@Title3:>\a',
  915. 'title4' : '\n<@Title4:>\a',
  916. 'title5' : '\n<@Title5:>\a',
  917. 'areaPreOpen' : '<@PreFormat:>' ,
  918. 'areaQuoteOpen' : '<@Quote:>' ,
  919. 'fontMonoOpen' : '<FONT "Lucida Console"><SIZE 9>' ,
  920. 'fontMonoClose' : '<SIZE$><FONT$>',
  921. 'fontBoldOpen' : '<B>' ,
  922. 'fontBoldClose' : '<P>' ,
  923. 'fontItalicOpen' : '<I>' ,
  924. 'fontItalicClose' : '<P>' ,
  925. 'fontBolditalicOpen' : '<B><I>' ,
  926. 'fontBolditalicClose' : '<P>' ,
  927. 'fontUnderlineOpen' : '<U>' ,
  928. 'fontUnderlineClose' : '<P>' ,
  929. 'listOpen' : '<@Bullet:>' ,
  930. 'listItem' : '\x95 ' , # \x95 == ~U
  931. 'numlistOpen' : '<@Bullet:>' ,
  932. 'numlistItem' : '\x95 ' ,
  933. 'bar1' : '\a' ,
  934. 'bar2' : '\a' ,
  935. 'url' : '<U>\a<P>' , # underline
  936. 'urlMark' : '\a <U>\a<P>' ,
  937. 'email' : '\a' ,
  938. 'emailMark' : '\a \a' ,
  939. 'img' : '\a'
  940. }
  941. }
  942. # compose the target tags dictionary
  943. tags = {}
  944. target_tags = alltags[doctype]
  945. for key in keys: tags[key] = '' # create empty keys
  946. for key in target_tags.keys():
  947. tags[key] = maskEscapeChar(target_tags[key]) # populate
  948. return tags
  949. def getRules(doctype):
  950. ret = {}
  951. allrules = [
  952. # target rules (ON/OFF)
  953. 'linkable', # target supports external links
  954. 'tableable', # target supports tables
  955. 'imglinkable', # target supports images as links
  956. 'imgalignable', # target supports image alignment
  957. 'imgasdefterm', # target supports image as definition term
  958. 'tablealignable', # target supports table alignment
  959. 'autonumberlist', # target supports numbered lists natively
  960. 'autonumbertitle', # target supports numbered titles natively
  961. 'tablecellsplit', # place delimiters only *between* cells
  962. 'listnotnested', # lists cannot be nested
  963. 'quotenotnested', # quotes cannot be nested
  964. 'preareanotescaped', # don't escape specials in PRE area
  965. 'escapeurl', # escape special in link URL
  966. # target code beautify (ON/OFF)
  967. 'indentprearea', # add leading spaces to PRE area lines
  968. 'breaktablecell', # break lines after any table cell
  969. 'breaktablelineopen', # break line after opening table line
  970. 'keepquoteindent', # don't remove the leading TABs on quotes
  971. # value settings
  972. 'listmaxdepth', # maximum depth for lists
  973. 'tablecellaligntype' # type of table cell align: cell, column
  974. ]
  975. rules = {
  976. 'txt' : {
  977. 'indentprearea':1
  978. },
  979. 'html': {
  980. 'indentprearea':1,
  981. 'linkable':1,
  982. 'imglinkable':1,
  983. 'imgalignable':1,
  984. 'imgasdefterm':1,
  985. 'autonumberlist':1,
  986. 'tableable':1,
  987. 'breaktablecell':1,
  988. 'breaktablelineopen':1,
  989. 'keepquoteindent':1,
  990. 'tablealignable':1,
  991. 'tablecellaligntype':'cell'
  992. },
  993. 'sgml': {
  994. 'linkable':1,
  995. 'escapeurl':1,
  996. 'autonumberlist':1,
  997. 'tableable':1,
  998. 'tablecellsplit':1,
  999. 'quotenotnested':1,
  1000. 'keepquoteindent':1,
  1001. 'tablecellaligntype':'column'
  1002. },
  1003. 'mgp' : {
  1004. },
  1005. 'tex' : {
  1006. 'autonumberlist':1,
  1007. 'autonumbertitle':1,
  1008. 'tableable':1,
  1009. 'tablecellsplit':1,
  1010. 'preareanotescaped':1,
  1011. 'listmaxdepth':4,
  1012. 'tablecellaligntype':'column'
  1013. },
  1014. 'moin': {
  1015. 'linkable':1,
  1016. 'tableable':1
  1017. },
  1018. 'man' : {
  1019. 'indentprearea':1,
  1020. 'listnotnested':1
  1021. },
  1022. 'pm6' : {
  1023. }
  1024. }
  1025. # populate return dictionary
  1026. myrules = rules[doctype]
  1027. for key in allrules : ret[key] = 0 # reset all
  1028. for key in myrules.keys(): ret[key] = myrules[key] # turn ON
  1029. return ret
  1030. def getRegexes():
  1031. regex = {
  1032. # extra at end: (\[(?P<label>\w+)\])?
  1033. 'title':
  1034. re.compile(r'^\s*(?P<id>={1,5})(?P<txt>[^=].*[^=])\1\s*$'),
  1035. 'numtitle':
  1036. re.compile(r'^\s*(?P<id>\+{1,5})(?P<txt>[^+].*[^+])\1\s*$'),
  1037. 'areaPreOpen':
  1038. re.compile(r'^---$'),
  1039. 'areaPreClose':
  1040. re.compile(r'^---$'),
  1041. 'quote':
  1042. re.compile(r'^\t+'),
  1043. '1linePre':
  1044. re.compile(r'^--- (?=.)'),
  1045. 'fontMono':
  1046. re.compile(r'`([^`]+)`'),
  1047. 'fontBold':
  1048. re.compile(r'\*\*([^\s*].*?)\*\*'),
  1049. 'fontItalic':
  1050. re.compile(r'(^|[^:])//([^ /].*?)//'),
  1051. 'fontUnderline':
  1052. re.compile(r'__([^_].*?)__'), # underline lead/trailing blank
  1053. 'fontBolditalic':
  1054. re.compile(r'\*/([^/].*?)/\*'),
  1055. 'list':
  1056. re.compile(r'^( *)([+-]) ([^ ])'),
  1057. 'deflist':
  1058. re.compile(r'^( *)(=) ([^:]+):'),
  1059. 'bar':
  1060. re.compile(r'^\s*([_=-]{20,})\s*$'),
  1061. 'table':
  1062. re.compile(r'^ *\|\|? '),
  1063. 'blankline':
  1064. re.compile(r'^\s*$'),
  1065. 'comment':
  1066. re.compile(r'^%'),
  1067. 'raw':
  1068. re.compile(r'``(.+?)``')
  1069. }
  1070. # special char to place data on TAGs contents (\a == bell)
  1071. regex['x'] = re.compile('\a')
  1072. # %%date [ (formatting) ]
  1073. regex['date'] = re.compile(r'%%date\b(\((?P<fmt>.*?)\))?', re.I)
  1074. ### complicated regexes begin here ;)
  1075. #
  1076. # textual descriptions on --help's style: [...] is optional, | is OR
  1077. ### first, some auxiliar variables
  1078. #
  1079. # [image.EXT]
  1080. patt_img = r'\[([\w_,.+%$#@!?+~/-]+\.(png|jpe?g|gif|eps|bmp))\]'
  1081. # link things
  1082. urlskel = {
  1083. 'proto' : r'(https?|ftp|news|telnet|gopher|wais)://',
  1084. 'guess' : r'(www[23]?|ftp)\.', # w/out proto, try to guess
  1085. 'login' : r'A-Za-z0-9_.-', # for ftp://login@domain.com
  1086. 'pass' : r'[^ @]*', # for ftp://login:password@dom.com
  1087. 'chars' : r'A-Za-z0-9%._/~:,=$@-',# %20(space), :80(port)
  1088. 'anchor': r'A-Za-z0-9%._-', # %nn(encoded)
  1089. 'form' : r'A-Za-z0-9/%&=+.,@*_-',# .,@*_-(as is)
  1090. 'punct' : r'.,;:!?'
  1091. }
  1092. # username [ :password ] @
  1093. patt_url_login = r'([%s]+(:%s)?@)?'%(urlskel['login'],urlskel['pass'])
  1094. # [ http:// ] [ username:password@ ] domain.com [ / ]
  1095. # [ #anchor | ?form=data ]
  1096. retxt_url = r'\b(%s%s|%s)[%s]+\b/*(\?[%s]+)?(#[%s]+)?'%(
  1097. urlskel['proto'],patt_url_login, urlskel['guess'],
  1098. urlskel['chars'],urlskel['form'],urlskel['anchor'])
  1099. # filename | [ filename ] #anchor
  1100. retxt_url_local = r'[%s]+|[%s]*(#[%s]+)'%(
  1101. urlskel['chars'],urlskel['chars'],urlskel['anchor'])
  1102. # user@domain [ ?form=data ]
  1103. patt_email = r'\b[%s]+@([A-Za-z0-9_-]+\.)+[A-Za-z]{2,4}\b(\?[%s]+)?'%(
  1104. urlskel['login'],urlskel['form'])
  1105. # saving for future use
  1106. regex['_urlskel'] = urlskel
  1107. ### and now the real regexes
  1108. #
  1109. regex['email'] = re.compile(patt_email,re.I)
  1110. # email | url
  1111. regex['link'] = \
  1112. re.compile(r'%s|%s'%(retxt_url,patt_email), re.I)
  1113. # \[ label | imagetag url | email | filename \]
  1114. regex['linkmark'] = \
  1115. re.compile(r'\[(?P<label>%s|[^]]+) (?P<link>%s|%s|%s)\]'%(
  1116. patt_img, retxt_url, patt_email, retxt_url_local),
  1117. re.L+re.I)
  1118. # image
  1119. regex['img'] = re.compile(patt_img, re.L+re.I)
  1120. # all macros
  1121. regex['macro'] = regex['date']
  1122. # special things
  1123. regex['special'] = re.compile(r'^%!\s*')
  1124. regex['command'] = re.compile(r'(Include)\s*:\s*(.+)\s*$',re.I)
  1125. return regex
  1126. ### END OF regex nightmares
  1127. class SubareaMaster:
  1128. def __init__(self) : self.x = []
  1129. def __call__(self) :
  1130. if not self.x: return ''
  1131. return self.x[-1]
  1132. def add(self, area):
  1133. if not self.x or (self.x and self.x[-1] != area):
  1134. self.x.append(area)
  1135. Debug('subarea ++ (%s): %s' % (area,self.x), 1)
  1136. def pop(self, area=None):
  1137. if area and self.x[-1] == area: self.x.pop()
  1138. Debug('subarea -- (%s): %s' % (area,self.x), 1)
  1139. def doHeader(headers, CONF):
  1140. if CONF['noheaders']: return []
  1141. doctype = CONF['type']
  1142. if not HEADER_TEMPLATE.has_key(doctype):
  1143. Error("doheader: Unknow doctype '%s'"%doctype)
  1144. template = string.split(HEADER_TEMPLATE[doctype], '\n')
  1145. head_data = {'STYLE':'', 'ENCODING':''}
  1146. for key in head_data.keys():
  1147. val = CONF.get(string.lower(key))
  1148. if key == 'ENCODING': val = get_encoding_string(val, doctype)
  1149. head_data[key] = val
  1150. # parse header contents
  1151. for i in 0,1,2:
  1152. contents = doDateMacro(headers[i]) # expand %%date
  1153. # Escapes - on tex, just do it if any \tag{} present
  1154. if doctype != 'tex' or \
  1155. (doctype == 'tex' and re.search(r'\\\w+{', contents)):
  1156. contents = doEscape(doctype, contents)
  1157. head_data['HEADER%d'%(i+1)] = contents
  1158. Debug("Header Data: %s"%head_data, 1)
  1159. # scan for empty dictionary keys
  1160. # if found, scan template lines for that key reference
  1161. # if found, remove the reference
  1162. # if there isn't any other key reference on the same line, remove it
  1163. for key in head_data.keys():
  1164. if head_data.get(key): continue
  1165. for line in template:
  1166. if string.count(line, '%%(%s)s'%key):
  1167. sline = string.replace(line, '%%(%s)s'%key, '')
  1168. if not re.search(r'%\([A-Z0-9]+\)s', sline):
  1169. template.remove(line)
  1170. # populate template with data
  1171. template = string.join(template, '\n') % head_data
  1172. ### post processing
  1173. #
  1174. # let tex format today
  1175. if doctype == 'tex' and head_data['HEADER3'] == currdate:
  1176. template = re.sub(r'\\date\{.*?}', r'\date', template)
  1177. return string.split(template, '\n')
  1178. def doDateMacro(line):
  1179. re_date = getRegexes()['date']
  1180. while re_date.search(line):
  1181. m = re_date.search(line)
  1182. fmt = m.group('fmt') or ''
  1183. dateme = currdate
  1184. if fmt: dateme = strftime(fmt,localtime(time()))
  1185. line = re_date.sub(dateme,line,1)
  1186. return line
  1187. def doCommentLine(txt):
  1188. # the -- string ends a sgml/html comment :(
  1189. if string.count(TAGS['comment'], '--') and \
  1190. string.count(txt, '--'):
  1191. txt = re.sub('-(?=-)', r'-\\', txt)
  1192. if TAGS['comment']:
  1193. return regex['x'].sub(txt, TAGS['comment'])
  1194. return ''
  1195. def doFooter(CONF):
  1196. ret = []
  1197. doctype = CONF['type']
  1198. cmdline = CONF['cmdline']
  1199. typename = doctype
  1200. if doctype == 'tex': typename = 'LaTeX2e'
  1201. ppgd = '%s code generated by txt2tags %s (%s)'%(
  1202. typename,my_version,my_url)
  1203. cmdline = 'cmdline: txt2tags %s'%string.join(cmdline[1:], ' ')
  1204. ret.append('\n'+doCommentLine(ppgd))
  1205. ret.append(doCommentLine(cmdline))
  1206. ret.append(TAGS['EOD'])
  1207. return ret
  1208. # TODO mgp: any line (header or not) can't begin with % (add a space before)
  1209. def doEscape(doctype,txt):
  1210. if doctype in ['html','sgml']:
  1211. txt = re.sub('&','&amp;',txt)
  1212. txt = re.sub('<','&lt;',txt)
  1213. txt = re.sub('>','&gt;',txt)
  1214. if doctype == 'sgml':
  1215. txt = re.sub('\xff','&yuml;',txt) # "+y
  1216. elif doctype == 'pm6':
  1217. txt = re.sub('<','<\#60>',txt)
  1218. elif doctype == 'mgp':
  1219. txt = re.sub('^%',' %',txt) # add leading blank to avoid parse
  1220. elif doctype == 'man':
  1221. txt = re.sub("^([.'])", '\\&\\1',txt) # command ID
  1222. txt = string.replace(txt,ESCCHAR, ESCCHAR+'e') # \e
  1223. elif doctype == 'tex':
  1224. txt = string.replace(txt, ESCCHAR, '@@LaTeX-escaping-SUX@@')
  1225. txt = re.sub('([#$&%{}])', r'\\\1', txt)
  1226. txt = string.replace(txt, '~', maskEscapeChar(r'\~{}'))
  1227. txt = string.replace(txt, '^', maskEscapeChar(r'\^{}'))
  1228. txt = string.replace(txt, '@@LaTeX-escaping-SUX@@',
  1229. maskEscapeChar(r'$\backslash$'))
  1230. # TIP the _ is escaped at the end
  1231. return txt
  1232. def doFinalEscape(doctype, txt):
  1233. "Last escapes of each line"
  1234. if doctype == 'pm6' : txt = string.replace(txt,ESCCHAR+'<',r'<\#92><')
  1235. elif doctype == 'man' : txt = string.replace(txt, '-', r'\-')
  1236. elif doctype == 'tex' : txt = string.replace(txt, '_', r'\_')
  1237. elif doctype == 'sgml': txt = string.replace(txt, '[', '&lsqb;')
  1238. return txt
  1239. def EscapeCharHandler(action, data):
  1240. "Mask/Unmask the Escape Char on the given string"
  1241. if not string.strip(data): return data
  1242. if action not in ['mask','unmask']:
  1243. Error("EscapeCharHandler: Invalid action '%s'"%action)
  1244. if action == 'mask': return string.replace(data,'\\',ESCCHAR)
  1245. else: return string.replace(data,ESCCHAR,'\\')
  1246. def maskEscapeChar(data):
  1247. "Replace any Escape Char \ with a text mask (Input: str or list)"
  1248. if type(data) == type([]):
  1249. return map(lambda x: EscapeCharHandler('mask', x), data)
  1250. return EscapeCharHandler('mask',data)
  1251. def unmaskEscapeChar(data):
  1252. "Undo the Escape char \ masking (Input: str or list)"
  1253. if type(data) == type([]):
  1254. return map(lambda x: EscapeCharHandler('unmask', x), data)
  1255. return EscapeCharHandler('unmask',data)
  1256. def addLineBreaks(list):
  1257. "use LB to respect sys.platform"
  1258. ret = []
  1259. for line in list:
  1260. line = string.replace(line,'\n',LB) # embedded \n's
  1261. ret.append(line+LB) # add final line break
  1262. return ret
  1263. def doPreLine(doctype,line):
  1264. "Parsing procedures for preformatted (verbatim) lines"
  1265. if not rules['preareanotescaped']: line = doEscape(doctype,line)
  1266. if rules['indentprearea']: line = ' '+line
  1267. if doctype == 'pm6': line = doFinalEscape(doctype, line)
  1268. return line
  1269. def doCloseTable(doctype):
  1270. global subarea, tableborder
  1271. ret = ''
  1272. if rules['tableable']:
  1273. if doctype == 'tex' and tableborder:
  1274. ret = TAGS['tableLineOpen']+TAGS['tableClose']+'\n'
  1275. else:
  1276. ret = TAGS['tableClose']+'\n'
  1277. else:
  1278. ret = TAGS['areaPreClose']
  1279. tableborder = 0
  1280. subarea.pop('table')
  1281. return ret
  1282. def doCloseQuote(howmany=None):
  1283. global quotedepth
  1284. ret = []
  1285. if not howmany: howmany = len(quotedepth)
  1286. for i in range(howmany):
  1287. quotedepth.pop()
  1288. #TODO align open/close tag -> FREE_ALING_TAG = 1 (man not)
  1289. ret.append(TAGS['areaQuoteClose'])
  1290. if not quotedepth: subarea.pop('quote')
  1291. return string.join(ret,'\n')
  1292. def doCloseList(howmany=None):
  1293. global listindent, listids
  1294. ret

Large files files are truncated, but you can click here to view the full file