PageRenderTime 93ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/old/txt2tags-2.2.py

http://txt2tags.googlecode.com/
Python | 4517 lines | 4086 code | 160 blank | 271 comment | 157 complexity | 28f3e926696e9b98da7c6234906e4f9f MD5 | raw file
Possible License(s): GPL-2.0, GPL-3.0, WTFPL
  1. #!/usr/bin/env python
  2. # txt2tags - generic text conversion tool
  3. # http://txt2tags.sf.net
  4. #
  5. # Copyright 2001, 2002, 2003, 2004 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. #
  20. #
  21. # +-------------------------------------------------------------+
  22. # | IMPORTANT MESSAGES, PLEASE READ |
  23. # +-------------------------------------------------------------+
  24. # | |
  25. # | |
  26. # | v1.x COMPATIBILITY |
  27. # | ------------------ |
  28. # | |
  29. # | Due the major syntax changes, the new 2.x series |
  30. # | BREAKS backwards compatibility. |
  31. # | |
  32. # | Use the 't2tconv' script to upgrade your existing |
  33. # | v1.x files to conform the new v2.x syntax. |
  34. # | |
  35. # | Do a visual inspection on the new converted file. |
  36. # | Specially Pre & Post proc filters can break. |
  37. # | Check them! |
  38. # | |
  39. # | |
  40. # +-------------------------------------------------------------+
  41. #
  42. #
  43. ########################################################################
  44. #
  45. # BORING CODE EXPLANATION AHEAD
  46. #
  47. # Just read if you wish to understand how the txt2tags code works
  48. #
  49. ########################################################################
  50. #
  51. # Version 2.0 was a complete rewrite for the program 'core'.
  52. #
  53. # Now the code that [1] parses the marked text is separated from the
  54. # code that [2] insert the target tags.
  55. #
  56. # [1] made by: def convert()
  57. # [2] made by: class BlockMaster
  58. #
  59. # The structures of the marked text are identifyed and its contents are
  60. # extracted into a data holder (Python lists and dictionaries).
  61. #
  62. # When parsing the source file, the blocks (para, lists, quote, table)
  63. # are opened with BlockMaster, right when found. Then its contents,
  64. # which spans on several lines, are feeded into a special holder on the
  65. # BlockMaster instance. Just when the block is closed, the target tags
  66. # are inserted for the full block as a whole, in one pass. This way, we
  67. # have a better control on blocks. Much better than the previous line by
  68. # line approach.
  69. #
  70. # In other words, whenever inside a block, the parser *holds* the tag
  71. # insertion process, waiting until the full block is readed. That was
  72. # needed primary to close paragraphs for the new XHTML target, but
  73. # proved to be a very good adding, improving many other processings.
  74. #
  75. # -------------------------------------------------------------------
  76. #
  77. # There is also a brand new code for the Configuration schema, 100%
  78. # rewritten. There are new classes, all self documented: CommandLine,
  79. # SourceDocument, ConfigMaster and ConfigLines. In short, a new RAW
  80. # Config format was created, and all kind of configuration is first
  81. # converted to this format, and then a generic method parses it.
  82. #
  83. # The init processing was changed also, and now the functions which
  84. # gets informations about the input files are: get_infiles_config(),
  85. # process_source_file() and convert_this_files()
  86. #
  87. # Other parts are untouched, and remains the same as in v1.7, as the
  88. # marks regexes, target Headers and target Tags&Rules.
  89. #
  90. ########################################################################
  91. # Now I think the code is nice, easier to read and understand
  92. #XXX Python coding warning
  93. # Avoid common mistakes:
  94. # - do NOT use newlist=list instead newlist=list[:]
  95. # - do NOT use newdic=dic instead newdic=dic.copy()
  96. # - do NOT use dic[key] instead dic.get(key)
  97. # - do NOT use del dic[key] without has_key() before
  98. #XXX Smart Image Align don't work if the image is a link
  99. # Can't fix that because the image is expanded together with the
  100. # link, at the linkbank filling moment. Only the image is passed
  101. # to parse_images(), not the full line, so it is always 'middle'.
  102. #XXX Paragraph separation not valid inside Quote
  103. # Quote will not have <p></p> inside, instead will close and open
  104. # again the <blockquote>. This really sux in CSS, when defining a
  105. # diferent background color. Still don't know how to fix it.
  106. #XXX TODO (maybe)
  107. # New mark or macro which expands to an anchor full title.
  108. # It is necessary to parse the full document in this order:
  109. # DONE 1st scan: HEAD: get all settings, including %!includeconf
  110. # DONE 2nd scan: BODY: expand includes & apply %!preproc
  111. # 3rd scan: BODY: read titles and compose TOC info
  112. # 4th scan: BODY: full parsing, expanding [#anchor] 1st
  113. # Steps 2 and 3 can be made together, with no tag adding.
  114. # Two complete body scans will be *slow*, don't know if it worths.
  115. # One solution may be add the titles as postproc rules
  116. ##############################################################################
  117. # User config (1=ON, 0=OFF)
  118. USE_I18N = 1 # use gettext for i18ned messages? (default is 1)
  119. COLOR_DEBUG = 1 # show debug messages in colors? (default is 1)
  120. BG_LIGHT = 0 # your terminal background color is light (default is 0)
  121. HTML_LOWER = 0 # use lowercased HTML tags instead upper? (default is 0)
  122. ##############################################################################
  123. # these are all the core Python modules used by txt2tags (KISS!)
  124. import re, string, os, sys, time, getopt
  125. # program information
  126. my_url = 'http://txt2tags.sf.net'
  127. my_name = 'txt2tags'
  128. my_email = 'verde@aurelio.net'
  129. my_version = '2.2'
  130. # i18n - just use if available
  131. if USE_I18N:
  132. try:
  133. import gettext
  134. # if your locale dir is different, change it here
  135. cat = gettext.Catalog('txt2tags',localedir='/usr/share/locale/')
  136. _ = cat.gettext
  137. except:
  138. _ = lambda x:x
  139. else:
  140. _ = lambda x:x
  141. # FLAGS : the conversion related flags , may be used in %!options
  142. # OPTIONS : the conversion related options, may be used in %!options
  143. # ACTIONS : the other behaviour modifiers, valid on command line only
  144. # MACROS : the valid macros with their default values for formatting
  145. # SETTINGS: global miscelaneous settings, valid on RC file only
  146. # CONFIG_KEYWORDS: the valid %!key:val keywords
  147. #
  148. # FLAGS and OPTIONS are configs that affect the converted document.
  149. # They usually have also a --no-<option> to turn them OFF.
  150. # ACTIONS are needed because when doing multiple input files, strange
  151. # behaviour would be found, as use command line interface for the
  152. # first file and gui for the second. There is no --no-<action>.
  153. # --version and --help inside %!options are also odd
  154. #
  155. TARGETS = ['html', 'xhtml', 'sgml', 'tex', 'lout', 'man', 'mgp',
  156. 'moin', 'pm6' , 'txt']
  157. FLAGS = {'headers' :1 , 'enum-title' :0 , 'mask-email' :0 ,
  158. 'toc-only' :0 , 'toc' :0 , 'rc' :1 ,
  159. 'css-sugar' :0 , 'css-suggar' :0 , 'css-inside' :0 ,
  160. 'quiet' :0 }
  161. OPTIONS = {'target' :'', 'toc-level' :3 , 'style' :'',
  162. 'infile' :'', 'outfile' :'', 'encoding' :'',
  163. 'split' :0 , 'lang' :''}
  164. ACTIONS = {'help' :0 , 'version' :0 , 'gui' :0 ,
  165. 'verbose' :0 , 'debug' :0 , 'dump-config':0 }
  166. MACROS = {'date' : '%Y%m%d', 'infile': '%f',
  167. 'mtime': '%Y%m%d', 'outfile': '%f'}
  168. SETTINGS = {} # for future use
  169. CONFIG_KEYWORDS = [
  170. 'target', 'encoding', 'style', 'options', 'preproc','postproc',
  171. 'guicolors']
  172. TARGET_NAMES = {
  173. 'html' : _('HTML page'),
  174. 'xhtml': _('XHTML page'),
  175. 'sgml' : _('SGML document'),
  176. 'tex' : _('LaTeX document'),
  177. 'lout' : _('Lout document'),
  178. 'man' : _('UNIX Manual page'),
  179. 'mgp' : _('Magic Point presentation'),
  180. 'moin' : _('MoinMoin page'),
  181. 'pm6' : _('PageMaker 6.0 document'),
  182. 'txt' : _('Plain Text'),
  183. }
  184. DEBUG = 0 # do not edit here, please use --debug
  185. VERBOSE = 0 # do not edit here, please use -v, -vv or -vvv
  186. QUIET = 0 # do not edit here, please use --quiet
  187. GUI = 0 # do not edit here, please use --gui
  188. AUTOTOC = 1 # do not edit here, please use --no-toc or %%toc
  189. RC_RAW = []
  190. CMDLINE_RAW = []
  191. CONF = {}
  192. BLOCK = None
  193. regex = {}
  194. TAGS = {}
  195. rules = {}
  196. lang = 'english'
  197. TARGET = ''
  198. STDIN = STDOUT = '-'
  199. ESCCHAR = '\x00'
  200. SEPARATOR = '\x01'
  201. LISTNAMES = {'-':'list', '+':'numlist', ':':'deflist'}
  202. LINEBREAK = {'default':'\n', 'win':'\r\n', 'mac':'\r'}
  203. # plataform specific settings
  204. LB = LINEBREAK.get(sys.platform[:3]) or LINEBREAK['default']
  205. # identify a development version
  206. #dev_suffix = '-dev'+time.strftime('%m%d',time.localtime(time.time()))
  207. #my_version = my_version + dev_suffix
  208. VERSIONSTR = _("%s version %s <%s>")%(my_name,my_version,my_url)
  209. USAGE = string.join([
  210. '',
  211. _("Usage: %s [OPTIONS] [infile.t2t ...]") % my_name,
  212. '',
  213. _(" -t, --target=TYPE set target document type. currently supported:"),
  214. ' %s' % re.sub(r"[]'[]",'',repr(TARGETS)),
  215. _(" -i, --infile=FILE set FILE as the input file name ('-' for STDIN)"),
  216. _(" -o, --outfile=FILE set FILE as the output file name ('-' for STDOUT)"),
  217. _(" -n, --enum-title enumerate all title lines as 1, 1.1, 1.1.1, etc"),
  218. _(" -H, --no-headers suppress header, title and footer contents"),
  219. _(" --headers show header, title and footer contents (default ON)"),
  220. _(" --encoding=ENC set target file encoding (utf-8, iso-8859-1, etc)"),
  221. _(" --style=FILE use FILE as the document style (like HTML CSS)"),
  222. _(" --css-sugar insert CSS-friendly tags for HTML and XHTML targets"),
  223. _(" --css-inside insert CSS file contents inside HTML/XHTML headers"),
  224. _(" --mask-email hide email from spam robots. x@y.z turns <x (a) y z>"),
  225. _(" --toc add TOC (Table of Contents) to target document"),
  226. _(" --toc-only print document TOC and exit"),
  227. _(" --toc-level=N set maximum TOC level (depth) to N"),
  228. _(" --rc read user config file ~/.txt2tagsrc (default ON)"),
  229. _(" --gui invoke Graphical Tk Interface"),
  230. _(" -q, --quiet quiet mode, suppress all output (except errors)"),
  231. _(" -v, --verbose print informative messages during conversion"),
  232. _(" -h, --help print this help information and exit"),
  233. _(" -V, --version print program version and exit"),
  234. _(" --dump-config print all the config found and exit"),
  235. '',
  236. _("Turn OFF options:"),
  237. " --no-outfile, --no-infile, --no-style, --no-encoding, --no-headers",
  238. " --no-toc, --no-toc-only, --no-mask-email, --no-enum-title, --no-rc",
  239. " --no-css-sugar, --no-css-inside, --no-quiet",
  240. '',
  241. _("Example:\n %s -t html --toc myfile.t2t") % my_name,
  242. '',
  243. _("By default, converted output is saved to 'infile.<target>'."),
  244. _("Use --outfile to force an output file name."),
  245. _("If input file is '-', reads from STDIN."),
  246. _("If output file is '-', dumps output to STDOUT."),
  247. ''
  248. ], '\n')
  249. ##############################################################################
  250. # here is all the target's templates
  251. # you may edit them to fit your needs
  252. # - the %(HEADERn)s strings represent the Header lines
  253. # - the %(STYLE)s string is changed by --style contents
  254. # - the %(ENCODING)s string is changed by --encoding contents
  255. # - if any of the above is empty, the full line is removed
  256. # - use %% to represent a literal %
  257. #
  258. HEADER_TEMPLATE = {
  259. 'txt': """\
  260. %(HEADER1)s
  261. %(HEADER2)s
  262. %(HEADER3)s
  263. """,
  264. 'sgml': """\
  265. <!doctype linuxdoc system>
  266. <article>
  267. <title>%(HEADER1)s
  268. <author>%(HEADER2)s
  269. <date>%(HEADER3)s
  270. """,
  271. 'html': """\
  272. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  273. <HTML>
  274. <HEAD>
  275. <META NAME="generator" CONTENT="http://txt2tags.sf.net">
  276. <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=%(ENCODING)s">
  277. <LINK REL="stylesheet" TYPE="text/css" HREF="%(STYLE)s">
  278. <TITLE>%(HEADER1)s</TITLE>
  279. </HEAD><BODY BGCOLOR="white" TEXT="black">
  280. <P ALIGN="center"><CENTER><H1>%(HEADER1)s</H1>
  281. <FONT SIZE="4">
  282. <I>%(HEADER2)s</I><BR>
  283. %(HEADER3)s
  284. </FONT></CENTER>
  285. """,
  286. 'htmlcss': """\
  287. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  288. <HTML>
  289. <HEAD>
  290. <META NAME="generator" CONTENT="http://txt2tags.sf.net">
  291. <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=%(ENCODING)s">
  292. <LINK REL="stylesheet" TYPE="text/css" HREF="%(STYLE)s">
  293. <TITLE>%(HEADER1)s</TITLE>
  294. </HEAD>
  295. <BODY>
  296. <DIV CLASS="header" ID="header">
  297. <H1>%(HEADER1)s</H1>
  298. <H2>%(HEADER2)s</H2>
  299. <H3>%(HEADER3)s</H3>
  300. </DIV>
  301. """,
  302. 'xhtml': """\
  303. <?xml version="1.0"
  304. encoding="%(ENCODING)s"
  305. ?>
  306. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\
  307. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  308. <html xmlns="http://www.w3.org/1999/xhtml">
  309. <head>
  310. <title>%(HEADER1)s</title>
  311. <meta name="generator" content="http://txt2tags.sf.net" />
  312. <link rel="stylesheet" type="text/css" href="%(STYLE)s" />
  313. </head>
  314. <body bgcolor="white" text="black">
  315. <div align="center">
  316. <h1>%(HEADER1)s</h1>
  317. <h2>%(HEADER2)s</h2>
  318. <h3>%(HEADER3)s</h3>
  319. </div>
  320. """,
  321. 'xhtmlcss': """\
  322. <?xml version="1.0"?>
  323. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\
  324. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  325. <html xmlns="http://www.w3.org/1999/xhtml">
  326. <head>
  327. <title>%(HEADER1)s</title>
  328. <meta name="generator" content="http://txt2tags.sf.net" />
  329. <meta http-equiv="Content-Type" content="text/html; charset=%(ENCODING)s" />
  330. <link rel="stylesheet" type="text/css" href="%(STYLE)s" />
  331. </head>
  332. <body>
  333. <div class="header" id="header">
  334. <h1>%(HEADER1)s</h1>
  335. <h2>%(HEADER2)s</h2>
  336. <h3>%(HEADER3)s</h3>
  337. </div>
  338. """,
  339. 'man': """\
  340. .TH "%(HEADER1)s" 1 "%(HEADER3)s" "%(HEADER2)s"
  341. """,
  342. # TODO style to <HR>
  343. 'pm6': """\
  344. <PMTags1.0 win><C-COLORTABLE ("Preto" 1 0 0 0)
  345. ><@Normal=
  346. <FONT "Times New Roman"><CCOLOR "Preto"><SIZE 11>
  347. <HORIZONTAL 100><LETTERSPACE 0><CTRACK 127><CSSIZE 70><C+SIZE 58.3>
  348. <C-POSITION 33.3><C+POSITION 33.3><P><CBASELINE 0><CNOBREAK 0><CLEADING -0.05>
  349. <GGRID 0><GLEFT 7.2><GRIGHT 0><GFIRST 0><G+BEFORE 7.2><G+AFTER 0>
  350. <GALIGNMENT "justify"><GMETHOD "proportional"><G& "ENGLISH">
  351. <GPAIRS 12><G%% 120><GKNEXT 0><GKWIDOW 0><GKORPHAN 0><GTABS $>
  352. <GHYPHENATION 2 34 0><GWORDSPACE 75 100 150><GSPACE -5 0 25>
  353. ><@Bullet=<@-PARENT "Normal"><FONT "Abadi MT Condensed Light">
  354. <GLEFT 14.4><G+BEFORE 2.15><G%% 110><GTABS(25.2 l "")>
  355. ><@PreFormat=<@-PARENT "Normal"><FONT "Lucida Console"><SIZE 8><CTRACK 0>
  356. <GLEFT 0><G+BEFORE 0><GALIGNMENT "left"><GWORDSPACE 100 100 100><GSPACE 0 0 0>
  357. ><@Title1=<@-PARENT "Normal"><FONT "Arial"><SIZE 14><B>
  358. <GCONTENTS><GLEFT 0><G+BEFORE 0><GALIGNMENT "left">
  359. ><@Title2=<@-PARENT "Title1"><SIZE 12><G+BEFORE 3.6>
  360. ><@Title3=<@-PARENT "Title1"><SIZE 10><GLEFT 7.2><G+BEFORE 7.2>
  361. ><@Title4=<@-PARENT "Title3">
  362. ><@Title5=<@-PARENT "Title3">
  363. ><@Quote=<@-PARENT "Normal"><SIZE 10><I>>
  364. %(HEADER1)s
  365. %(HEADER2)s
  366. %(HEADER3)s
  367. """,
  368. 'mgp': """\
  369. #!/usr/X11R6/bin/mgp -t 90
  370. %%deffont "normal" xfont "utopia-medium-r", charset "iso8859-1"
  371. %%deffont "normal-i" xfont "utopia-medium-i", charset "iso8859-1"
  372. %%deffont "normal-b" xfont "utopia-bold-r" , charset "iso8859-1"
  373. %%deffont "normal-bi" xfont "utopia-bold-i" , charset "iso8859-1"
  374. %%deffont "mono" xfont "courier-medium-r", charset "iso8859-1"
  375. %%default 1 size 5
  376. %%default 2 size 8, fore "yellow", font "normal-b", center
  377. %%default 3 size 5, fore "white", font "normal", left, prefix " "
  378. %%tab 1 size 4, vgap 30, prefix " ", icon arc "red" 40, leftfill
  379. %%tab 2 prefix " ", icon arc "orange" 40, leftfill
  380. %%tab 3 prefix " ", icon arc "brown" 40, leftfill
  381. %%tab 4 prefix " ", icon arc "darkmagenta" 40, leftfill
  382. %%tab 5 prefix " ", icon arc "magenta" 40, leftfill
  383. %%%%------------------------- end of headers -----------------------------
  384. %%page
  385. %%size 10, center, fore "yellow"
  386. %(HEADER1)s
  387. %%font "normal-i", size 6, fore "white", center
  388. %(HEADER2)s
  389. %%font "mono", size 7, center
  390. %(HEADER3)s
  391. """,
  392. 'moin': """\
  393. '''%(HEADER1)s'''
  394. ''%(HEADER2)s''
  395. %(HEADER3)s
  396. """,
  397. 'tex': \
  398. r"""\documentclass[11pt,a4paper]{article}
  399. \usepackage{amsfonts,graphicx}
  400. \usepackage[pdfstartview=FitV,urlcolor=blue,colorlinks=true,bookmarks=true]{hyperref}
  401. \usepackage[%(ENCODING)s]{inputenc} %% char encoding
  402. \usepackage{%(STYLE)s} %% user defined package
  403. \pagestyle{plain} %% do page numbering ('empty' turns off)
  404. \frenchspacing %% no aditional spaces after periods
  405. \setlength{\parskip}{8pt}\parindent=0pt %% no paragraph indentation
  406. \title{%(HEADER1)s}
  407. \author{%(HEADER2)s}
  408. \begin{document}
  409. \date{%(HEADER3)s}
  410. \maketitle
  411. \clearpage
  412. """,
  413. 'lout': """\
  414. @SysInclude { doc }
  415. @Document
  416. @InitialFont { Times Base 12p } # Times, Courier, Helvetica, ...
  417. @PageOrientation { Portrait } # Portrait, Landscape
  418. @ColumnNumber { 1 } # Number of columns (2, 3, ...)
  419. @PageHeaders { Simple } # None, Simple, Titles, NoTitles
  420. @InitialLanguage { English } # German, French, Portuguese, ...
  421. @OptimizePages { Yes } # Yes/No smart page break feature
  422. //
  423. @Text @Begin
  424. @Display @Heading { %(HEADER1)s }
  425. @Display @I { %(HEADER2)s }
  426. @Display { %(HEADER3)s }
  427. #@NP # Break page after Headers
  428. """
  429. # @SysInclude { tbl } # Tables support
  430. # setup: @MakeContents { Yes } # show TOC
  431. # setup: @SectionGap # break page at each section
  432. }
  433. ##############################################################################
  434. def getTags(config):
  435. "Returns all the known tags for the specified target"
  436. keys = [
  437. 'paragraphOpen','paragraphClose',
  438. 'title1','title2','title3','title4','title5',
  439. 'title1Open','title1Close','title2Open','title2Close',
  440. 'blocktitle1Open','title1Close','title2Open','title2Close',
  441. 'title3Open','title3Close','title4Open','title4Close',
  442. 'title5Open','title5Close',
  443. 'numtitle1','numtitle2','numtitle3','numtitle4','numtitle5',
  444. 'blockVerbOpen','blockVerbClose',
  445. 'blockQuoteOpen','blockQuoteClose','blockQuoteLine',
  446. 'fontMonoOpen','fontMonoClose',
  447. 'fontBoldOpen','fontBoldClose',
  448. 'fontItalicOpen','fontItalicClose',
  449. 'fontUnderlineOpen','fontUnderlineClose',
  450. 'listOpen','listClose',
  451. 'listItemOpen','listItemClose','listItemLine',
  452. 'numlistOpen','numlistClose',
  453. 'numlistItemOpen','numlistItemClose','numlistItemLine',
  454. 'deflistOpen','deflistClose',
  455. 'deflistItem1Open','deflistItem1Close',
  456. 'deflistItem2Open','deflistItem2Close',
  457. 'bar1','bar2',
  458. 'url','urlMark','email','emailMark',
  459. 'img','imgAlignLeft','imgAlignRight','imgAlignCenter',
  460. 'tableOpen','tableClose',
  461. 'tableRowOpen','tableRowClose','tableRowSep',
  462. 'tableCellOpen','tableCellClose','tableCellSep',
  463. 'tableTitleCellOpen','tableTitleCellClose','tableTitleCellSep',
  464. 'tableTitleRowOpen','tableTitleRowClose',
  465. 'tableBorder', 'tableAlignLeft', 'tableAlignCenter',
  466. 'tableCellAlignLeft','tableCellAlignRight','tableCellAlignCenter',
  467. 'tableColAlignLeft','tableColAlignRight','tableColAlignCenter',
  468. 'tableColAlignSep',
  469. 'anchor','comment','pageBreak',
  470. 'TOC','tocOpen','tocClose',
  471. 'cssOpen', 'cssClose',
  472. 'bodyOpen','bodyClose',
  473. 'EOD'
  474. ]
  475. # TIP: \a represents the current text on the mark
  476. # TIP: ~A~, ~B~ and ~C~ are expanded to other tags parts
  477. alltags = {
  478. 'txt': {
  479. 'title1' : ' \a' ,
  480. 'title2' : '\t\a' ,
  481. 'title3' : '\t\t\a' ,
  482. 'title4' : '\t\t\t\a' ,
  483. 'title5' : '\t\t\t\t\a',
  484. 'blockQuoteLine' : '\t' ,
  485. 'listItemOpen' : '- ' ,
  486. 'numlistItemOpen' : '\a. ' ,
  487. 'bar1' : '\a' ,
  488. 'url' : '\a' ,
  489. 'urlMark' : '\a (\a)' ,
  490. 'email' : '\a' ,
  491. 'emailMark' : '\a (\a)' ,
  492. 'img' : '[\a]' ,
  493. },
  494. 'html': {
  495. 'paragraphOpen' : '<P>' ,
  496. 'paragraphClose' : '</P>' ,
  497. 'title1' : '~A~<H1>\a</H1>' ,
  498. 'title2' : '~A~<H2>\a</H2>' ,
  499. 'title3' : '~A~<H3>\a</H3>' ,
  500. 'title4' : '~A~<H4>\a</H4>' ,
  501. 'title5' : '~A~<H5>\a</H5>' ,
  502. 'blockVerbOpen' : '<PRE>' ,
  503. 'blockVerbClose' : '</PRE>' ,
  504. 'blockQuoteOpen' : '<BLOCKQUOTE>' ,
  505. 'blockQuoteClose' : '</BLOCKQUOTE>' ,
  506. 'fontMonoOpen' : '<CODE>' ,
  507. 'fontMonoClose' : '</CODE>' ,
  508. 'fontBoldOpen' : '<B>' ,
  509. 'fontBoldClose' : '</B>' ,
  510. 'fontItalicOpen' : '<I>' ,
  511. 'fontItalicClose' : '</I>' ,
  512. 'fontUnderlineOpen' : '<U>' ,
  513. 'fontUnderlineClose' : '</U>' ,
  514. 'listOpen' : '<UL>' ,
  515. 'listClose' : '</UL>' ,
  516. 'listItemOpen' : '<LI>' ,
  517. 'numlistOpen' : '<OL>' ,
  518. 'numlistClose' : '</OL>' ,
  519. 'numlistItemOpen' : '<LI>' ,
  520. 'deflistOpen' : '<DL>' ,
  521. 'deflistClose' : '</DL>' ,
  522. 'deflistItem1Open' : '<DT>' ,
  523. 'deflistItem1Close' : '</DT>' ,
  524. 'deflistItem2Open' : '<DD>' ,
  525. 'bar1' : '<HR NOSHADE SIZE=1>' ,
  526. 'bar2' : '<HR NOSHADE SIZE=5>' ,
  527. 'url' : '<A HREF="\a">\a</A>' ,
  528. 'urlMark' : '<A HREF="\a">\a</A>' ,
  529. 'email' : '<A HREF="mailto:\a">\a</A>' ,
  530. 'emailMark' : '<A HREF="mailto:\a">\a</A>' ,
  531. 'img' : '<IMG~A~ SRC="\a" BORDER="0" ALT="">',
  532. 'imgAlignLeft' : ' ALIGN="left"' ,
  533. 'imgAlignCenter' : ' ALIGN="middle"',
  534. 'imgAlignRight' : ' ALIGN="right"' ,
  535. 'tableOpen' : '<TABLE~A~ CELLPADDING="4"~B~>',
  536. 'tableClose' : '</TABLE>' ,
  537. 'tableRowOpen' : '<TR>' ,
  538. 'tableRowClose' : '</TR>' ,
  539. 'tableCellOpen' : '<TD\a>' ,
  540. 'tableCellClose' : '</TD>' ,
  541. 'tableTitleCellOpen' : '<TH>' ,
  542. 'tableTitleCellClose' : '</TH>' ,
  543. 'tableBorder' : ' BORDER="1"' ,
  544. 'tableAlignCenter' : ' ALIGN="center"',
  545. 'tableCellAlignRight' : ' ALIGN="right"' ,
  546. 'tableCellAlignCenter': ' ALIGN="center"',
  547. 'anchor' : '<A NAME="\a"></A>\n',
  548. 'cssOpen' : '<STYLE TYPE="text/css">',
  549. 'cssClose' : '</STYLE>' ,
  550. 'comment' : '<!-- \a -->' ,
  551. 'EOD' : '</BODY></HTML>'
  552. },
  553. #TIP xhtml inherits all HTML definitions (lowercased)
  554. #TIP http://www.w3.org/TR/xhtml1/#guidelines
  555. #TIP http://www.htmlref.com/samples/Chapt17/17_08.htm
  556. 'xhtml': {
  557. 'listItemClose' : '</li>' ,
  558. 'numlistItemClose' : '</li>' ,
  559. 'deflistItem2Close' : '</dd>' ,
  560. 'bar1' : '<hr class="light" />',
  561. 'bar2' : '<hr class="heavy" />',
  562. 'anchor' : '<a id="\a" name="\a"></a>\n',
  563. 'img' : '<img~A~ src="\a" border="0" alt=""/>',
  564. },
  565. 'sgml': {
  566. 'paragraphOpen' : '<p>' ,
  567. 'title1' : '<sect>\a~A~<p>' ,
  568. 'title2' : '<sect1>\a~A~<p>' ,
  569. 'title3' : '<sect2>\a~A~<p>' ,
  570. 'title4' : '<sect3>\a~A~<p>' ,
  571. 'title5' : '<sect4>\a~A~<p>' ,
  572. 'blockVerbOpen' : '<tscreen><verb>' ,
  573. 'blockVerbClose' : '</verb></tscreen>' ,
  574. 'blockQuoteOpen' : '<quote>' ,
  575. 'blockQuoteClose' : '</quote>' ,
  576. 'fontMonoOpen' : '<tt>' ,
  577. 'fontMonoClose' : '</tt>' ,
  578. 'fontBoldOpen' : '<bf>' ,
  579. 'fontBoldClose' : '</bf>' ,
  580. 'fontItalicOpen' : '<em>' ,
  581. 'fontItalicClose' : '</em>' ,
  582. 'fontUnderlineOpen' : '<bf><em>' ,
  583. 'fontUnderlineClose' : '</em></bf>' ,
  584. 'listOpen' : '<itemize>' ,
  585. 'listClose' : '</itemize>' ,
  586. 'listItemOpen' : '<item>' ,
  587. 'numlistOpen' : '<enum>' ,
  588. 'numlistClose' : '</enum>' ,
  589. 'numlistItemOpen' : '<item>' ,
  590. 'deflistOpen' : '<descrip>' ,
  591. 'deflistClose' : '</descrip>' ,
  592. 'deflistItem1Open' : '<tag>' ,
  593. 'deflistItem1Close' : '</tag>' ,
  594. 'bar1' : '<!-- \a -->' ,
  595. 'url' : '<htmlurl url="\a" name="\a">' ,
  596. 'urlMark' : '<htmlurl url="\a" name="\a">' ,
  597. 'email' : '<htmlurl url="mailto:\a" name="\a">' ,
  598. 'emailMark' : '<htmlurl url="mailto:\a" name="\a">' ,
  599. 'img' : '<figure><ph vspace=""><img src="\a">'+\
  600. '</figure>' ,
  601. 'tableOpen' : '<table><tabular ca="~C~">' ,
  602. 'tableClose' : '</tabular></table>' ,
  603. 'tableRowSep' : '<rowsep>' ,
  604. 'tableCellSep' : '<colsep>' ,
  605. 'tableColAlignLeft' : 'l' ,
  606. 'tableColAlignRight' : 'r' ,
  607. 'tableColAlignCenter' : 'c' ,
  608. 'comment' : '<!-- \a -->' ,
  609. 'anchor' : '<label id="\a">' ,
  610. 'TOC' : '<toc>' ,
  611. 'EOD' : '</article>'
  612. },
  613. 'tex': {
  614. 'title1' : '\n\section*{\a}' ,
  615. 'title2' : '\\subsection*{\a}' ,
  616. 'title3' : '\\subsubsection*{\a}',
  617. # title 4/5: DIRTY: para+BF+\\+\n
  618. 'title4' : '\\paragraph{}\\textbf{\a}\\\\\n',
  619. 'title5' : '\\paragraph{}\\textbf{\a}\\\\\n',
  620. 'numtitle1' : '\n\section{\a}' ,
  621. 'numtitle2' : '\\subsection{\a}' ,
  622. 'numtitle3' : '\\subsubsection{\a}' ,
  623. 'blockVerbOpen' : '\\begin{verbatim}' ,
  624. 'blockVerbClose' : '\\end{verbatim}' ,
  625. 'blockQuoteOpen' : '\\begin{quotation}' ,
  626. 'blockQuoteClose' : '\\end{quotation}' ,
  627. 'fontMonoOpen' : '\\texttt{' ,
  628. 'fontMonoClose' : '}' ,
  629. 'fontBoldOpen' : '\\textbf{' ,
  630. 'fontBoldClose' : '}' ,
  631. 'fontItalicOpen' : '\\textit{' ,
  632. 'fontItalicClose' : '}' ,
  633. 'fontUnderlineOpen' : '\\underline{' ,
  634. 'fontUnderlineClose' : '}' ,
  635. 'listOpen' : '\\begin{itemize}' ,
  636. 'listClose' : '\\end{itemize}' ,
  637. 'listItemOpen' : '\\item ' ,
  638. 'numlistOpen' : '\\begin{enumerate}' ,
  639. 'numlistClose' : '\\end{enumerate}' ,
  640. 'numlistItemOpen' : '\\item ' ,
  641. 'deflistOpen' : '\\begin{description}',
  642. 'deflistClose' : '\\end{description}' ,
  643. 'deflistItem1Open' : '\\item[' ,
  644. 'deflistItem1Close' : ']' ,
  645. 'bar1' : '\n\\hrulefill{}\n' ,
  646. 'bar2' : '\n\\rule{\linewidth}{1mm}\n',
  647. 'url' : '\\htmladdnormallink{\a}{\a}',
  648. 'urlMark' : '\\htmladdnormallink{\a}{\a}',
  649. 'email' : '\\htmladdnormallink{\a}{mailto:\a}',
  650. 'emailMark' : '\\htmladdnormallink{\a}{mailto:\a}',
  651. 'img' : '\\includegraphics{\a}',
  652. 'tableOpen' : '\\begin{center}\\begin{tabular}{|~C~|}',
  653. 'tableClose' : '\\end{tabular}\\end{center}',
  654. 'tableRowOpen' : '\\hline ' ,
  655. 'tableRowClose' : ' \\\\' ,
  656. 'tableCellSep' : ' & ' ,
  657. 'tableColAlignLeft' : 'l' ,
  658. 'tableColAlignRight' : 'r' ,
  659. 'tableColAlignCenter' : 'c' ,
  660. 'tableColAlignSep' : '|' ,
  661. 'comment' : '% \a' ,
  662. 'TOC' : '\\tableofcontents',
  663. 'pageBreak' : '\\clearpage',
  664. 'EOD' : '\\end{document}'
  665. },
  666. 'lout': {
  667. 'paragraphOpen' : '@LP' ,
  668. 'blockTitle1Open' : '@BeginSections' ,
  669. 'blockTitle1Close' : '@EndSections' ,
  670. 'blockTitle2Open' : ' @BeginSubSections' ,
  671. 'blockTitle2Close' : ' @EndSubSections' ,
  672. 'blockTitle3Open' : ' @BeginSubSubSections' ,
  673. 'blockTitle3Close' : ' @EndSubSubSections' ,
  674. 'title1Open' : '\n@Section @Title { \a } @Begin',
  675. 'title1Close' : '@End @Section' ,
  676. 'title2Open' : '\n @SubSection @Title { \a } @Begin',
  677. 'title2Close' : ' @End @SubSection' ,
  678. 'title3Open' : '\n @SubSubSection @Title { \a } @Begin',
  679. 'title3Close' : ' @End @SubSubSection' ,
  680. 'title4Open' : '\n@LP @LeftDisplay @B { \a }',
  681. 'title5Open' : '\n@LP @LeftDisplay @B { \a }',
  682. 'anchor' : '@Tag { \a }' ,
  683. 'blockVerbOpen' : '@LP @ID @F @RawVerbatim @Begin',
  684. 'blockVerbClose' : '@End @RawVerbatim' ,
  685. 'blockQuoteOpen' : '@QD {' ,
  686. 'blockQuoteClose' : '}' ,
  687. # enclosed inside {} to deal with joined**words**
  688. 'fontMonoOpen' : '{@F {' ,
  689. 'fontMonoClose' : '}}' ,
  690. 'fontBoldOpen' : '{@B {' ,
  691. 'fontBoldClose' : '}}' ,
  692. 'fontItalicOpen' : '{@II {' ,
  693. 'fontItalicClose' : '}}' ,
  694. 'fontUnderlineOpen' : '{@Underline{' ,
  695. 'fontUnderlineClose' : '}}' ,
  696. # the full form is more readable, but could be BL EL LI NL TL DTI
  697. 'listOpen' : '@BulletList' ,
  698. 'listClose' : '@EndList' ,
  699. 'listItemOpen' : '@ListItem{' ,
  700. 'listItemClose' : '}' ,
  701. 'numlistOpen' : '@NumberedList' ,
  702. 'numlistClose' : '@EndList' ,
  703. 'numlistItemOpen' : '@ListItem{' ,
  704. 'numlistItemClose' : '}' ,
  705. 'deflistOpen' : '@TaggedList' ,
  706. 'deflistClose' : '@EndList' ,
  707. 'deflistItem1Open' : '@DropTagItem {' ,
  708. 'deflistItem1Close' : '}' ,
  709. 'deflistItem2Open' : '{' ,
  710. 'deflistItem2Close' : '}' ,
  711. 'bar1' : '\n@DP @FullWidthRule\n' ,
  712. 'url' : '{blue @Colour { \a }}' ,
  713. 'urlMark' : '\a ({blue @Colour { \a }})' ,
  714. 'email' : '{blue @Colour { \a }}' ,
  715. 'emailMark' : '\a ({blue Colour{ \a }})' ,
  716. 'img' : '~A~@IncludeGraphic { \a }' , # eps only!
  717. 'imgAlignLeft' : '@LeftDisplay ' ,
  718. 'imgAlignRight' : '@RightDisplay ' ,
  719. 'imgAlignCenter' : '@CentredDisplay ' ,
  720. # lout tables are *way* complicated, no support for now
  721. #'tableOpen' : '~A~@Tbl~B~\naformat{ @Cell A | @Cell B } {',
  722. #'tableClose' : '}' ,
  723. #'tableRowOpen' : '@Rowa\n' ,
  724. #'tableTitleRowOpen' : '@HeaderRowa' ,
  725. #'tableCenterAlign' : '@CentredDisplay ' ,
  726. #'tableCellOpen' : '\a {' , # A, B, ...
  727. #'tableCellClose' : '}' ,
  728. #'tableBorder' : '\nrule {yes}' ,
  729. 'comment' : '# \a' ,
  730. # @MakeContents must be on the config file
  731. 'TOC' : '@DP @ContentsGoesHere @DP',
  732. 'pageBreak' : '\n@NP\n' ,
  733. 'EOD' : '@End @Text'
  734. },
  735. 'moin': {
  736. 'title1' : '= \a =' ,
  737. 'title2' : '== \a ==' ,
  738. 'title3' : '=== \a ===' ,
  739. 'title4' : '==== \a ====' ,
  740. 'title5' : '===== \a =====',
  741. 'blockVerbOpen' : '{{{' ,
  742. 'blockVerbClose' : '}}}' ,
  743. 'blockQuoteLine' : ' ' ,
  744. 'fontMonoOpen' : '{{{' ,
  745. 'fontMonoClose' : '}}}' ,
  746. 'fontBoldOpen' : "'''" ,
  747. 'fontBoldClose' : "'''" ,
  748. 'fontItalicOpen' : "''" ,
  749. 'fontItalicClose' : "''" ,
  750. 'fontUnderlineOpen' : "__" ,
  751. 'fontUnderlineClose' : "__" ,
  752. 'listItemOpen' : ' * ' ,
  753. 'numlistItemOpen' : ' \a. ' ,
  754. 'bar1' : '----' ,
  755. 'url' : '[\a]' ,
  756. 'urlMark' : '[\a \a]' ,
  757. 'email' : '[\a]' ,
  758. 'emailMark' : '[\a \a]' ,
  759. 'img' : '[\a]' ,
  760. 'tableRowOpen' : '||' ,
  761. 'tableCellOpen' : '\a' ,
  762. 'tableCellClose' : '||' ,
  763. 'tableTitleCellClose' : '||' ,
  764. 'tableCellAlignRight' : '<)>' ,
  765. 'tableCellAlignCenter': '<:>' ,
  766. 'comment' : '## \a' ,
  767. 'TOC' : '[[TableOfContents]]'
  768. },
  769. 'mgp': {
  770. 'paragraphOpen' : '%font "normal", size 5' ,
  771. 'title1' : '%page\n\n\a\n' ,
  772. 'title2' : '%page\n\n\a\n' ,
  773. 'title3' : '%page\n\n\a\n' ,
  774. 'title4' : '%page\n\n\a\n' ,
  775. 'title5' : '%page\n\n\a\n' ,
  776. 'blockVerbOpen' : '%font "mono"' ,
  777. 'blockVerbClose' : '%font "normal"' ,
  778. 'blockQuoteOpen' : '%prefix " "' ,
  779. 'blockQuoteClose' : '%prefix " "' ,
  780. 'fontMonoOpen' : '\n%cont, font "mono"\n' ,
  781. 'fontMonoClose' : '\n%cont, font "normal"\n' ,
  782. 'fontBoldOpen' : '\n%cont, font "normal-b"\n' ,
  783. 'fontBoldClose' : '\n%cont, font "normal"\n' ,
  784. 'fontItalicOpen' : '\n%cont, font "normal-i"\n' ,
  785. 'fontItalicClose' : '\n%cont, font "normal"\n' ,
  786. 'fontUnderlineOpen' : '\n%cont, fore "cyan"\n' ,
  787. 'fontUnderlineClose' : '\n%cont, fore "white"\n' ,
  788. 'listItemLine' : '\t' ,
  789. 'numlistItemLine' : '\t' ,
  790. 'deflistItem1Open' : '\t\n%cont, font "normal-b"\n',
  791. 'deflistItem1Close' : '\n%cont, font "normal"\n' ,
  792. 'bar1' : '%bar "white" 5' ,
  793. 'bar2' : '%pause' ,
  794. 'url' : '\n%cont, fore "cyan"\n\a' +\
  795. '\n%cont, fore "white"\n' ,
  796. 'urlMark' : '\a \n%cont, fore "cyan"\n\a'+\
  797. '\n%cont, fore "white"\n' ,
  798. 'email' : '\n%cont, fore "cyan"\n\a' +\
  799. '\n%cont, fore "white"\n' ,
  800. 'emailMark' : '\a \n%cont, fore "cyan"\n\a'+\
  801. '\n%cont, fore "white"\n' ,
  802. 'img' : '~A~\n%newimage "\a"\n%left\n',
  803. 'imgAlignLeft' : '\n%left' ,
  804. 'imgAlignRight' : '\n%right' ,
  805. 'imgAlignCenter' : '\n%center' ,
  806. 'comment' : '%% \a' ,
  807. 'pageBreak' : '%page\n\n\n' ,
  808. 'EOD' : '%%EOD'
  809. },
  810. # man groff_man ; man 7 groff
  811. 'man': {
  812. 'paragraphOpen' : '.P' ,
  813. 'title1' : '.SH \a' ,
  814. 'title2' : '.SS \a' ,
  815. 'title3' : '.SS \a' ,
  816. 'title4' : '.SS \a' ,
  817. 'title5' : '.SS \a' ,
  818. 'blockVerbOpen' : '.nf' ,
  819. 'blockVerbClose' : '.fi\n' ,
  820. 'blockQuoteOpen' : '.RS' ,
  821. 'blockQuoteClose' : '.RE' ,
  822. 'fontBoldOpen' : '\\fB' ,
  823. 'fontBoldClose' : '\\fR' ,
  824. 'fontItalicOpen' : '\\fI' ,
  825. 'fontItalicClose' : '\\fR' ,
  826. 'listOpen' : '.RS' ,
  827. 'listItemOpen' : '.IP \(bu 3\n',
  828. 'listClose' : '.RE' ,
  829. 'numlistOpen' : '.RS' ,
  830. 'numlistItemOpen' : '.IP \a. 3\n',
  831. 'numlistClose' : '.RE' ,
  832. 'deflistItem1Open' : '.TP\n' ,
  833. 'bar1' : '\n\n' ,
  834. 'url' : '\a' ,
  835. 'urlMark' : '\a (\a)',
  836. 'email' : '\a' ,
  837. 'emailMark' : '\a (\a)',
  838. 'img' : '\a' ,
  839. 'tableOpen' : '.TS\n~A~~B~tab(^); ~C~.',
  840. 'tableClose' : '.TE' ,
  841. 'tableRowOpen' : ' ' ,
  842. 'tableCellSep' : '^' ,
  843. 'tableAlignCenter' : 'center, ',
  844. 'tableBorder' : 'allbox, ',
  845. 'tableColAlignLeft' : 'l' ,
  846. 'tableColAlignRight' : 'r' ,
  847. 'tableColAlignCenter' : 'c' ,
  848. 'comment' : '.\\" \a'
  849. },
  850. 'pm6': {
  851. 'paragraphOpen' : '<@Normal:>' ,
  852. 'title1' : '\n<@Title1:>\a',
  853. 'title2' : '\n<@Title2:>\a',
  854. 'title3' : '\n<@Title3:>\a',
  855. 'title4' : '\n<@Title4:>\a',
  856. 'title5' : '\n<@Title5:>\a',
  857. 'blockVerbOpen' : '<@PreFormat:>' ,
  858. 'blockQuoteLine' : '<@Quote:>' ,
  859. 'fontMonoOpen' : '<FONT "Lucida Console"><SIZE 9>' ,
  860. 'fontMonoClose' : '<SIZE$><FONT$>',
  861. 'fontBoldOpen' : '<B>' ,
  862. 'fontBoldClose' : '<P>' ,
  863. 'fontItalicOpen' : '<I>' ,
  864. 'fontItalicClose' : '<P>' ,
  865. 'fontUnderlineOpen' : '<U>' ,
  866. 'fontUnderlineClose' : '<P>' ,
  867. 'listOpen' : '<@Bullet:>' ,
  868. 'listItemOpen' : '\x95\t' , # \x95 == ~U
  869. 'numlistOpen' : '<@Bullet:>' ,
  870. 'numlistItemOpen' : '\x95\t' ,
  871. 'bar1' : '\a' ,
  872. 'url' : '<U>\a<P>' , # underline
  873. 'urlMark' : '\a <U>\a<P>' ,
  874. 'email' : '\a' ,
  875. 'emailMark' : '\a \a' ,
  876. 'img' : '\a'
  877. }
  878. }
  879. # exceptions for --css-sugar
  880. if config['css-sugar'] and config['target'] in ('html','xhtml'):
  881. # change just HTML because XHTML inherits it
  882. htmltags = alltags['html']
  883. # table with no cellpadding
  884. htmltags['tableOpen'] = string.replace(
  885. htmltags['tableOpen'], ' CELLPADDING="4"', '')
  886. # DIVs
  887. htmltags['tocOpen' ] = '<DIV CLASS="toc" ID="toc">'
  888. htmltags['tocClose'] = '</DIV>'
  889. htmltags['bodyOpen'] = '<DIV CLASS="body" ID="body">'
  890. htmltags['bodyClose']= '</DIV>'
  891. # make the HTML -> XHTML inheritance
  892. xhtml = alltags['html'].copy()
  893. for key in xhtml.keys(): xhtml[key] = string.lower(xhtml[key])
  894. # some like HTML tags as lowercase, some don't... (headers out)
  895. if HTML_LOWER: alltags['html'] = xhtml.copy()
  896. xhtml.update(alltags['xhtml'])
  897. alltags['xhtml'] = xhtml.copy()
  898. # compose the target tags dictionary
  899. tags = {}
  900. target_tags = alltags[config['target']].copy()
  901. for key in keys: tags[key] = '' # create empty keys
  902. for key in target_tags.keys():
  903. tags[key] = maskEscapeChar(target_tags[key]) # populate
  904. # map strong line to separator if not defined
  905. if not tags['bar2'] and tags['bar1']:
  906. tags['bar2'] = tags['bar1']
  907. return tags
  908. ##############################################################################
  909. def getRules(config):
  910. "Returns all the target-specific syntax rules"
  911. ret = {}
  912. allrules = [
  913. # target rules (ON/OFF)
  914. 'linkable', # target supports external links
  915. 'tableable', # target supports tables
  916. 'imglinkable', # target supports images as links
  917. 'imgalignable', # target supports image alignment
  918. 'imgasdefterm', # target supports image as definition term
  919. 'autonumberlist', # target supports numbered lists natively
  920. 'autonumbertitle', # target supports numbered titles natively
  921. 'parainsidelist', # lists items supports paragraph
  922. 'spacedlistitem', # lists support blank lines between items
  923. 'listnotnested', # lists cannot be nested
  924. 'quotenotnested', # quotes cannot be nested
  925. 'verbblocknotescaped', # don't escape specials in verb block
  926. 'verbblockfinalescape', # do final escapes in verb block
  927. 'escapeurl', # escape special in link URL
  928. 'onelinepara', # dump paragraph as a single long line
  929. 'tabletitlerowinbold', # manually bold any cell on table titles
  930. 'tablecellstrip', # strip extra spaces from each table cell
  931. 'barinsidequote', # bars are allowed inside quote blocks
  932. 'finalescapetitle', # perform final escapes on title lines
  933. 'autotocnewpagebefore', # break page before automatic TOC
  934. 'autotocnewpageafter', # break page after automatic TOC
  935. 'autotocwithbars', # automatic TOC surrounded by bars
  936. 'mapbar2pagebreak', # map the strong bar to a page break
  937. 'titleblocks', # titles must be on open/close section blocks
  938. # target code beautify (ON/OFF)
  939. 'indentverbblock', # add leading spaces to verb block lines
  940. 'breaktablecell', # break lines after any table cell
  941. 'breaktablelineopen', # break line after opening table line
  942. 'notbreaklistopen', # don't break line after opening a new list
  943. 'notbreakparaopen', # don't break line after opening a new para
  944. 'keepquoteindent', # don't remove the leading TABs on quotes
  945. 'keeplistindent', # don't remove the leading spaces on lists
  946. 'blankendmotherlist', # append a blank line at the mother list end
  947. 'blankendtable', # append a blank line at the table end
  948. 'blankendautotoc', # append a blank line at the auto TOC end
  949. 'tagnotindentable', # tags must be placed at the line begining
  950. # value settings
  951. 'listmaxdepth', # maximum depth for lists
  952. 'tablecellaligntype' # type of table cell align: cell, column
  953. ]
  954. rules_bank = {
  955. 'txt' : {
  956. 'indentverbblock':1,
  957. 'spacedlistitem':1,
  958. 'parainsidelist':1,
  959. 'keeplistindent':1,
  960. 'barinsidequote':1,
  961. 'autotocwithbars':1,
  962. 'blankendmotherlist':1
  963. },
  964. 'html': {
  965. 'indentverbblock':1,
  966. 'linkable':1,
  967. 'escapeurl':1,
  968. 'imglinkable':1,
  969. 'imgalignable':1,
  970. 'imgasdefterm':1,
  971. 'autonumberlist':1,
  972. 'spacedlistitem':1,
  973. 'parainsidelist':1,
  974. 'blankendmotherlist':1,
  975. 'tableable':1,
  976. 'tablecellstrip':1,
  977. 'blankendtable':1,
  978. 'breaktablecell':1,
  979. 'breaktablelineopen':1,
  980. 'keeplistindent':1,
  981. 'keepquoteindent':1,
  982. 'barinsidequote':1,
  983. 'autotocwithbars':1,
  984. 'tablecellaligntype':'cell'
  985. },
  986. #TIP xhtml inherits all HTML rules
  987. 'xhtml': {
  988. },
  989. 'sgml': {
  990. 'linkable':1,
  991. 'escapeurl':1,
  992. 'autonumberlist':1,
  993. 'spacedlistitem':1,
  994. 'blankendmotherlist':1,
  995. 'tableable':1,
  996. 'tablecellstrip':1,
  997. 'blankendtable':1,
  998. 'blankendautotoc':1,
  999. 'quotenotnested':1,
  1000. 'keeplistindent':1,
  1001. 'keepquoteindent':1,
  1002. 'barinsidequote':1,
  1003. 'finalescapetitle':1,
  1004. 'tablecellaligntype':'column'
  1005. },
  1006. 'mgp' : {
  1007. 'blankendmotherlist':1,
  1008. 'tagnotindentable':1,
  1009. 'spacedlistitem':1,
  1010. 'imgalignable':1,
  1011. 'autotocnewpagebefore':1,
  1012. },
  1013. 'tex' : {
  1014. 'autonumberlist':1,
  1015. 'autonumbertitle':1,
  1016. 'spacedlistitem':1,
  1017. 'blankendmotherlist':1,
  1018. 'tableable':1,
  1019. 'tablecellstrip':1,
  1020. 'tabletitlerowinbold':1,
  1021. 'blankendtable':1,
  1022. 'verbblocknotescaped':1,
  1023. 'keeplistindent':1,
  1024. 'listmaxdepth':4,
  1025. 'barinsidequote':1,
  1026. 'finalescapetitle':1,
  1027. 'autotocnewpageafter':1,
  1028. 'mapbar2pagebreak':1,
  1029. 'tablecellaligntype':'column'
  1030. },
  1031. 'lout': {
  1032. 'keepquoteindent':1,
  1033. 'escapeurl':1,
  1034. 'verbblocknotescaped':1,
  1035. 'tableable':0,
  1036. 'imgalignable':1,
  1037. 'mapbar2pagebreak':1,
  1038. 'titleblocks':1,
  1039. 'notbreakparaopen':1
  1040. },
  1041. 'moin': {
  1042. 'spacedlistitem':1,
  1043. 'linkable':1,
  1044. 'blankendmotherlist':1,
  1045. 'keeplistindent':1,
  1046. 'tableable':1,
  1047. 'barinsidequote':1,
  1048. 'blankendtable':1,
  1049. 'tabletitlerowinbold':1,
  1050. 'tablecellstrip':1,
  1051. 'autotocwithbars':1,
  1052. 'tablecellaligntype':'cell'
  1053. },
  1054. 'man' : {
  1055. 'spacedlistitem':1,
  1056. 'indentverbblock':1,
  1057. 'blankendmotherlist':1,
  1058. 'tagnotindentable':1,
  1059. 'tableable':1,
  1060. 'tablecellaligntype':'column',
  1061. 'tabletitlerowinbold':1,
  1062. 'tablecellstrip':1,
  1063. 'blankendtable':1,
  1064. 'keeplistindent':0,
  1065. 'barinsidequote':1,
  1066. 'parainsidelist':0,
  1067. },
  1068. 'pm6' : {
  1069. 'keeplistindent':1,
  1070. 'verbblockfinalescape':1,
  1071. #TODO add support for these - maybe set a JOINNEXT char and
  1072. # do it on addLineBreaks()
  1073. 'notbreaklistopen':1,
  1074. 'notbreakparaopen':1,
  1075. 'barinsidequote':1,
  1076. 'autotocwithbars':1,
  1077. 'onelinepara':1,
  1078. }
  1079. }
  1080. # exceptions for --css-sugar
  1081. if config['css-sugar'] and config['target'] in ('html','xhtml'):
  1082. rules_bank['html']['indentverbblock'] = 0
  1083. rules_bank['html']['autotocwithbars'] = 0
  1084. # get the target specific rules
  1085. if config['target'] == 'xhtml':
  1086. myrules = rules_bank['html'].copy() # inheritance
  1087. myrules.update(rules_bank['xhtml']) # get XHTML specific
  1088. else:
  1089. myrules = rules_bank[config['target']].copy()
  1090. # populate return dictionary
  1091. for key in allrules: ret[key] = 0 # reset all
  1092. ret.update(myrules) # get rules
  1093. return ret
  1094. ##############################################################################
  1095. def getRegexes():
  1096. "Returns all the regexes used to find the t2t marks"
  1097. bank = {
  1098. 'blockVerbOpen':
  1099. re.compile(r'^```\s*$'),
  1100. 'blockVerbClose':
  1101. re.compile(r'^```\s*$'),
  1102. 'blockRawOpen':
  1103. re.compile(r'^"""\s*$'),
  1104. 'blockRawClose':
  1105. re.compile(r'^"""\s*$'),
  1106. 'quote':
  1107. re.compile(r'^\t+'),
  1108. '1lineVerb':
  1109. re.compile(r'^``` (?=.)'),
  1110. '1lineRaw':
  1111. re.compile(r'^""" (?=.)'),
  1112. # mono, raw, bold, italic, underline:
  1113. # - marks must be glued with the contents, no boundary spaces
  1114. # - they are greedy, so in ****bold****, turns to <b>**bold**</b>
  1115. 'fontMono':
  1116. re.compile( r'``([^\s](|.*?[^\s])`*)``'),
  1117. 'raw':
  1118. re.compile( r'""([^\s](|.*?[^\s])"*)""'),
  1119. 'fontBold':
  1120. re.compile(r'\*\*([^\s](|.*?[^\s])\**)\*\*'),
  1121. 'fontItalic':
  1122. re.compile( r'//([^\s](|.*?[^\s])/*)//'),
  1123. 'fontUnderline':
  1124. re.compile( r'__([^\s](|.*?[^\s])_*)__'),
  1125. 'list':
  1126. re.compile(r'^( *)(-) (?=[^ ])'),
  1127. 'numlist':
  1128. re.compile(r'^( *)(\+) (?=[^ ])'),
  1129. 'deflist':
  1130. re.compile(r'^( *)(:) (.*)$'),
  1131. 'listclose':
  1132. re.compile(r'^( *)([-+:])\s*$'),
  1133. 'bar':
  1134. re.compile(r'^(\s*)([_=-]{20,})\s*$'),
  1135. 'table':
  1136. re.compile(r'^ *\|\|? '),
  1137. 'blankline':
  1138. re.compile(r'^\s*$'),
  1139. 'comment':
  1140. re.compile(r'^%'),
  1141. # auxiliar tag regexes
  1142. '_imgAlign' : re.compile(r'~A~',re.I),
  1143. '_tableAlign' : re.compile(r'~A~',re.I),
  1144. '_anchor' : re.compile(r'~A~',re.I),
  1145. '_tableBorder' : re.compile(r'~B~',re.I),
  1146. '_tableColAlign': re.compile(r'~C~',re.I),
  1147. }
  1148. # special char to place data on TAGs contents (\a == bell)
  1149. bank['x'] = re.compile('\a')
  1150. # %%macroname [ (formatting) ]
  1151. bank['macros'] = re.compile(r'%%%%(?P<name>%s)\b(\((?P<fmt>.*?)\))?'%(
  1152. string.join(MACROS.keys(), '|')), re.I)
  1153. # %%TOC special macro for TOC positioning
  1154. bank['toc'] = re.compile(r'^ *%%toc\s*$', re.I)
  1155. # almost complicated title regexes ;)
  1156. titskel = r'^ *(?P<id>%s)(?P<txt>%s)\1(\[(?P<label>[\w-]*)\])?\s*$'
  1157. bank[ 'title'] = re.compile(titskel%('[=]{1,5}','[^=](|.*[^=])'))
  1158. bank['numtitle'] = re.compile(titskel%('[+]{1,5}','[^+](|.*[^+])'))
  1159. ### complicated regexes begin here ;)
  1160. #
  1161. # textual descriptions on --help's style: [...] is optional, | is OR
  1162. ### first, some auxiliar variables
  1163. #
  1164. # [image.EXT]
  1165. patt_img = r'\[([\w_,.+%$#@!?+~/-]+\.(png|jpe?g|gif|eps|bmp))\]'
  1166. # link things
  1167. urlskel = {
  1168. 'proto' : r'(https?|ftp|news|telnet|gopher|wais)://',
  1169. 'guess' : r'(www[23]?|ftp)\.', # w/out proto, try to guess
  1170. 'login' : r'A-Za-z0-9_.-', # for ftp://login@domain.com
  1171. 'pass' : r'[^ @]*', # for ftp://login:pass@dom.com
  1172. 'chars' : r'A-Za-z0-9%._/~:,=$@&+-', # %20(space), :80(port), D&D
  1173. 'anchor': r'A-Za-z0-9%._-', # %nn(encoded)
  1174. 'form' : r'A-Za-z0-9/%&=+;.,$@*_-', # .,@*_-(as is)
  1175. 'punct' : r'.,;:!?'
  1176. }
  1177. # username [ :password ] @
  1178. patt_url_login = r'([%s]+(:%s)?@)?'%(urlskel['login'],urlskel['pass'])
  1179. # [ http:// ] [ username:password@ ] domain.com [ / ]
  1180. # [ #anchor | ?form=data ]
  1181. retxt_url = r'\b(%s%s|%s)[%s]+\b/*(\?[%s]+)?(#[%s]+)?'%(
  1182. urlskel['proto'],patt_url_login, urlskel['guess'],
  1183. urlskel['chars'],urlskel['form'],urlskel['anchor'])
  1184. # filename | [ filename ] #anchor
  1185. retxt_url_local = r'[%s]+|[%s]*(#[%s]+)'%(
  1186. urlskel['chars'],urlskel['chars'],urlskel['anchor'])
  1187. # user@domain [ ?form=data ]
  1188. patt_email = r'\b[%s]+@([A-Za-z0-9_-]+\.)+[A-Za-z]{2,4}\b(\?[%s]+)?'%(
  1189. urlskel['login'],urlskel['form'])
  1190. # saving for future use
  1191. bank['_urlskel'] = urlskel
  1192. ### and now the real regexes
  1193. #
  1194. bank['email'] = re.compile(patt_email,re.I)
  1195. # email | url
  1196. bank['link'] = re.compile(r'%s|%s'%(retxt_url,patt_email), re.I)
  1197. # \[ label | imagetag url | email | filename \]
  1198. bank['linkmark'] = re.compile(
  1199. r'\[(?P<label>%s|[^]]+) (?P<link>%s|%s|%s)\]'%(
  1200. patt_img, retxt_url, patt_email, retxt_url_local),
  1201. re.L+re.I)
  1202. # image
  1203. bank['img'] = re.compile(patt_img, re.L+re.I)
  1204. # special things
  1205. bank['special'] = re.compile(r'^%!\s*')
  1206. return bank
  1207. ### END OF regex nightmares
  1208. ##############################################################################
  1209. class error(Exception):
  1210. pass
  1211. def echo(msg): # for quick debug
  1212. print '\033[32;1m%s\033[m'%msg
  1213. def Quit(msg=''):
  1214. if msg: print msg
  1215. sys.exit(0)
  1216. def Error(msg):
  1217. msg = _("%s: Error: ")%my_name + msg
  1218. raise error, msg
  1219. def getTraceback():
  1220. try:
  1221. from traceback import format_exception
  1222. etype, value, tb = sys.exc_info()
  1223. return string.join(format_exception(etype, value, tb), '')
  1224. except: pass
  1225. def getUnknownErrorMessage():
  1226. msg = '%s\n%s (%s):\n\n%s'%(
  1227. _('Sorry! Txt2tags aborted by an unknow error.'),
  1228. _('Please send the following Error Traceback to the author'),
  1229. my_email, getTraceback())
  1230. return msg
  1231. def Message(msg,level):
  1232. if level <= VERBOSE and not QUIET:
  1233. prefix = '-'*5
  1234. print "%s %s"%(prefix*level, msg)
  1235. def Debug(msg,id=0,linenr=None):
  1236. "Show debug messages, categorized (colored or not)"
  1237. if QUIET or not DEBUG: return
  1238. if int(id) not in range(8): id = 0
  1239. # 0:black 1:red 2:green 3:yellow 4:blue 5:pink 6:cyan 7:white ;1:light
  1240. ids = ['INI','CFG','SRC','BLK','HLD','GUI','OUT','DET']
  1241. colors_bgdark = ['7;1','1;1','3;1','6;1','4;1','5;1','2;1','7;1']
  1242. colors_bglight = ['0' ,'1' ,'3' ,'6' ,'4' ,'5' ,'2' ,'0' ]
  1243. if linenr is not None: msg = "LINE %04d: %s"%(linenr,msg)
  1244. if COLOR_DEBUG:
  1245. if BG_LIGHT: color = colors_bglight[id]
  1246. else : color = colors_bgdark[id]
  1247. msg = '\033[3%sm%s\033[m'%(color,msg)
  1248. print "++ %s: %s"%(ids[id],msg)
  1249. def Readfile(file, remove_linebreaks=0, ignore_error=0):
  1250. data = []
  1251. if file == '-':
  1252. try: data = sys.stdin.readlines()
  1253. except:
  1254. if not ignore_error:
  1255. Error(_('You must feed me with data on STDIN!'))
  1256. else:
  1257. try: f = open(file); data = f.readlines() ; f.close()
  1258. except:
  1259. if not ignore_error:
  1260. Error(_("Cannot read file:")+" %s"%file)
  1261. if remove_linebreaks:
  1262. data = map(lambda x:re.sub('[\n\r]+$','',x), data)
  1263. Message(_("Readed file (%d lines): %s")%(len(data),file),2)
  1264. return data
  1265. def Savefile(file, contents):
  1266. try: f = open(file, 'wb')
  1267. except: Error(_("Cannot open file for writing:")+" %s"%file)
  1268. if type(contents) == type([]): doit = f.writelines
  1269. else: doit = f.write
  1270. doit(contents) ; f.close()
  1271. def showdic(dic):
  1272. for k in dic.keys(): print "%15s : %s" % (k,dic[k])
  1273. def dotted_spaces(txt=''):
  1274. return string.replace(txt,' ','.')
  1275. # TIP: win env vars http://www.winnetmag.com/Article/ArticleID/23873/23873.html
  1276. def get_rc_path():
  1277. "Return the full path for the users' RC file"
  1278. # try to get the path from an env var. if yes, we're done
  1279. user_defined = os.environ.get('T2TCONFIG')
  1280. if user_defined: return user_defined
  1281. # env var not found, so perform automatic path composing
  1282. # set default filename according system platform
  1283. rc_names = {'default':'.txt2tagsrc', 'win':'_t2trc'}
  1284. rc_file = rc_names.get(sys.platform[:3]) or rc_names['default']
  1285. # the file must be on the user directory, but where is this dir?
  1286. rc_dir_search = ['HOME', 'HOMEPATH']
  1287. for var in rc_dir_search:
  1288. rc_dir = os.environ.get(var)
  1289. if rc_dir: break
  1290. # rc dir found, now we must join dir+file to compose the full path
  1291. if rc_dir:
  1292. # compose path and return it if the file exists
  1293. rc_path = os.path.join(rc_dir, rc_file)
  1294. # on windows, prefix with the drive (%homedrive%: 2k/XP/NT)
  1295. if sys.platform[:3] == 'win':
  1296. rc_drive = os.environ.get('HOMEDRIVE')
  1297. rc_path = os.path.join(rc_drive,rc_path)
  1298. return rc_path
  1299. # sorry, not found
  1300. return ''
  1301. ##############################################################################
  1302. class CommandLine:
  1303. """
  1304. Command Line class - Masters command line
  1305. This class checks and extract data from the provided command line.
  1306. The --long options and flags are taken from the global OPTIONS,
  1307. FLAGS and ACTIONS dictionaries. The short options are registered
  1308. here, and also their equivalence to the long ones.
  1309. METHODS:
  1310. _compose_short_opts() -> str
  1311. _compose_long_opts() -> list
  1312. Compose the valid short and long options list, on the
  1313. 'getopt' format.
  1314. parse() -> (opts, args)
  1315. Call getopt to check and parse the command line.
  1316. It expects to receive the command line as a list, and
  1317. without the program name (sys.argv[1:]).
  1318. get_raw_config() -> [RAW config]
  1319. Scans command line and convert the data to the RAW config
  1320. format. See ConfigMaster class to the RAW format description.
  1321. Optional 'ignore' and 'filter' arguments are used to filter
  1322. in or out specified keys.
  1323. compose_cmdline(dict) -> [Command line]
  1324. Compose a command line list from an already parsed config
  1325. dictionary, generated from RAW by ConfigMaster(). Use
  1326. this to compose an optimal command line for a group of
  1327. options.
  1328. The get_raw_config() calls parse(), so the tipical use of this
  1329. class is:
  1330. raw = CommandLine().get_raw_config(sys.argv[1:])
  1331. """
  1332. def __init__(self):
  1333. self.all_options = OPTIONS.keys()
  1334. self.all_flags = FLAGS.keys()
  1335. self.all_actions = ACTIONS.keys()
  1336. # short:long options equivalence
  1337. self.short_long = {
  1338. 'h':'help' , 'V':'version',
  1339. 'n':'enum-title', 'i':'infile' ,
  1340. 'H':'no-headers', 'o':'outfile',
  1341. 'v':'verbose' , 't':'target' ,
  1342. 'q':'quiet'
  1343. }
  1344. # compose valid short and long options data for getopt
  1345. self.short_opts = self._compose_short_opts()
  1346. self.long_opts = self._compose_long_opts()
  1347. def _compose_short_opts(self):
  1348. "Returns a string like 'hVt:o' with all short options/flags"
  1349. ret = []
  1350. for opt in self.short_long.keys():
  1351. long = self.short_long[opt]
  1352. if long in self.all_options: # is flag or option?
  1353. opt = opt+':' # option: have param
  1354. ret.append(opt)
  1355. #Debug('Valid SHORT options: %s'%ret)
  1356. return string.join(ret, '')
  1357. def _compose_long_opts(self):
  1358. "Returns a list with all the valid long options/flags"
  1359. ret = map(lambda x:x+'=', self.all_options) # add =
  1360. ret.extend(self.all_flags) # flag ON
  1361. ret.extend(self.all_actions) # acts
  1362. ret.extend(map(lambda x:'no-'+x, self.all_flags)) # add no-*
  1363. ret.extend(['no-style','no-encoding','no-outfile']) # turn OFF
  1364. #Debug('Valid LONG options: %s'%ret)
  1365. return ret
  1366. def _tokenize(self, cmd_string=''):
  1367. "Convert a command line string to a list"
  1368. #TODO protect quotes contents
  1369. return string.split(cmd_string)
  1370. def parse(self, cmdline=[]):
  1371. "Check/Parse a command line list TIP: no program name!"
  1372. # get the valid options
  1373. short, long = self.short_opts, self.long_opts
  1374. # parse it!
  1375. try:
  1376. opts, args = getopt.getopt(cmdline, short, long)
  1377. except getopt.error, errmsg:
  1378. Error(_("%s (try --help)")%errmsg)
  1379. return (opts, args)
  1380. def get_raw_config(self, cmdline=[], ignore=[], filter=[], relative=0):
  1381. "Returns the options/arguments found as RAW config"
  1382. if not cmdline: return []
  1383. ret = []
  1384. # we need lists, not strings
  1385. if type(cmdline) == type(''): cmdline = self._tokenize(cmdline)
  1386. opts, args = self.parse(cmdline[:])
  1387. # get infile, if any
  1388. while args:
  1389. infile = args.pop(0)
  1390. ret.append(['infile', infile])
  1391. # parse all options
  1392. for name,value in opts:
  1393. # remove leading - and --
  1394. name = re.sub('^--?', '', name)
  1395. # alias to old mispelled 'suGGar'
  1396. if name == 'css-suggar': name = 'css-sugar'
  1397. elif name == 'no-css-suggar': name = 'no-css-sugar'
  1398. # translate short opt to long
  1399. if len(name) == 1: name = self.short_long.get(name)
  1400. # outfile exception: path relative to PWD
  1401. if name == 'outfile' and value != STDOUT and relative:
  1402. value = os.path.abspath(value)
  1403. # save it
  1404. ret.append([name, value])
  1405. # apply 'ignore' and 'filter' rules (filter is stronger)
  1406. temp = ret[:] ; ret = []
  1407. for name,value in temp:
  1408. if (not filter and not ignore) or \
  1409. (filter and name in filter) or \
  1410. (ignore and name not in ignore):
  1411. ret.append( ['all', name, value] )
  1412. # add the original command line string as 'realcmdline'
  1413. ret.append( ['all', 'realcmdline', cmdline] )
  1414. return ret
  1415. def compose_cmdline(self, conf={}, no_check=0):
  1416. "compose a full (and diet) command line from CONF dict"
  1417. if not conf: return []
  1418. args = []
  1419. dft_options = OPTIONS.copy()
  1420. cfg = conf.copy()
  1421. valid_opts = self.all_options + self.all_flags
  1422. use_short = {'no-headers':'H', 'enum-title':'n'}
  1423. # remove useless options
  1424. if not no_check and cfg.get('toc-only'):
  1425. if cfg.has_key('no-headers'):
  1426. del cfg['no-headers']
  1427. if cfg.has_key('outfile'):
  1428. del cfg['outfile'] # defaults to STDOUT
  1429. if cfg.get('target') == 'txt':
  1430. del cfg['target'] # already default
  1431. args.append('--toc-only') # must be the first
  1432. del cfg['toc-only']
  1433. # add target type
  1434. if cfg.has_key('target'):
  1435. args.append('-t '+cfg['target'])
  1436. del cfg['target']
  1437. # add other options
  1438. for key in cfg.keys():
  1439. if key not in valid_opts: continue # may be a %!setting
  1440. if key in ['outfile','infile']: continue # later
  1441. val = cfg[key]
  1442. if not val: continue
  1443. # default values are useless on cmdline
  1444. if val == dft_options.get(key): continue
  1445. # -short format
  1446. if key in use_short.keys():
  1447. args.append('-'+use_short[key])
  1448. continue
  1449. # --long format
  1450. if key in self.all_flags: # add --option
  1451. args.append('--'+key)
  1452. else: # add --option=value
  1453. args.append('--%s=%s'%(key,val))
  1454. # the outfile using -o
  1455. if cfg.has_key('outfile') and \
  1456. cfg['outfile'] != dft_options.get('outfile'):
  1457. args.append('-o '+cfg['outfile'])
  1458. # place input file(s) always at the end
  1459. if cfg.has_key('infile'):
  1460. args.append(string.join(cfg['infile'],' '))
  1461. # return as a nice list
  1462. Debug("Diet command line: %s"%string.join(args,' '), 1)
  1463. return args
  1464. ##############################################################################
  1465. class SourceDocument:
  1466. """
  1467. SourceDocument class - scan document structure, extract data
  1468. It knows about full files. It reads a file and identify all
  1469. the areas begining (Head,Conf,Body). With this info it can
  1470. extract each area contents.
  1471. Note: the original line break is removed.
  1472. DATA:
  1473. self.arearef - Save Head, Conf, Body init line number
  1474. self.areas - Store the area names which are not empty
  1475. self.buffer - The full file contents (with NO \\r, \\n)
  1476. METHODS:
  1477. get() - Access the contents of an Area. Example:
  1478. config = SourceDocument(file).get('conf')
  1479. split() - Get all the document Areas at once. Example:
  1480. head, conf, body = SourceDocument(file).split()
  1481. RULES:
  1482. * The document parts are sequential: Head, Conf and Body.
  1483. * One ends when the next begins.
  1484. * The Conf Area is optional, so a document can have just
  1485. Head and Body Areas.
  1486. These are the Areas limits:
  1487. - Head Area: the first three lines
  1488. - Body Area: from the first valid text line to the end
  1489. - Conf Area: the comments between Head and Body Areas
  1490. Exception: If the first line is blank, this means no
  1491. header info, so the Head Area is just the first line.
  1492. """
  1493. def __init__(self, filename='', contents=[]):
  1494. self.areas = ['head','conf','body']
  1495. self.arearef = []
  1496. self.areas_fancy = ''
  1497. self.filename = filename
  1498. self.buffer = []
  1499. if filename:
  1500. self.scan_file(filename)
  1501. elif contents:
  1502. self.scan(contents)
  1503. def split(self):
  1504. "Returns all document parts, splitted into lists."
  1505. return self.get('head'), self.get('conf'), self.get('body')
  1506. def get(self, areaname):
  1507. "Returns head|conf|body contents from self.buffer"
  1508. # sanity
  1509. if areaname not in self.areas: return []
  1510. if not self.buffer : return []
  1511. # go get it
  1512. bufini = 1
  1513. bufend = len(self.buffer)
  1514. if areaname == 'head':
  1515. ini = bufini
  1516. end = self.arearef[1] or self.arearef[2] or bufend
  1517. elif areaname == 'conf':
  1518. ini = self.arearef[1]
  1519. end = self.arearef[2] or bufend
  1520. elif areaname == 'body':
  1521. ini = self.arearef[2]
  1522. end = bufend
  1523. else:
  1524. Error("Unknown Area name '%s'"%areaname)
  1525. lines = self.buffer[ini:end]
  1526. # make sure head will always have 3 lines
  1527. while areaname == 'head' and len(lines) < 3:
  1528. lines.append('')
  1529. return lines
  1530. def scan_file(self, filename):
  1531. Debug("source file: %s"%filename)
  1532. Message(_("Loading source document"),1)
  1533. buf = Readfile(filename, remove_linebreaks=1)
  1534. self.scan(buf)
  1535. def scan(self, lines):
  1536. "Run through source file and identify head/conf/body areas"
  1537. buf = lines
  1538. if len(buf) == 0:
  1539. Error(_('The input file is empty: %s')%filename)
  1540. cfg_parser = ConfigLines().parse_line
  1541. buf.insert(0, '') # text start at pos 1
  1542. ref = [1,4,0]
  1543. if not string.strip(buf[1]): # no header
  1544. ref[0] = 0 ; ref[1] = 2
  1545. rgx = getRegexes()
  1546. for i in range(ref[1],len(buf)): # find body init:
  1547. if string.strip(buf[i]) and ( # ... not blank and
  1548. buf[i][0] != '%' or # ... not comment or
  1549. rgx['macros'].match(buf[i]) or # ... %%macro
  1550. rgx['toc'].match(buf[i]) or # ... %%toc
  1551. cfg_parser(buf[i],'include')[1]): # ... %!include
  1552. ref[2] = i ; break
  1553. if ref[1] == ref[2]: ref[1] = 0 # no conf area
  1554. for i in 0,1,2: # del !existent
  1555. if ref[i] >= len(buf): ref[i] = 0 # title-only
  1556. if not ref[i]: self.areas[i] = ''
  1557. Debug('Head,Conf,Body start line: %s'%ref)
  1558. self.arearef = ref # save results
  1559. self.buffer = buf
  1560. # fancyness sample: head conf body (1 4 8)
  1561. self.areas_fancy = "%s (%s)"%(
  1562. string.join(self.areas),
  1563. string.join(map(str, map(lambda x:x or '', ref))))
  1564. Message(_("Areas found: %s")%self.areas_fancy, 2)
  1565. def get_raw_config(self):
  1566. "Handy method to get the CONF area RAW config (if any)"
  1567. if not self.areas.count('conf'): return []
  1568. Message(_("Scanning source document CONF area"),1)
  1569. raw = ConfigLines(
  1570. file=self.filename, lines=self.get('conf'),
  1571. first_line=self.arearef[1]).get_raw_config()
  1572. Debug("document raw config: %s"%raw, 1)
  1573. return raw
  1574. ##############################################################################
  1575. class ConfigMaster:
  1576. """
  1577. ConfigMaster class - the configuration wizard
  1578. This class is the configuration master. It knows how to handle
  1579. the RAW and PARSED config format. It also performs the sanity
  1580. checkings for a given configuration.
  1581. DATA:
  1582. self.raw - Stores the config on the RAW format
  1583. self.parsed - Stores the config on the PARSED format
  1584. self.defaults - Stores the default values for all keys
  1585. self.off - Stores the OFF values for all keys
  1586. self.multi - List of keys which can have multiple values
  1587. self.numeric - List of keys which value must be a number
  1588. self.incremental - List of keys which are incremental
  1589. RAW FORMAT:
  1590. The RAW format is a list of lists, being each mother list item
  1591. a full configuration entry. Any entry is a 3 item list, on
  1592. the following format: [ TARGET, KEY, VALUE ]
  1593. Being a list, the order is preserved, so it's easy to use
  1594. different kinds of configs, as CONF area and command line,
  1595. respecting the precedence.
  1596. The special target 'all' is used when no specific target was
  1597. defined on the original config.
  1598. PARSED FORMAT:
  1599. The PARSED format is a dictionary, with all the 'key : value'
  1600. found by reading the RAW config. The self.target contents
  1601. matters, so this dictionary only contains the target's
  1602. config. The configs of other targets are ignored.
  1603. The CommandLine and ConfigLines classes have the get_raw_config()
  1604. method which convert the configuration found to the RAW format.
  1605. Just feed it to parse() and get a brand-new ready-to-use config
  1606. dictionary. Example:
  1607. >>> raw = CommandLine().get_raw_config(['-n', '-H'])
  1608. >>> print raw
  1609. [['all', 'enum-title', ''], ['all', 'no-headers', '']]
  1610. >>> parsed = ConfigMaster(raw).parse()
  1611. >>> print parsed
  1612. {'enum-title': 1, 'headers': 0}
  1613. """
  1614. def __init__(self, raw=[], target=''):
  1615. self.raw = raw
  1616. self.target = target
  1617. self.parsed = {}
  1618. self.dft_options = OPTIONS.copy()
  1619. self.dft_flags = FLAGS.copy()
  1620. self.dft_actions = ACTIONS.copy()
  1621. self.dft_settings = SETTINGS.copy()
  1622. self.defaults = self._get_defaults()
  1623. self.off = self._get_off()
  1624. self.multi = ['infile', 'options','preproc','postproc']
  1625. self.incremental = ['verbose']
  1626. self.numeric = ['toc-level','split']
  1627. def _get_defaults(self):
  1628. "Get the default values for all config/options/flags"
  1629. empty = {}
  1630. for kw in CONFIG_KEYWORDS: empty[kw] = ''
  1631. empty.update(self.dft_options)
  1632. empty.update(self.dft_flags)
  1633. empty.update(self.dft_actions)
  1634. empty.update(self.dft_settings)
  1635. empty['realcmdline'] = '' # internal use only
  1636. empty['sourcefile'] = '' # internal use only
  1637. return empty
  1638. def _get_off(self):
  1639. "Turns OFF all the config/options/flags"
  1640. off = {}
  1641. for key in self.defaults.keys():
  1642. kind = type(self.defaults[key])
  1643. if kind == type(9):
  1644. off[key] = 0
  1645. elif kind == type(''):
  1646. off[key] = ''
  1647. elif kind == type([]):
  1648. off[key] = []
  1649. else:
  1650. Error('ConfigMaster: %s: Unknown type'+key)
  1651. return off
  1652. def _check_target(self):
  1653. "Checks if the target is already defined. If not, do it"
  1654. if not self.target:
  1655. self.target = self.find_value('target')
  1656. def get_target_raw(self):
  1657. "Returns the raw config for self.target or 'all'"
  1658. ret = []
  1659. self._check_target()
  1660. for entry in self.raw:
  1661. if entry[0] in [self.target, 'all']:
  1662. ret.append(entry)
  1663. return ret
  1664. def add(self, key, val):
  1665. "Adds the key:value pair to the config dictionary (if needed)"
  1666. # %!options
  1667. if key == 'options':
  1668. ignoreme = self.dft_actions.keys() + ['target']
  1669. raw_opts = CommandLine().get_raw_config(
  1670. val, ignore=ignoreme)
  1671. for target, key, val in raw_opts:
  1672. self.add(key, val)
  1673. return
  1674. # the no- prefix turns OFF this key
  1675. if key[:3] == 'no-':
  1676. key = key[3:] # remove prefix
  1677. val = self.off.get(key) # turn key OFF
  1678. # is this key valid?
  1679. if key not in self.defaults.keys():
  1680. Debug('Bogus Config %s:%s'%(key,val),1)
  1681. return
  1682. # is this value the default one?
  1683. if val == self.defaults.get(key):
  1684. # if default value, remove previous key:val
  1685. if self.parsed.has_key(key):
  1686. del self.parsed[key]
  1687. # nothing more to do
  1688. return
  1689. # flags ON comes empty. we'll add the 1 value now
  1690. if val == '' and \
  1691. key in self.dft_flags.keys()+self.dft_actions.keys():
  1692. val = 1
  1693. # multi value or single?
  1694. if key in self.multi:
  1695. # first one? start new list
  1696. if not self.parsed.has_key(key):
  1697. self.parsed[key] = []
  1698. self.parsed[key].append(val)
  1699. # incremental value? so let's add it
  1700. elif key in self.incremental:
  1701. self.parsed[key] = (self.parsed.get(key) or 0) + val
  1702. else:
  1703. self.parsed[key] = val
  1704. fancykey = dotted_spaces("%12s"%key)
  1705. Message(_("Added config %s : %s")%(fancykey,val),3)
  1706. def get_outfile_name(self, config={}):
  1707. "Dirname is the same for {in,out}file"
  1708. infile, outfile = config['sourcefile'], config['outfile']
  1709. if outfile and outfile != STDOUT and not os.path.isabs(outfile):
  1710. outfile = os.path.join(os.path.dirname(infile), outfile)
  1711. if infile == STDIN and not outfile: outfile = STDOUT
  1712. if not outfile and (infile and config.get('target')):
  1713. basename = re.sub('\.(txt|t2t)$','',infile)
  1714. outfile = "%s.%s"%(basename, config['target'])
  1715. Debug(" infile: '%s'"%infile , 1)
  1716. Debug("outfile: '%s'"%outfile, 1)
  1717. return outfile
  1718. def sanity(self, config, gui=0):
  1719. "Basic config sanity checkings"
  1720. if not config: return {}
  1721. target = config.get('target')
  1722. # --toc-only doesn't require target specification
  1723. if not target and config.get('toc-only'):
  1724. target = 'txt'
  1725. # on GUI, some checkings are skipped
  1726. if not gui:
  1727. # we *need* a target
  1728. if not target:
  1729. Error(_('No target specified (try --help)')+\
  1730. '\n\n'+\
  1731. _('Maybe trying to convert an old v1.x file?'))
  1732. # and of course, an infile also
  1733. if not config.get('infile'):
  1734. Error(_('Missing input file (try --help)'))
  1735. # is the target valid?
  1736. if not TARGETS.count(target):
  1737. Error(_("Invalid target '%s' (try --help)")%\
  1738. target)
  1739. # ensure all keys are present
  1740. empty = self.defaults.copy() ; empty.update(config)
  1741. config = empty.copy()
  1742. # check integers options
  1743. for key in config.keys():
  1744. if key in self.numeric:
  1745. try: config[key] = int(config[key])
  1746. except: Error(_('--%s value must be a number'
  1747. )%key)
  1748. # check split level value
  1749. if config['split'] not in [0,1,2]:
  1750. Error(_('Option --split must be 0, 1 or 2'))
  1751. # --toc-only is stronger than others
  1752. if config['toc-only']:
  1753. config['headers'] = 0
  1754. config['toc'] = 0
  1755. config['split'] = 0
  1756. config['gui'] = 0
  1757. config['outfile'] = config['outfile'] or STDOUT
  1758. # splitting is disable for now (future: HTML only, no STDOUT)
  1759. config['split'] = 0
  1760. # restore target
  1761. config['target'] = target
  1762. # set output file name
  1763. config['outfile'] = self.get_outfile_name(config)
  1764. # checking suicide
  1765. if config['sourcefile'] == config['outfile'] and \
  1766. config['outfile'] != STDOUT and not gui:
  1767. Error(_("Input and Output files are the same: %s")%(
  1768. config['outfile']))
  1769. return config
  1770. def parse(self):
  1771. "Returns the parsed config for the current target"
  1772. raw = self.get_target_raw()
  1773. for target, key, value in raw:
  1774. self.add(key, value)
  1775. Message(_("Added the following keys: %s")%string.join(
  1776. self.parsed.keys(),', '),2)
  1777. return self.parsed.copy()
  1778. def find_value(self, key='', target=''):
  1779. "Scans ALL raw config to find the desired key"
  1780. ret = []
  1781. # scan and save all values found
  1782. for targ, k, val in self.raw:
  1783. if targ in [target, 'all'] and k == key:
  1784. ret.append(val)
  1785. if not ret: return ''
  1786. # if not multi value, return only the last found
  1787. if key in self.multi: return ret
  1788. else : return ret[-1]
  1789. ########################################################################
  1790. class ConfigLines:
  1791. """
  1792. ConfigLines class - the config file data extractor
  1793. This class reads and parse the config lines on the %!key:val
  1794. format, converting it to RAW config. It deals with user
  1795. config file (RC file), source document CONF area and
  1796. %!includeconf directives.
  1797. Call it passing a file name or feed the desired config lines.
  1798. Then just call the get_raw_config() method and wait to
  1799. receive the full config data on the RAW format. This method
  1800. also follows the possible %!includeconf directives found on
  1801. the config lines. Example:
  1802. raw = ConfigLines(file=".txt2tagsrc").get_raw_config()
  1803. The parse_line() method is also useful to be used alone,
  1804. to identify and tokenize a single config line. For example,
  1805. to get the %!include command components, on the source
  1806. document BODY:
  1807. target, key, value = ConfigLines().parse_line(body_line)
  1808. """
  1809. def __init__(self, file='', lines=[], first_line=1):
  1810. self.file = file or 'NOFILE'
  1811. self.lines = lines
  1812. self.first_line = first_line
  1813. def load_lines(self):
  1814. "Make sure we've loaded the file contents into buffer"
  1815. if not self.lines and not self.file:
  1816. Error("ConfigLines: No file or lines provided")
  1817. if not self.lines:
  1818. self.lines = self.read_config_file(self.file)
  1819. def read_config_file(self, filename=''):
  1820. "Read a Config File contents, aborting on invalid line"
  1821. if not filename: return []
  1822. errormsg = _("Invalid CONFIG line on %s")+"\n%03d:%s"
  1823. lines = Readfile(filename, remove_linebreaks=1)
  1824. # sanity: try to find invalid config lines
  1825. for i in range(len(lines)):
  1826. line = string.rstrip(lines[i])
  1827. if not line: continue # empty
  1828. if line[0] != '%': Error(errormsg%(filename,i+1,line))
  1829. return lines
  1830. def include_config_file(self, file=''):
  1831. "Perform the %!includeconf action, returning RAW config"
  1832. if not file: return []
  1833. # current dir relative to the current file (self.file)
  1834. current_dir = os.path.dirname(self.file)
  1835. file = os.path.join(current_dir, file)
  1836. # read and parse included config file contents
  1837. lines = self.read_config_file(file)
  1838. return ConfigLines(file=file, lines=lines).get_raw_config()
  1839. def get_raw_config(self):
  1840. "Scan buffer and extract all config as RAW (including includes)"
  1841. ret = []
  1842. self.load_lines()
  1843. first = self.first_line
  1844. for i in range(len(self.lines)):
  1845. line = self.lines[i]
  1846. Message(_("Processing line %03d: %s")%(first+i,line),2)
  1847. target, key, val = self.parse_line(line)
  1848. if not key: continue # no config on this line
  1849. if key == 'includeconf':
  1850. more_raw = self.include_config_file(val)
  1851. ret.extend(more_raw)
  1852. Message(_("Finished Config file inclusion: %s"
  1853. )%(val),2)
  1854. else:
  1855. ret.append([target, key, val])
  1856. Message(_("Added %s")%key,3)
  1857. return ret
  1858. def parse_line(self, line='', keyname='', target=''):
  1859. "Detects %!key:val config lines and extract data from it"
  1860. empty = ['', '', '']
  1861. if not line: return empty
  1862. no_target = ['target', 'includeconf']
  1863. re_name = keyname or '[a-z]+'
  1864. re_target = target or '[a-z]*'
  1865. cfgregex = re.compile("""
  1866. ^%%!\s* # leading id with opt spaces
  1867. (?P<name>%s)\s* # config name
  1868. (\((?P<target>%s)\))? # optional target spec inside ()
  1869. \s*:\s* # key:value delimiter with opt spaces
  1870. (?P<value>\S.+?) # config value
  1871. \s*$ # rstrip() spaces and hit EOL
  1872. """%(re_name,re_target), re.I+re.VERBOSE)
  1873. prepostregex = re.compile("""
  1874. # ---[ PATTERN ]---
  1875. ^( "([^"]*)" # "double quoted" or
  1876. | '([^']*)' # 'single quoted' or
  1877. | ([^\s]+) # single_word
  1878. )
  1879. \s+ # separated by spaces
  1880. # ---[ REPLACE ]---
  1881. ( "([^"]*)" # "double quoted" or
  1882. | '([^']*)' # 'single quoted' or
  1883. | (.*) # anything
  1884. )
  1885. \s*$
  1886. """, re.VERBOSE)
  1887. guicolors = re.compile("^([^\s]+\s+){3}[^\s]+") # 4 tokens
  1888. match = cfgregex.match(line)
  1889. if not match: return empty
  1890. name = string.lower(match.group('name') or '')
  1891. target = string.lower(match.group('target') or 'all')
  1892. value = match.group('value')
  1893. # NO target keywords: force all targets
  1894. if name in no_target: target = 'all'
  1895. # special config for GUI colors
  1896. if name == 'guicolors':
  1897. valmatch = guicolors.search(value)
  1898. if not valmatch: return empty
  1899. value = re.split('\s+', value)
  1900. # Special config with two quoted values (%!preproc: "foo" 'bar')
  1901. if name in ['preproc','postproc']:
  1902. valmatch = prepostregex.search(value)
  1903. if not valmatch: return empty
  1904. getval = valmatch.group
  1905. patt = getval(2) or getval(3) or getval(4) or ''
  1906. repl = getval(6) or getval(7) or getval(8) or ''
  1907. value = (patt, repl)
  1908. return [target, name, value]
  1909. ##############################################################################
  1910. class MaskMaster:
  1911. "(Un)Protect important structures from escaping and formatting"
  1912. def __init__(self):
  1913. self.linkmask = 'vvvLINKvvv'
  1914. self.monomask = 'vvvMONOvvv'
  1915. self.macromask = 'vvvMACROvvv'
  1916. self.rawmask = 'vvvRAWvvv'
  1917. self.tocmask = 'vvvTOCvvv'
  1918. self.macroman = MacroMaster()
  1919. self.reset()
  1920. def reset(self):
  1921. self.linkbank = []
  1922. self.monobank = []
  1923. self.macrobank = []
  1924. self.rawbank = []
  1925. def mask(self, line=''):
  1926. global AUTOTOC
  1927. # protect raw text
  1928. while regex['raw'].search(line):
  1929. txt = regex['raw'].search(line).group(1)
  1930. txt = doEscape(TARGET,txt)
  1931. self.rawbank.append(txt)
  1932. line = regex['raw'].sub(self.rawmask,line,1)
  1933. # protect pre-formatted font text
  1934. while regex['fontMono'].search(line):
  1935. txt = regex['fontMono'].search(line).group(1)
  1936. txt = doEscape(TARGET,txt)
  1937. self.monobank.append(txt)
  1938. line = regex['fontMono'].sub(self.monomask,line,1)
  1939. # protect macros
  1940. while regex['macros'].search(line):
  1941. txt = regex['macros'].search(line).group()
  1942. self.macrobank.append(txt)
  1943. line = regex['macros'].sub(self.macromask,line,1)
  1944. # protect TOC location
  1945. while regex['toc'].search(line):
  1946. line = regex['toc'].sub(self.tocmask,line)
  1947. AUTOTOC = 0
  1948. # protect URLs and emails
  1949. while regex['linkmark'].search(line) or \
  1950. regex['link' ].search(line):
  1951. # try to match plain or named links
  1952. match_link = regex['link'].search(line)
  1953. match_named = regex['linkmark'].search(line)
  1954. # define the current match
  1955. if match_link and match_named:
  1956. # both types found, which is the first?
  1957. m = match_link
  1958. if match_named.start() < match_link.start():
  1959. m = match_named
  1960. else:
  1961. # just one type found, we're fine
  1962. m = match_link or match_named
  1963. # extract link data and apply mask
  1964. if m == match_link: # plain link
  1965. link = m.group()
  1966. label = ''
  1967. link_re = regex['link']
  1968. else: # named link
  1969. link = m.group('link')
  1970. label = string.rstrip(m.group('label'))
  1971. link_re = regex['linkmark']
  1972. line = link_re.sub(self.linkmask,line,1)
  1973. # save link data to the link bank
  1974. self.linkbank.append((label, link))
  1975. return line
  1976. def undo(self, line):
  1977. # url & email
  1978. for label,url in self.linkbank:
  1979. link = get_tagged_link(label, url)
  1980. line = string.replace(line, self.linkmask, link, 1)
  1981. # expand macros
  1982. for macro in self.macrobank:
  1983. macro = self.macroman.expand(macro)
  1984. line = string.replace(line, self.macromask, macro,1)
  1985. # expand verb
  1986. for mono in self.monobank:
  1987. open,close = TAGS['fontMonoOpen'],TAGS['fontMonoClose']
  1988. tagged = open+mono+close
  1989. line = string.replace(line,self.monomask,tagged,1)
  1990. # expand raw
  1991. for raw in self.rawbank:
  1992. line = string.replace(line,self.rawmask,raw,1)
  1993. return line
  1994. ##############################################################################
  1995. class TitleMaster:
  1996. "Title things"
  1997. def __init__(self):
  1998. self.count = ['',0,0,0,0,0]
  1999. self.toc = []
  2000. self.level = 0
  2001. self.kind = ''
  2002. self.txt = ''
  2003. self.label = ''
  2004. self.tag = ''
  2005. self.tag_hold = []
  2006. self.last_level = 0
  2007. self.count_id = ''
  2008. self.user_labels = {}
  2009. self.anchor_count = 0
  2010. self.anchor_prefix = 'toc'
  2011. def _open_close_blocks(self):
  2012. "Open new title blocks, closing the previous (if any)"
  2013. if not rules['titleblocks']: return
  2014. tag = ''
  2015. last = self.last_level
  2016. curr = self.level
  2017. # same level, just close the previous
  2018. if curr == last:
  2019. tag = TAGS.get('title%dClose'%last)
  2020. if tag: self.tag_hold.append(tag)
  2021. # section -> subsection, more depth
  2022. while curr > last:
  2023. last = last + 1
  2024. # open the new block of subsections
  2025. tag = TAGS.get('blockTitle%dOpen'%last)
  2026. if tag: self.tag_hold.append(tag)
  2027. # jump from title1 to title3 or more
  2028. # fill the gap with an empty section
  2029. if curr - last > 0:
  2030. tag = TAGS.get('title%dOpen'%last)
  2031. tag = regex['x'].sub('', tag) # del \a
  2032. if tag: self.tag_hold.append(tag)
  2033. # section <- subsection, less depth
  2034. while curr < last:
  2035. # close the current opened subsection
  2036. tag = TAGS.get('title%dClose'%last)
  2037. if tag: self.tag_hold.append(tag)
  2038. # close the current opened block of subsections
  2039. tag = TAGS.get('blockTitle%dClose'%last)
  2040. if tag: self.tag_hold.append(tag)
  2041. last = last - 1
  2042. # close the previous section of the same level
  2043. # the subsections were under it
  2044. if curr == last:
  2045. tag = TAGS.get('title%dClose'%last)
  2046. if tag: self.tag_hold.append(tag)
  2047. def add(self, line):
  2048. "Parses a new title line."
  2049. if not line: return
  2050. self._set_prop(line)
  2051. self._open_close_blocks()
  2052. self._set_count_id()
  2053. self._set_label()
  2054. self._save_toc_info()
  2055. def close_all(self):
  2056. "Closes all opened title blocks"
  2057. ret = []
  2058. ret.extend(self.tag_hold)
  2059. while self.level:
  2060. tag = TAGS.get('title%dClose'%self.level)
  2061. if tag: ret.append(tag)
  2062. tag = TAGS.get('blockTitle%dClose'%self.level)
  2063. if tag: ret.append(tag)
  2064. self.level = self.level - 1
  2065. return ret
  2066. def _save_toc_info(self):
  2067. "Save TOC info, used by self.dump_marked_toc()"
  2068. self.toc.append((self.level, self.count_id,
  2069. self.txt , self.label ))
  2070. def _set_prop(self, line=''):
  2071. "Extract info from original line and set data holders."
  2072. # detect title type (numbered or not)
  2073. id = string.lstrip(line)[0]
  2074. if id == '=': kind = 'title'
  2075. elif id == '+': kind = 'numtitle'
  2076. else: Error("Unknown Title ID '%s'"%id)
  2077. # extract line info
  2078. match = regex[kind].search(line)
  2079. level = len(match.group('id'))
  2080. txt = string.strip(match.group('txt'))
  2081. label = match.group('label')
  2082. # parse info & save
  2083. if CONF['enum-title']: kind = 'numtitle' # force
  2084. if rules['titleblocks']:
  2085. self.tag = TAGS.get('%s%dOpen'%(kind,level)) or \
  2086. TAGS.get('title%dOpen'%level)
  2087. else:
  2088. self.tag = TAGS.get(kind+`level`) or \
  2089. TAGS.get('title'+`level`)
  2090. self.last_level = self.level
  2091. self.kind = kind
  2092. self.level = level
  2093. self.txt = txt
  2094. self.label = label
  2095. def _set_count_id(self):
  2096. "Compose and save the title count identifier (if needed)."
  2097. count_id = ''
  2098. if self.kind == 'numtitle' and not rules['autonumbertitle']:
  2099. # manually increase title count
  2100. self.count[self.level] = self.count[self.level] +1
  2101. # reset sublevels count (if any)
  2102. max_levels = len(self.count)
  2103. if self.level < max_levels-1:
  2104. for i in range(self.level+1, max_levels):
  2105. self.count[i] = 0
  2106. # compose count id from hierarchy
  2107. for i in range(self.level):
  2108. count_id= "%s%d."%(count_id, self.count[i+1])
  2109. self.count_id = count_id
  2110. def _set_label(self):
  2111. "Compose and save title label, used by anchors."
  2112. # remove invalid chars from label set by user
  2113. self.label = re.sub('[^A-Za-z0-9_-]', '', self.label or '')
  2114. # generate name as 15 first :alnum: chars
  2115. #TODO how to translate safely accented chars to plain?
  2116. #self.label = re.sub('[^A-Za-z0-9]', '', self.txt)[:15]
  2117. # 'tocN' label - sequential count, ignoring 'toc-level'
  2118. #self.label = self.anchor_prefix + str(len(self.toc)+1)
  2119. def _get_tagged_anchor(self):
  2120. "Return anchor if user defined a label, or TOC is on."
  2121. ret = ''
  2122. label = self.label
  2123. if CONF['toc'] and self.level <= CONF['toc-level']:
  2124. # this count is needed bcos self.toc stores all
  2125. # titles, regardless of the 'toc-level' setting,
  2126. # so we can't use self.toc lenght to number anchors
  2127. self.anchor_count = self.anchor_count + 1
  2128. # autonumber label (if needed)
  2129. label = label or '%s%s'%(
  2130. self.anchor_prefix, self.anchor_count)
  2131. if label and TAGS['anchor']:
  2132. ret = regex['x'].sub(label,TAGS['anchor'])
  2133. return ret
  2134. def _get_full_title_text(self):
  2135. "Returns the full title contents, already escaped."
  2136. ret = self.txt
  2137. # insert count_id (if any) before text
  2138. if self.count_id:
  2139. ret = '%s %s'%(self.count_id, ret)
  2140. # escape specials
  2141. ret = doEscape(TARGET, ret)
  2142. # same targets needs final escapes on title lines
  2143. # it's here because there is a 'continue' after title
  2144. if rules['finalescapetitle']:
  2145. ret = doFinalEscape(TARGET, ret)
  2146. return ret
  2147. def get(self):
  2148. "Returns the tagged title as a list."
  2149. ret = []
  2150. # maybe some anchoring before?
  2151. anchor = self._get_tagged_anchor()
  2152. self.tag = regex['_anchor'].sub(anchor, self.tag)
  2153. ### compose & escape title text (TOC uses unescaped)
  2154. full_title = self._get_full_title_text()
  2155. # close previous section area
  2156. ret.extend(self.tag_hold)
  2157. self.tag_hold = []
  2158. # finish title, adding "underline" on TXT target
  2159. tagged = regex['x'].sub(full_title, self.tag)
  2160. if TARGET == 'txt':
  2161. ret.append('') # blank line before
  2162. ret.append(tagged)
  2163. ret.append(regex['x'].sub('='*len(full_title),self.tag))
  2164. ret.append('') # blank line after
  2165. else:
  2166. ret.append(tagged)
  2167. return ret
  2168. def dump_marked_toc(self, max_level=99):
  2169. "Dumps all toc itens as a valid t2t markup list"
  2170. #TODO maybe use quote+linebreaks instead lists
  2171. ret = []
  2172. toc_count = 1
  2173. for level, count_id, txt, label in self.toc:
  2174. if level > max_level: continue # ignore
  2175. indent = ' '*level
  2176. id_txt = string.lstrip('%s %s'%(count_id, txt))
  2177. label = label or self.anchor_prefix+`toc_count`
  2178. toc_count = toc_count + 1
  2179. # TOC will have links
  2180. if TAGS['anchor']:
  2181. # TOC is more readable with master topics
  2182. # not linked at number. This is a stoled
  2183. # idea from Windows .CHM help files
  2184. if CONF['enum-title'] and level == 1:
  2185. tocitem = '%s+ [""%s"" #%s]'%(
  2186. indent, txt, label)
  2187. else:
  2188. tocitem = '%s- [""%s"" #%s]'%(
  2189. indent, id_txt, label)
  2190. # no links on TOC, just text
  2191. else:
  2192. # man don't reformat TOC lines, cool!
  2193. if TARGET in ['txt', 'man']:
  2194. tocitem = '%s""%s""' %(
  2195. indent, id_txt)
  2196. else:
  2197. tocitem = '%s- ""%s""'%(
  2198. indent, id_txt)
  2199. ret.append(tocitem)
  2200. return ret
  2201. ##############################################################################
  2202. #TODO check all this table mess
  2203. # trata linhas TABLE, com as prop do parse_row
  2204. # o metodo table() do BLOCK xunxa e troca as celulas pelas parseadas
  2205. class TableMaster:
  2206. def __init__(self, line=''):
  2207. self.rows = []
  2208. self.border = 0
  2209. self.align = 'Left'
  2210. self.cellalign = []
  2211. if line:
  2212. prop = self.parse_row(line)
  2213. self.border = prop['border']
  2214. self.align = prop['align']
  2215. self.cellalign = prop['cellalign']
  2216. def _get_open_tag(self):
  2217. topen = TAGS['tableOpen']
  2218. tborder = TAGS['tableBorder']
  2219. talign = TAGS['tableAlign'+self.align]
  2220. calignsep = TAGS['tableColAlignSep']
  2221. calign = ''
  2222. # the first line defines if table has border or not
  2223. if not self.border: tborder = ''
  2224. # set the columns alignment
  2225. if rules['tablecellaligntype'] == 'column':
  2226. calign = map(lambda x: TAGS['tableColAlign%s'%x],
  2227. self.cellalign)
  2228. calign = string.join(calign, calignsep)
  2229. # align full table, set border and Column align (if any)
  2230. topen = regex['_tableAlign' ].sub(talign , topen)
  2231. topen = regex['_tableBorder' ].sub(tborder, topen)
  2232. topen = regex['_tableColAlign'].sub(calign , topen)
  2233. # tex table spec, border or not: {|l|c|r|} , {lcr}
  2234. if calignsep and not self.border:
  2235. # remove cell align separator
  2236. topen = string.replace(topen, calignsep, '')
  2237. return topen
  2238. def _get_cell_align(self, cells):
  2239. ret = []
  2240. for cell in cells:
  2241. align = 'Left'
  2242. if string.strip(cell):
  2243. if cell[0] == ' ' and cell[-1] == ' ':
  2244. align = 'Center'
  2245. elif cell[0] == ' ':
  2246. align = 'Right'
  2247. ret.append(align)
  2248. return ret
  2249. def _tag_cells(self, rowdata):
  2250. row = []
  2251. cells = rowdata['cells']
  2252. open = TAGS['tableCellOpen']
  2253. close = TAGS['tableCellClose']
  2254. sep = TAGS['tableCellSep']
  2255. calign = map(lambda x: TAGS['tableCellAlign'+x],
  2256. rowdata['cellalign'])
  2257. # maybe is it a title row?
  2258. if rowdata['title']:
  2259. open = TAGS['tableTitleCellOpen'] or open
  2260. close = TAGS['tableTitleCellClose'] or close
  2261. sep = TAGS['tableTitleCellSep'] or sep
  2262. # should we break the line on *each* table cell?
  2263. if rules['breaktablecell']: close = close+'\n'
  2264. # cells pre processing
  2265. if rules['tablecellstrip']:
  2266. cells = map(lambda x: string.strip(x), cells)
  2267. if rowdata['title'] and rules['tabletitlerowinbold']:
  2268. cells = map(lambda x: enclose_me('fontBold',x), cells)
  2269. # add cell BEGIN/END tags
  2270. for cell in cells:
  2271. # insert cell align into open tag (if cell is alignable)
  2272. if rules['tablecellaligntype'] == 'cell':
  2273. copen = string.replace(open,'\a',calign.pop(0))
  2274. else:
  2275. copen = open
  2276. row.append(copen + cell + close)
  2277. # maybe there are cell separators?
  2278. return string.join(row, sep)
  2279. def add_row(self, cells):
  2280. self.rows.append(cells)
  2281. def parse_row(self, line):
  2282. # default table proprierties
  2283. ret = {'border':0,'title':0,'align':'Left',
  2284. 'cells':[],'cellalign':[]}
  2285. # detect table align (and remove spaces mark)
  2286. if line[0] == ' ': ret['align'] = 'Center'
  2287. line = string.lstrip(line)
  2288. # detect title mark
  2289. if line[1] == '|': ret['title'] = 1
  2290. # delete trailing spaces after last cell border
  2291. line = re.sub('\|\s*$','|', line)
  2292. # detect (and delete) border mark (and leading space)
  2293. if line[-1] == '|': ret['border'] = 1 ; line = line[:-2]
  2294. # delete table mark
  2295. line = regex['table'].sub('', line)
  2296. # split cells
  2297. ret['cells'] = string.split(line, ' | ')
  2298. # find cells align
  2299. ret['cellalign'] = self._get_cell_align(ret['cells'])
  2300. Debug('Table Prop: %s' % ret, 7)
  2301. return ret
  2302. def dump(self):
  2303. open = self._get_open_tag()
  2304. rows = self.rows
  2305. close = TAGS['tableClose']
  2306. rowopen = TAGS['tableRowOpen']
  2307. rowclose = TAGS['tableRowClose']
  2308. rowsep = TAGS['tableRowSep']
  2309. titrowopen = TAGS['tableTitleRowOpen'] or rowopen
  2310. titrowclose = TAGS['tableTitleRowClose'] or rowclose
  2311. if rules['breaktablelineopen']:
  2312. rowopen = rowopen + '\n'
  2313. titrowopen = titrowopen + '\n'
  2314. # tex gotchas
  2315. if TARGET == 'tex':
  2316. if not self.border:
  2317. rowopen = titrowopen = ''
  2318. else:
  2319. close = rowopen + close
  2320. # now we tag all the table cells on each row
  2321. #tagged_cells = map(lambda x: self._tag_cells(x), rows) #!py15
  2322. tagged_cells = []
  2323. for cell in rows: tagged_cells.append(self._tag_cells(cell))
  2324. # add row separator tags between lines
  2325. tagged_rows = []
  2326. if rowsep:
  2327. #!py15
  2328. #tagged_rows = map(lambda x:x+rowsep, tagged_cells)
  2329. for cell in tagged_cells:
  2330. tagged_rows.append(cell+rowsep)
  2331. # remove last rowsep, because the table is over
  2332. tagged_rows[-1] = string.replace(
  2333. tagged_rows[-1], rowsep, '')
  2334. # add row BEGIN/END tags for each line
  2335. else:
  2336. for rowdata in rows:
  2337. if rowdata['title']:
  2338. o,c = titrowopen, titrowclose
  2339. else:
  2340. o,c = rowopen, rowclose
  2341. row = tagged_cells.pop(0)
  2342. tagged_rows.append(o + row + c)
  2343. fulltable = [open] + tagged_rows + [close]
  2344. if rules['blankendtable']: fulltable.append('')
  2345. return fulltable
  2346. ##############################################################################
  2347. class BlockMaster:
  2348. "TIP: use blockin/out to add/del holders"
  2349. def __init__(self):
  2350. self.BLK = []
  2351. self.HLD = []
  2352. self.PRP = []
  2353. self.depth = 0
  2354. self.last = ''
  2355. self.tableparser = None
  2356. self.contains = {
  2357. 'para' :['passthru','raw'],
  2358. 'verb' :[],
  2359. 'table' :[],
  2360. 'raw' :[],
  2361. 'passthru':[],
  2362. 'quote' :['quote','passthru','raw'],
  2363. 'list' :['list' ,'numlist' ,'deflist','para','verb',
  2364. 'raw' ,'passthru'],
  2365. 'numlist' :['list' ,'numlist' ,'deflist','para','verb',
  2366. 'raw' ,'passthru'],
  2367. 'deflist' :['list' ,'numlist' ,'deflist','para','verb',
  2368. 'raw' ,'passthru']
  2369. }
  2370. self.allblocks = self.contains.keys()
  2371. def block(self):
  2372. if not self.BLK: return ''
  2373. return self.BLK[-1]
  2374. def isblock(self, name=''):
  2375. return self.block() == name
  2376. def prop(self, key):
  2377. if not self.PRP: return ''
  2378. return self.PRP[-1].get(key) or ''
  2379. def propset(self, key, val):
  2380. self.PRP[-1][key] = val
  2381. #Debug('BLOCK prop ++: %s->%s'%(key,repr(val)), 1)
  2382. #Debug('BLOCK props: %s'%(repr(self.PRP)), 1)
  2383. def hold(self):
  2384. if not self.HLD: return []
  2385. return self.HLD[-1]
  2386. def holdadd(self, line):
  2387. if self.block()[-4:] == 'list': line = [line]
  2388. self.HLD[-1].append(line)
  2389. Debug('HOLD add: %s'%repr(line), 4)
  2390. Debug('FULL HOLD: %s'%self.HLD, 4)
  2391. def holdaddsub(self, line):
  2392. self.HLD[-1][-1].append(line)
  2393. Debug('HOLD addsub: %s'%repr(line), 4)
  2394. Debug('FULL HOLD: %s'%self.HLD, 4)
  2395. def holdextend(self, lines):
  2396. if self.block()[-4:] == 'list': lines = [lines]
  2397. self.HLD[-1].extend(lines)
  2398. Debug('HOLD extend: %s'%repr(lines), 4)
  2399. Debug('FULL HOLD: %s'%self.HLD, 4)
  2400. def blockin(self, block):
  2401. ret = []
  2402. if block not in self.allblocks:
  2403. Error("Invalid block '%s'"%block)
  2404. # first, let's close other possible open blocks
  2405. while self.block() and block not in self.contains[self.block()]:
  2406. ret.extend(self.blockout())
  2407. # now we can gladly add this new one
  2408. self.BLK.append(block)
  2409. self.HLD.append([])
  2410. self.PRP.append({})
  2411. if block == 'table': self.tableparser = TableMaster()
  2412. # deeper and deeper
  2413. self.depth = len(self.BLK)
  2414. Debug('block ++ (%s): %s' % (block,self.BLK), 3)
  2415. return ret
  2416. def blockout(self):
  2417. if not self.BLK: Error('No block to pop')
  2418. self.last = self.BLK.pop()
  2419. tagged = getattr(self, self.last)()
  2420. parsed = self.HLD.pop()
  2421. self.PRP.pop()
  2422. self.depth = len(self.BLK)
  2423. if self.last == 'table': del self.tableparser
  2424. # inserting a nested block into mother
  2425. if self.block():
  2426. if self.block()[-4:] == 'list':
  2427. self.HLD[-1][-1].append(tagged)
  2428. else:
  2429. self.HLD[-1].append(tagged)
  2430. tagged = [] # reset. mother will have it all
  2431. Debug('block -- (%s): %s' % (self.last,self.BLK), 3)
  2432. Debug('RELEASED (%s): %s' % (self.last,parsed), 3)
  2433. if tagged: Debug('BLOCK: %s'%tagged, 6)
  2434. return tagged
  2435. def _last_escapes(self, line):
  2436. return doFinalEscape(TARGET, line)
  2437. def _get_escaped_hold(self):
  2438. ret = []
  2439. for line in self.hold():
  2440. linetype = type(line)
  2441. if linetype == type(''):
  2442. ret.append(self._last_escapes(line))
  2443. elif linetype == type([]):
  2444. ret.extend(line)
  2445. else:
  2446. Error("BlockMaster: Unknown HOLD item type:"
  2447. " %s"%linetype)
  2448. return ret
  2449. def _remove_twoblanks(self, lastitem):
  2450. if len(lastitem) > 1 and lastitem[-2:] == ['','']:
  2451. return lastitem[:-2]
  2452. return lastitem
  2453. def passthru(self):
  2454. return self.hold()
  2455. def raw(self):
  2456. lines = self.hold()
  2457. return map(lambda x: doEscape(TARGET, x), lines)
  2458. def para(self):
  2459. tagged = []
  2460. open = TAGS['paragraphOpen']
  2461. close = TAGS['paragraphClose']
  2462. lines = self._get_escaped_hold()
  2463. # open (or not) paragraph
  2464. if not open+close and self.last == 'para':
  2465. pass # avoids multiple blank lines
  2466. else:
  2467. tagged.append(open)
  2468. # pagemaker likes a paragraph as a single long line
  2469. if rules['onelinepara']:
  2470. tagged.append(string.join(lines,' '))
  2471. # others are normal :)
  2472. else:
  2473. tagged.extend(lines)
  2474. tagged.append(close)
  2475. # very very very very very very very very very UGLY fix
  2476. # needed because <center> can't appear inside <p>
  2477. try:
  2478. if len(lines) == 1 and \
  2479. TARGET in ('html', 'xhtml') and \
  2480. re.match('^\s*<center>.*</center>\s*$', lines[0]):
  2481. tagged = [lines[0]]
  2482. except: pass
  2483. return tagged
  2484. def verb(self):
  2485. "Verbatim lines are not masked, so there's no need to unmask"
  2486. tagged = []
  2487. tagged.append(TAGS['blockVerbOpen'])
  2488. for line in self.hold():
  2489. if self.prop('mapped') == 'table':
  2490. line = MacroMaster().expand(line)
  2491. if not rules['verbblocknotescaped']:
  2492. line = doEscape(TARGET,line)
  2493. if rules['indentverbblock']:
  2494. line = ' '+line
  2495. if rules['verbblockfinalescape']:
  2496. line = doFinalEscape(TARGET, line)
  2497. tagged.append(line)
  2498. #TODO maybe use if not TAGS['blockVerbClose']
  2499. if TARGET != 'pm6':
  2500. tagged.append(TAGS['blockVerbClose'])
  2501. return tagged
  2502. def table(self):
  2503. # rewrite all table cells by the unmasked and escaped data
  2504. lines = self._get_escaped_hold()
  2505. for i in range(len(lines)):
  2506. cells = string.split(lines[i], SEPARATOR)
  2507. self.tableparser.rows[i]['cells'] = cells
  2508. return self.tableparser.dump()
  2509. def quote(self):
  2510. tagged = []
  2511. myre = regex['quote']
  2512. open = TAGS['blockQuoteOpen'] # block based
  2513. close = TAGS['blockQuoteClose']
  2514. qline = TAGS['blockQuoteLine'] # line based
  2515. indent = tagindent = '\t'*self.depth
  2516. if rules['tagnotindentable']: tagindent = ''
  2517. if not rules['keepquoteindent']: indent = ''
  2518. if open: tagged.append(tagindent+open) # open block
  2519. for item in self.hold():
  2520. if type(item) == type([]):
  2521. tagged.extend(item) # subquotes
  2522. else:
  2523. item = myre.sub('', item) # del TABs
  2524. if rules['barinsidequote']:
  2525. item = get_tagged_bar(item)
  2526. item = self._last_escapes(item)
  2527. item = qline*self.depth + item
  2528. tagged.append(indent+item) # quote line
  2529. if close: tagged.append(tagindent+close) # close block
  2530. return tagged
  2531. def deflist(self): return self.list('deflist')
  2532. def numlist(self): return self.list('numlist')
  2533. def list(self, name='list'):
  2534. tagged = []
  2535. items = self.hold()
  2536. indent = self.prop('indent')
  2537. tagindent = indent
  2538. listopen = TAGS.get(name+'Open')
  2539. listclose = TAGS.get(name+'Close')
  2540. listline = TAGS.get(name+'ItemLine')
  2541. itemcount = 0
  2542. if rules['tagnotindentable']: tagindent = ''
  2543. if not rules['keeplistindent']: indent = ''
  2544. if name == 'deflist':
  2545. itemopen = TAGS[name+'Item1Open']
  2546. itemclose = TAGS[name+'Item2Close']
  2547. itemsep = TAGS[name+'Item1Close']+\
  2548. TAGS[name+'Item2Open']
  2549. else:
  2550. itemopen = TAGS[name+'ItemOpen']
  2551. itemclose = TAGS[name+'ItemClose']
  2552. itemsep = ''
  2553. # ItemLine: number of leading chars identifies list depth
  2554. if listline:
  2555. itemopen = listline*self.depth
  2556. # dirty fix for mgp
  2557. if name == 'numlist': itemopen = itemopen + '\a. '
  2558. # remove two-blanks from list ending mark, to avoid <p>
  2559. items[-1] = self._remove_twoblanks(items[-1])
  2560. # open list (not nestable lists are only opened at mother)
  2561. if listopen and not \
  2562. (rules['listnotnested'] and BLOCK.depth != 1):
  2563. tagged.append(tagindent+listopen)
  2564. # tag each list item (multine items)
  2565. itemopenorig = itemopen
  2566. for item in items:
  2567. # add "manual" item count for noautonum targets
  2568. itemcount = itemcount + 1
  2569. if name == 'numlist' and not rules['autonumberlist']:
  2570. n = str(itemcount)
  2571. itemopen = regex['x'].sub(n, itemopenorig)
  2572. del n
  2573. item[0] = self._last_escapes(item[0])
  2574. if name == 'deflist':
  2575. term, rest = string.split(item[0],SEPARATOR,1)
  2576. item[0] = rest
  2577. if not item[0]: del item[0] # to avoid <p>
  2578. tagged.append(tagindent+itemopen+term+itemsep)
  2579. else:
  2580. fullitem = tagindent+itemopen
  2581. tagged.append(string.replace(
  2582. item[0], SEPARATOR, fullitem))
  2583. del item[0]
  2584. # process next lines for this item (if any)
  2585. for line in item:
  2586. if type(line) == type([]): # sublist inside
  2587. tagged.extend(line)
  2588. else:
  2589. line = self._last_escapes(line)
  2590. # blank lines turns to <p>
  2591. if not line and rules['parainsidelist']:
  2592. line = string.rstrip(indent +\
  2593. TAGS['paragraphOpen']+\
  2594. TAGS['paragraphClose'])
  2595. if not rules['keeplistindent']:
  2596. line = string.lstrip(line)
  2597. tagged.append(line)
  2598. # close item (if needed)
  2599. if itemclose: tagged.append(tagindent+itemclose)
  2600. # close list (not nestable lists are only closed at mother)
  2601. if listclose and not \
  2602. (rules['listnotnested'] and BLOCK.depth != 1):
  2603. tagged.append(tagindent+listclose)
  2604. if rules['blankendmotherlist'] and BLOCK.depth == 1:
  2605. tagged.append('')
  2606. return tagged
  2607. ##############################################################################
  2608. class MacroMaster:
  2609. def __init__(self, config={}):
  2610. self.name = ''
  2611. self.config = config or CONF
  2612. self.infile = self.config['sourcefile']
  2613. self.outfile = self.config['outfile']
  2614. self.currdate = time.localtime(time.time())
  2615. self.rgx = regex.get('macros') or getRegexes()['macros']
  2616. self.fileinfo = { 'infile': None, 'outfile': None }
  2617. self.dft_fmt = MACROS
  2618. def walk_file_format(self, fmt):
  2619. "Walks the %%{in/out}file format string, expanding the % flags"
  2620. i = 0; ret = '' # counter/hold
  2621. while i < len(fmt): # char by char
  2622. c = fmt[i]; i = i + 1
  2623. if c == '%': # hot char!
  2624. if i == len(fmt): # % at the end
  2625. ret = ret + c
  2626. break
  2627. c = fmt[i]; i = i + 1 # read next
  2628. ret = ret + self.expand_file_flag(c)
  2629. else:
  2630. ret = ret +c # common char
  2631. return ret
  2632. def expand_file_flag(self, flag):
  2633. "%f: filename %F: filename (w/o extension)"
  2634. "%d: dirname %D: dirname (only parent dir)"
  2635. "%p: file path %e: extension"
  2636. info = self.fileinfo[self.name] # get dict
  2637. if flag == '%': x = '%' # %% -> %
  2638. elif flag == 'f': x = info['name']
  2639. elif flag == 'F': x = re.sub('\.[^.]*$','',info['name'])
  2640. elif flag == 'd': x = info['dir']
  2641. elif flag == 'D': x = os.path.split(info['dir'])[-1]
  2642. elif flag == 'p': x = info['path']
  2643. elif flag == 'e': x = re.search('.(\.([^.]+))?$',info['name']
  2644. ).group(2) or ''
  2645. #TODO simplier way for %e ?
  2646. else : x = '%'+flag # false alarm
  2647. return x
  2648. def set_file_info(self, macroname):
  2649. if self.fileinfo.get(macroname): return # already done
  2650. file = getattr(self, self.name) # self.infile
  2651. if file == STDOUT:
  2652. dir = ''; path = name = STDOUT
  2653. else:
  2654. path = os.path.abspath(file)
  2655. dir = os.path.dirname(path)
  2656. name = os.path.basename(path)
  2657. self.fileinfo[macroname] = {'path':path,'dir':dir,'name':name}
  2658. def expand(self, line=''):
  2659. "Expand all macros found on the line"
  2660. while self.rgx.search(line):
  2661. m = self.rgx.search(line)
  2662. name = self.name = m.group('name')
  2663. fmt = m.group('fmt') or self.dft_fmt.get(name)
  2664. if name == 'date':
  2665. txt = time.strftime(fmt,self.currdate)
  2666. elif name == 'mtime':
  2667. if self.infile == STDIN:
  2668. fdate = self.currdate
  2669. else:
  2670. mtime = os.path.getmtime(self.infile)
  2671. fdate = time.localtime(mtime)
  2672. txt = time.strftime(fmt,fdate)
  2673. elif name in ['infile','outfile']:
  2674. self.set_file_info(name)
  2675. txt = self.walk_file_format(fmt)
  2676. else:
  2677. Error("Unknown macro name '%s'"%name)
  2678. line = self.rgx.sub(txt,line,1)
  2679. return line
  2680. ##############################################################################
  2681. def dumpConfig(source_raw, parsed_config):
  2682. onoff = {1:_('ON'), 0:_('OFF')}
  2683. data = [
  2684. (_('RC file') , RC_RAW ),
  2685. (_('source document'), source_raw ),
  2686. (_('command line') , CMDLINE_RAW)
  2687. ]
  2688. # first show all RAW data found
  2689. for label, cfg in data:
  2690. print _('RAW config for %s')%label
  2691. for target,key,val in cfg:
  2692. target = '(%s)'%target
  2693. key = dotted_spaces("%-14s"%key)
  2694. val = val or _('ON')
  2695. print ' %-8s %s: %s'%(target,key,val)
  2696. print
  2697. # then the parsed results of all of them
  2698. print _('Full PARSED config')
  2699. keys = parsed_config.keys() ; keys.sort() # sorted
  2700. for key in keys:
  2701. val = parsed_config[key]
  2702. # filters are the last
  2703. if key in ['preproc', 'postproc']:
  2704. continue
  2705. # flag beautifier
  2706. if key in FLAGS.keys()+ACTIONS.keys():
  2707. val = onoff.get(val) or val
  2708. # list beautifier
  2709. if type(val) == type([]):
  2710. if key == 'options': sep = ' '
  2711. else : sep = ', '
  2712. val = string.join(val, sep)
  2713. print "%25s: %s"%(dotted_spaces("%-14s"%key),val)
  2714. print
  2715. print _('Active filters')
  2716. for filter in ['preproc','postproc']:
  2717. for rule in parsed_config.get(filter) or []:
  2718. print "%25s: %s -> %s"%(
  2719. dotted_spaces("%-14s"%filter),rule[0],rule[1])
  2720. def get_file_body(file):
  2721. "Returns all the document BODY lines"
  2722. return process_source_file(file, noconf=1)[1][2]
  2723. def finish_him(outlist, config):
  2724. "Writing output to screen or file"
  2725. outfile = config['outfile']
  2726. outlist = unmaskEscapeChar(outlist)
  2727. # apply PostProc filters
  2728. if config['postproc']:
  2729. filters = compile_filters(config['postproc'],
  2730. _('Invalid PostProc filter regex'))
  2731. postoutlist = []
  2732. for line in outlist:
  2733. for rgx,repl in filters:
  2734. line = rgx.sub(repl, line)
  2735. postoutlist.append(line)
  2736. outlist = postoutlist[:]
  2737. if outfile == STDOUT:
  2738. if GUI:
  2739. return outlist, config
  2740. else:
  2741. for line in outlist: print line
  2742. else:
  2743. Savefile(outfile, addLineBreaks(outlist))
  2744. if not GUI and not QUIET:
  2745. print _('%s wrote %s')%(my_name,outfile)
  2746. if config['split']:
  2747. if not QUIET: print "--- html..."
  2748. sgml2html = 'sgml2html -s %s -l %s %s'%(
  2749. config['split'],config['lang'] or lang,outfile)
  2750. if not QUIET: print "Running system command:", sgml2html
  2751. os.system(sgml2html)
  2752. def toc_inside_body(body, toc, config):
  2753. ret = []
  2754. if AUTOTOC: return body # nothing to expand
  2755. toc_mark = MaskMaster().tocmask
  2756. # expand toc mark with TOC contents
  2757. for line in body:
  2758. if string.count(line, toc_mark): # toc mark found
  2759. if config['toc']:
  2760. ret.extend(toc) # include if --toc
  2761. else:
  2762. pass # or remove %%toc line
  2763. else:
  2764. ret.append(line) # common line
  2765. return ret
  2766. def toc_tagger(toc, config):
  2767. "Convert t2t-marked TOC (it is a list) to target-tagged TOC"
  2768. ret = []
  2769. # tag if TOC-only TOC "by hand" (target don't have a TOC tag)
  2770. if config['toc-only'] or (config['toc'] and not TAGS['TOC']):
  2771. fakeconf = config.copy()
  2772. fakeconf['headers'] = 0
  2773. fakeconf['toc-only'] = 0
  2774. fakeconf['mask-email'] = 0
  2775. fakeconf['preproc'] = []
  2776. fakeconf['postproc'] = []
  2777. fakeconf['css-sugar'] = 0
  2778. ret,foo = convert(toc, fakeconf)
  2779. set_global_config(config) # restore config
  2780. # target TOC is a tag
  2781. elif config['toc'] and TAGS['TOC']:
  2782. ret = [TAGS['TOC']]
  2783. return ret
  2784. def toc_formatter(toc, config):
  2785. "Formats TOC for automatic placement between headers and body"
  2786. if config['toc-only']: return toc # no formatting needed
  2787. if not config['toc'] : return [] # TOC disabled
  2788. ret = toc
  2789. # TOC open/close tags (if any)
  2790. if TAGS['tocOpen' ]: ret.insert(0, TAGS['tocOpen'])
  2791. if TAGS['tocClose']: ret.append(TAGS['tocClose'])
  2792. # autotoc specific formatting
  2793. if AUTOTOC:
  2794. if rules['autotocwithbars']: # TOC between bars
  2795. para = TAGS['paragraphOpen']+TAGS['paragraphClose']
  2796. bar = regex['x'].sub('-'*72,TAGS['bar1'])
  2797. tocbar = [para, bar, para]
  2798. ret = tocbar + ret + tocbar
  2799. if rules['blankendautotoc']: # blank line after TOC
  2800. ret.append('')
  2801. if rules['autotocnewpagebefore']: # page break before TOC
  2802. ret.insert(0,TAGS['pageBreak'])
  2803. if rules['autotocnewpageafter']: # page break after TOC
  2804. ret.append(TAGS['pageBreak'])
  2805. return ret
  2806. def doHeader(headers, config):
  2807. if not config['headers']: return []
  2808. if not headers: headers = ['','','']
  2809. target = config['target']
  2810. if not HEADER_TEMPLATE.has_key(target):
  2811. Error("doheader: Unknow target '%s'"%target)
  2812. if target in ['html','xhtml'] and config.get('css-sugar'):
  2813. template = string.split(HEADER_TEMPLATE[target+'css'], '\n')
  2814. else:
  2815. template = string.split(HEADER_TEMPLATE[target], '\n')
  2816. head_data = {'STYLE':'', 'ENCODING':''}
  2817. for key in head_data.keys():
  2818. val = config.get(string.lower(key))
  2819. if key == 'ENCODING': val = get_encoding_string(val, target)
  2820. head_data[key] = val
  2821. # parse header contents
  2822. for i in 0,1,2:
  2823. # expand macros
  2824. contents = MacroMaster(config=config).expand(headers[i])
  2825. # Escapes - on tex, just do it if any \tag{} present
  2826. if target != 'tex' or \
  2827. (target == 'tex' and re.search(r'\\\w+{', contents)):
  2828. contents = doEscape(target, contents)
  2829. if target == 'lout':
  2830. contents = doFinalEscape(target, contents)
  2831. head_data['HEADER%d'%(i+1)] = contents
  2832. # css-inside removes STYLE line
  2833. if target in ['html','xhtml'] and config.get('css-inside') and \
  2834. config.get('style'):
  2835. head_data['STYLE'] = ''
  2836. Debug("Header Data: %s"%head_data, 1)
  2837. # scan for empty dictionary keys
  2838. # if found, scan template lines for that key reference
  2839. # if found, remove the reference
  2840. # if there isn't any other key reference on the same line, remove it
  2841. for key in head_data.keys():
  2842. if head_data.get(key): continue
  2843. for line in template:
  2844. if string.count(line, '%%(%s)s'%key):
  2845. sline = string.replace(line, '%%(%s)s'%key, '')
  2846. if not re.search(r'%\([A-Z0-9]+\)s', sline):
  2847. template.remove(line)
  2848. # populate template with data
  2849. template = string.join(template, '\n') % head_data
  2850. # adding CSS contents into template (for --css-inside)
  2851. if target in ['html','xhtml'] and config.get('css-inside') and \
  2852. config.get('style'):
  2853. TAGS = getTags(config)
  2854. cssfile = config['style']
  2855. if not os.path.isabs(cssfile):
  2856. infile = config.get('sourcefile')
  2857. cssfile = os.path.join(os.path.dirname(infile), cssfile)
  2858. css = string.join(Readfile(cssfile, 1, 1), '\n')
  2859. css = "%s\n%s\n%s\n" % (TAGS['cssOpen'], css, TAGS['cssClose'])
  2860. template = string.replace(template, '</HEAD>', css+'</HEAD>')
  2861. return string.split(template, '\n')
  2862. def doCommentLine(txt):
  2863. # the -- string ends a (h|sg|xht)ml comment :(
  2864. txt = maskEscapeChar(txt)
  2865. if string.count(TAGS['comment'], '--') and \
  2866. string.count(txt, '--'):
  2867. txt = re.sub('-(?=-)', r'-\\', txt)
  2868. if TAGS['comment']:
  2869. return regex['x'].sub(txt, TAGS['comment'])
  2870. return ''
  2871. def doFooter(config):
  2872. if not config['headers']: return []
  2873. ret = []
  2874. target = config['target']
  2875. cmdline = config['realcmdline']
  2876. typename = target
  2877. if target == 'tex': typename = 'LaTeX2e'
  2878. ppgd = '%s code generated by %s %s (%s)'%(
  2879. typename,my_name,my_version,my_url)
  2880. cmdline = 'cmdline: %s %s'%(my_name, string.join(cmdline, ' '))
  2881. ret.append('\n'+doCommentLine(ppgd))
  2882. ret.append(doCommentLine(cmdline))
  2883. ret.append(TAGS['EOD'])
  2884. return ret
  2885. def doEscape(target,txt):
  2886. "Target-specific special escapes. Apply *before* insert any tag."
  2887. tmpmask = 'vvvvThisEscapingSuxvvvv'
  2888. if target in ['html','sgml','xhtml']:
  2889. txt = re.sub('&','&amp;',txt)
  2890. txt = re.sub('<','&lt;',txt)
  2891. txt = re.sub('>','&gt;',txt)
  2892. if target == 'sgml':
  2893. txt = re.sub('\xff','&yuml;',txt) # "+y
  2894. elif target == 'pm6':
  2895. txt = re.sub('<','<\#60>',txt)
  2896. elif target == 'mgp':
  2897. txt = re.sub('^%',' %',txt) # add leading blank to avoid parse
  2898. elif target == 'man':
  2899. txt = re.sub("^([.'])", '\\&\\1',txt) # command ID
  2900. txt = string.replace(txt,ESCCHAR, ESCCHAR+'e') # \e
  2901. elif target == 'lout':
  2902. # TIP: / moved to FinalEscape to avoid //italic//
  2903. # TIP: these are also converted by lout: ... --- --
  2904. txt = string.replace(txt, ESCCHAR, tmpmask) # \
  2905. txt = string.replace(txt, '"', '"%s""'%ESCCHAR) # "\""
  2906. txt = re.sub('([|&{}@#^~])', '"\\1"',txt) # "@"
  2907. txt = string.replace(txt, tmpmask, '"%s"'%(ESCCHAR*2)) # "\\"
  2908. elif target == 'tex':
  2909. # mark literal \ to be changed to $\backslash$ later
  2910. txt = string.replace( txt, ESCCHAR, tmpmask)
  2911. txt = re.sub('([#$&%{}])', ESCCHAR+r'\1' , txt) # \%
  2912. txt = re.sub('([~^])' , ESCCHAR+r'\1{}', txt) # \~{}
  2913. txt = re.sub('([<|>])' , r'$\1$', txt) # $>$
  2914. txt = string.replace(txt, tmpmask,
  2915. maskEscapeChar(r'$\backslash$'))
  2916. # TIP the _ is escaped at the end
  2917. return txt
  2918. # TODO man: where - really needs to be escaped?
  2919. def doFinalEscape(target, txt):
  2920. "Last escapes of each line"
  2921. if target == 'pm6' : txt = string.replace(txt,ESCCHAR+'<',r'<\#92><')
  2922. elif target == 'man' : txt = string.replace(txt, '-', r'\-')
  2923. elif target == 'sgml': txt = string.replace(txt, '[', '&lsqb;')
  2924. elif target == 'lout': txt = string.replace(txt, '/', '"/"')
  2925. elif target == 'tex' :
  2926. txt = string.replace(txt, '_', r'\_')
  2927. txt = string.replace(txt, 'vvvvTexUndervvvv', '_') # shame!
  2928. return txt
  2929. def EscapeCharHandler(action, data):
  2930. "Mask/Unmask the Escape Char on the given string"
  2931. if not string.strip(data): return data
  2932. if action not in ['mask','unmask']:
  2933. Error("EscapeCharHandler: Invalid action '%s'"%action)
  2934. if action == 'mask': return string.replace(data,'\\',ESCCHAR)
  2935. else: return string.replace(data,ESCCHAR,'\\')
  2936. def maskEscapeChar(data):
  2937. "Replace any Escape Char \ with a text mask (Input: str or list)"
  2938. if type(data) == type([]):
  2939. return map(lambda x: EscapeCharHandler('mask', x), data)
  2940. return EscapeCharHandler('mask',data)
  2941. def unmaskEscapeChar(data):
  2942. "Undo the Escape char \ masking (Input: str or list)"
  2943. if type(data) == type([]):
  2944. return map(lambda x: EscapeCharHandler('unmask', x), data)
  2945. return EscapeCharHandler('unmask',data)
  2946. def addLineBreaks(list):
  2947. "use LB to respect sys.platform"
  2948. ret = []
  2949. for line in list:
  2950. line = string.replace(line,'\n',LB) # embedded \n's
  2951. ret.append(line+LB) # add final line break
  2952. return ret
  2953. def compile_filters(filters, errmsg='Filter'):
  2954. if filters:
  2955. for i in range(len(filters)):
  2956. patt,repl = filters[i]
  2957. try: rgx = re.compile(patt)
  2958. except: Error("%s: '%s'"%(errmsg, patt))
  2959. filters[i] = (rgx,repl)
  2960. return filters
  2961. def enclose_me(tagname, txt):
  2962. return TAGS.get(tagname+'Open') + txt + TAGS.get(tagname+'Close')
  2963. def beautify_me(name, line):
  2964. "where name is: bold, italic or underline"
  2965. name = 'font%s' % string.capitalize(name)
  2966. open = TAGS['%sOpen'%name]
  2967. close = TAGS['%sClose'%name]
  2968. txt = r'%s\1%s'%(open, close)
  2969. line = regex[name].sub(txt,line)
  2970. return line
  2971. def get_tagged_link(label, url):
  2972. ret = ''
  2973. target = CONF['target']
  2974. image_re = regex['img']
  2975. # set link type
  2976. if regex['email'].match(url):
  2977. linktype = 'email'
  2978. else:
  2979. linktype = 'url';
  2980. # escape specials from TEXT parts
  2981. label = doEscape(target,label)
  2982. # escape specials from link URL
  2983. if rules['linkable'] and rules['escapeurl']:
  2984. url = doEscape(target, url)
  2985. # if not linkable, the URL is plain text, that needs escape
  2986. if not rules['linkable']:
  2987. if target == 'tex':
  2988. url = re.sub('^#', '\#', url) # ugly, but compile
  2989. else:
  2990. url = doEscape(target,url)
  2991. # adding protocol to guessed link
  2992. guessurl = ''
  2993. if linktype == 'url' and \
  2994. re.match(regex['_urlskel']['guess'], url):
  2995. if url[0] == 'w': guessurl = 'http://' +url
  2996. else : guessurl = 'ftp://' +url
  2997. # not link aware targets -> protocol is useless
  2998. if not rules['linkable']: guessurl = ''
  2999. # simple link (not guessed)
  3000. if not label and not guessurl:
  3001. if CONF['mask-email'] and linktype == 'email':
  3002. # do the email mask feature (no TAGs, just text)
  3003. url = string.replace(url,'@',' (a) ')
  3004. url = string.replace(url,'.',' ')
  3005. url = "<%s>" % url
  3006. if rules['linkable']: url = doEscape(target, url)
  3007. ret = url
  3008. else:
  3009. # just add link data to tag
  3010. tag = TAGS[linktype]
  3011. ret = regex['x'].sub(url,tag)
  3012. # named link or guessed simple link
  3013. else:
  3014. # adjusts for guessed link
  3015. if not label: label = url # no protocol
  3016. if guessurl : url = guessurl # with protocol
  3017. # image inside link!
  3018. if image_re.match(label):
  3019. if rules['imglinkable']: # get image tag
  3020. label = parse_images(label)
  3021. else: # img@link !supported
  3022. label = "(%s)"%image_re.match(label).group(1)
  3023. # putting data on the right appearance order
  3024. if rules['linkable']:
  3025. urlorder = [url, label] # link before label
  3026. else:
  3027. urlorder = [label, url] # label before link
  3028. # add link data to tag (replace \a's)
  3029. ret = TAGS["%sMark"%linktype]
  3030. for data in urlorder:
  3031. ret = regex['x'].sub(data,ret,1)
  3032. return ret
  3033. def parse_deflist_term(line):
  3034. "Extract and parse definition list term contents"
  3035. img_re = regex['img']
  3036. term = regex['deflist'].search(line).group(3)
  3037. # mask image inside term as (image.jpg), where not supported
  3038. if not rules['imgasdefterm'] and img_re.search(term):
  3039. while img_re.search(term):
  3040. imgfile = img_re.search(term).group(1)
  3041. term = img_re.sub('(%s)'%imgfile, term, 1)
  3042. #TODO tex: escape ] on term. \], \rbrack{} and \verb!]! don't work :(
  3043. return term
  3044. def get_tagged_bar(line):
  3045. m = regex['bar'].search(line)
  3046. if not m: return line
  3047. txt = m.group(2)
  3048. # map strong bar to pagebreak
  3049. if rules['mapbar2pagebreak'] and TAGS['pageBreak']:
  3050. TAGS['bar2'] = TAGS['pageBreak']
  3051. # set bar type
  3052. if txt[0] == '=': bar = TAGS['bar2']
  3053. else : bar = TAGS['bar1']
  3054. # to avoid comment tag confusion like <!-- ------ -->
  3055. if string.count(TAGS['comment'], '--'):
  3056. txt = string.replace(txt,'--','__')
  3057. # tag line
  3058. return regex['x'].sub(txt, bar)
  3059. def get_image_align(line):
  3060. "Return the image (first found) align for the given line"
  3061. # first clear marks that can mess align detection
  3062. line = re.sub(SEPARATOR+'$', '', line) # remove deflist sep
  3063. line = re.sub('^'+SEPARATOR, '', line) # remove list sep
  3064. line = re.sub('^[\t]+' , '', line) # remove quote mark
  3065. # get image position on the line
  3066. m = regex['img'].search(line)
  3067. ini = m.start() ; head = 0
  3068. end = m.end() ; tail = len(line)
  3069. # the align detection algorithm
  3070. if ini == head and end != tail: align = 'left' # ^img + text$
  3071. elif ini != head and end == tail: align = 'right' # ^text + img$
  3072. else : align = 'center' # default align
  3073. # some special cases
  3074. if BLOCK.isblock('table'): align = 'center' # ignore when table
  3075. # if TARGET == 'mgp' and align == 'center': align = 'center'
  3076. return align
  3077. # reference: http://www.iana.org/assignments/character-sets
  3078. # http://www.drclue.net/F1.cgi/HTML/META/META.html
  3079. def get_encoding_string(enc, target):
  3080. if not enc: return ''
  3081. # target specific translation table
  3082. translate = {
  3083. 'tex': {
  3084. # missing: ansinew , applemac , cp437 , cp437de , cp865
  3085. 'us-ascii' : 'ascii',
  3086. 'windows-1250': 'cp1250',
  3087. 'windows-1252': 'cp1252',
  3088. 'ibm850' : 'cp850',
  3089. 'ibm852' : 'cp852',
  3090. 'iso-8859-1' : 'latin1',
  3091. 'iso-8859-2' : 'latin2',
  3092. 'iso-8859-3' : 'latin3',
  3093. 'iso-8859-4' : 'latin4',
  3094. 'iso-8859-5' : 'latin5',
  3095. 'iso-8859-9' : 'latin9',
  3096. 'koi8-r' : 'koi8-r'
  3097. }
  3098. }
  3099. # normalization
  3100. enc = re.sub('(?i)(us[-_]?)?ascii|us|ibm367','us-ascii' , enc)
  3101. enc = re.sub('(?i)(ibm|cp)?85([02])' ,'ibm85\\2' , enc)
  3102. enc = re.sub('(?i)(iso[_-]?)?8859[_-]?' ,'iso-8859-' , enc)
  3103. enc = re.sub('iso-8859-($|[^1-9]).*' ,'iso-8859-1', enc)
  3104. # apply translation table
  3105. try: enc = translate[target][string.lower(enc)]
  3106. except: pass
  3107. return enc
  3108. ##############################################################################
  3109. ##MerryChristmas,IdontwanttofighttonightwithyouImissyourbodyandIneedyourlove##
  3110. ##############################################################################
  3111. def process_source_file(file='', noconf=0, contents=[]):
  3112. """
  3113. Find and Join all the configuration available for a source file.
  3114. No sanity checkings are done on this step.
  3115. It also extracts the source document parts into separate holders.
  3116. The config scan order is:
  3117. 1. The user configuration file (i.e. $HOME/.txt2tagsrc)
  3118. 2. The source document's CONF area
  3119. 3. The command line options
  3120. The return data is a tuple of two items:
  3121. 1. The parsed config dictionary
  3122. 2. The document's parts, as a (head, conf, body) tuple
  3123. All the conversion process will be based on the data and
  3124. configuration returned by this function.
  3125. The source files is readed on this step only.
  3126. """
  3127. if contents:
  3128. source = SourceDocument(contents=contents)
  3129. else:
  3130. source = SourceDocument(file)
  3131. head, conf, body = source.split()
  3132. Message(_("Source document contents stored"),2)
  3133. if not noconf:
  3134. # read document config
  3135. source_raw = source.get_raw_config()
  3136. # join all the config directives found, then parse it
  3137. full_raw = RC_RAW + source_raw + CMDLINE_RAW
  3138. Message(_("Parsing and saving all config found (%03d items)")%(
  3139. len(full_raw)),1)
  3140. full_parsed = ConfigMaster(full_raw).parse()
  3141. # add manually the filemane to the conf dic
  3142. if contents:
  3143. full_parsed['sourcefile'] = '-module-'
  3144. full_parsed['infile'] = '-module-'
  3145. else:
  3146. full_parsed['sourcefile'] = file
  3147. # maybe should we dump the config found?
  3148. if full_parsed.get('dump-config'):
  3149. dumpConfig(source_raw, full_parsed)
  3150. Quit()
  3151. # okay, all done
  3152. Debug("FULL config for this file: %s"%full_parsed, 1)
  3153. else:
  3154. full_parsed = {}
  3155. return full_parsed, (head,conf,body)
  3156. def get_infiles_config(infiles):
  3157. """
  3158. Find and Join into a single list, all configuration available
  3159. for each input file. This function is supposed to be the very
  3160. first one to be called, before any processing.
  3161. """
  3162. ret = []
  3163. if not infiles: return []
  3164. for infile in infiles:
  3165. ret.append((process_source_file(infile)))
  3166. return ret
  3167. def convert_this_files(configs, dump_results=0):
  3168. global CONF
  3169. for myconf,doc in configs: # multifile support
  3170. target_head = []
  3171. target_toc = []
  3172. target_body = []
  3173. target_foot = []
  3174. source_head, source_conf, source_body = doc
  3175. myconf = ConfigMaster().sanity(myconf)
  3176. # compose the target file Headers
  3177. #TODO escape line before?
  3178. #TODO see exceptions by tex and mgp
  3179. Message(_("Composing target Headers"),1)
  3180. target_head = doHeader(source_head, myconf)
  3181. # parse the full marked body into tagged target
  3182. first_body_line = (len(source_head) or 1)+ len(source_conf) + 1
  3183. Message(_("Composing target Body"),1)
  3184. target_body, marked_toc = convert(source_body, myconf,
  3185. firstlinenr=first_body_line)
  3186. # make TOC (if needed)
  3187. Message(_("Composing target TOC"),1)
  3188. tagged_toc = toc_tagger(marked_toc, myconf)
  3189. target_toc = toc_formatter(tagged_toc, myconf)
  3190. target_body = toc_inside_body(target_body, target_toc, myconf)
  3191. if not AUTOTOC and not myconf['toc-only']: target_toc = []
  3192. # compose the target file Footer
  3193. Message(_("Composing target Footer"),1)
  3194. target_foot = doFooter(myconf)
  3195. # finally, we have our document
  3196. outlist = target_head + target_toc + target_body + target_foot
  3197. # if on GUI, abort before finish_him
  3198. # else, write results to file or STDOUT
  3199. if GUI or dump_results:
  3200. return outlist, myconf
  3201. else:
  3202. Message(_("Saving results to the output file"),1)
  3203. finish_him(outlist, myconf)
  3204. def parse_images(line):
  3205. "Tag all images found"
  3206. while regex['img'].search(line) and TAGS['img'] != '[\a]':
  3207. txt = regex['img'].search(line).group(1)
  3208. tag = TAGS['img']
  3209. # HTML, XHTML and mgp!
  3210. if rules['imgalignable']:
  3211. align = get_image_align(line)
  3212. # add align on tag
  3213. align_name = string.capitalize(align)
  3214. align_tag = TAGS['imgAlign'+align_name]
  3215. tag = regex['_imgAlign'].sub(align_tag, tag, 1)
  3216. # dirty fix to allow centered solo images
  3217. if align == 'center' and TARGET in ['html','xhtml']:
  3218. rest = regex['img'].sub('',line,1)
  3219. if re.match('^\s+$', rest):
  3220. tag = "<center>%s</center>" %tag
  3221. if TARGET == 'tex':
  3222. tag = re.sub(r'\\b',r'\\\\b',tag)
  3223. txt = string.replace(txt, '_', 'vvvvTexUndervvvv')
  3224. line = regex['img'].sub(tag,line,1)
  3225. line = regex['x'].sub(txt,line,1)
  3226. return line
  3227. def add_inline_tags(line):
  3228. # beautifiers
  3229. for beauti in ['Bold', 'Italic', 'Underline']:
  3230. if regex['font%s'%beauti].search(line):
  3231. line = beautify_me(beauti, line)
  3232. line = parse_images(line)
  3233. return line
  3234. def get_include_contents(file, path=''):
  3235. "Parses %!include: value and extract file contents"
  3236. ids = {'`':'verb', '"':'raw', "'":'passthru' }
  3237. id = 't2t'
  3238. # set include type and remove identifier marks
  3239. mark = file[0]
  3240. if mark in ids.keys():
  3241. if file[:2] == file[-2:] == mark*2:
  3242. id = ids[mark] # set type
  3243. file = file[2:-2] # remove marks
  3244. # handle remote dir execution
  3245. filepath = os.path.join(path, file)
  3246. # read included file contents
  3247. lines = Readfile(filepath, remove_linebreaks=1)
  3248. # default txt2tags marked text, just BODY matters
  3249. if id == 't2t':
  3250. lines = get_file_body(filepath)
  3251. lines.insert(0, '%%INCLUDED(%s) starts here: %s'%(id,file))
  3252. lines.append('%%INCLUDED(%s) ends here: %s'%(id,file))
  3253. return id, lines
  3254. def set_global_config(config):
  3255. global CONF, TAGS, regex, rules, TARGET
  3256. CONF = config
  3257. TAGS = getTags(CONF)
  3258. rules = getRules(CONF)
  3259. regex = getRegexes()
  3260. TARGET = config['target'] # save for buggy functions that need global
  3261. def convert(bodylines, config, firstlinenr=1):
  3262. global BLOCK
  3263. set_global_config(config)
  3264. target = config['target']
  3265. BLOCK = BlockMaster()
  3266. MASK = MaskMaster()
  3267. TITLE = TitleMaster()
  3268. ret = []
  3269. f_lastwasblank = 0
  3270. # compiling all PreProc regexes
  3271. pre_filter = compile_filters(
  3272. CONF['preproc'], _('Invalid PreProc filter regex'))
  3273. # let's mark it up!
  3274. linenr = firstlinenr-1
  3275. lineref = 0
  3276. while lineref < len(bodylines):
  3277. # defaults
  3278. MASK.reset()
  3279. results_box = ''
  3280. untouchedline = bodylines[lineref]
  3281. line = re.sub('[\n\r]+$','',untouchedline) # del line break
  3282. # apply PreProc filters
  3283. if pre_filter:
  3284. for rgx,repl in pre_filter:
  3285. line = rgx.sub(repl, line)
  3286. line = maskEscapeChar(line) # protect \ char
  3287. linenr = linenr +1
  3288. lineref = lineref +1
  3289. Debug(repr(line), 2, linenr) # heavy debug: show each line
  3290. # any NOT table line (or comment), closes an open table
  3291. if ( BLOCK.isblock('table') or
  3292. ( BLOCK.isblock('verb') and
  3293. BLOCK.prop('mapped') == 'table'
  3294. )
  3295. ) \
  3296. and not regex['table'].search(line) \
  3297. and not regex['comment'].search(line):
  3298. ret.extend(BLOCK.blockout())
  3299. # any NOT quote line (or comment) closes all open quotes
  3300. if BLOCK.isblock('quote') \
  3301. and not regex['quote'].search(line) \
  3302. and not regex['comment'].search(line):
  3303. while BLOCK.isblock('quote'):
  3304. ret.extend(BLOCK.blockout())
  3305. #-------------------------[ Raw Text ]----------------------
  3306. # we're already on a raw block
  3307. if BLOCK.block() == 'raw':
  3308. # closing raw
  3309. if regex['blockRawClose'].search(line):
  3310. ret.extend(BLOCK.blockout())
  3311. continue
  3312. # normal raw-inside line
  3313. BLOCK.holdadd(line)
  3314. continue
  3315. # detecting raw block init
  3316. if regex['blockRawOpen'].search(line):
  3317. ret.extend(BLOCK.blockin('raw'))
  3318. continue
  3319. # one line verb-formatted text
  3320. if regex['1lineRaw'].search(line):
  3321. ret.extend(BLOCK.blockin('raw'))
  3322. line = regex['1lineRaw'].sub('',line)
  3323. BLOCK.holdadd(line)
  3324. ret.extend(BLOCK.blockout())
  3325. continue
  3326. #-----------------[ Verbatim (PRE-formatted) ]--------------
  3327. #TIP we'll never support beautifiers inside verbatim
  3328. # we're already on a verb block
  3329. if BLOCK.block() == 'verb':
  3330. # closing verb
  3331. if regex['blockVerbClose'].search(line):
  3332. ret.extend(BLOCK.blockout())
  3333. continue
  3334. # normal verb-inside line
  3335. BLOCK.holdadd(line)
  3336. continue
  3337. # detecting verb block init
  3338. if regex['blockVerbOpen'].search(line):
  3339. ret.extend(BLOCK.blockin('verb'))
  3340. f_lastwasblank = 0
  3341. continue
  3342. # one line verb-formatted text
  3343. if regex['1lineVerb'].search(line):
  3344. ret.extend(BLOCK.blockin('verb'))
  3345. line = regex['1lineVerb'].sub('',line)
  3346. BLOCK.holdadd(line)
  3347. ret.extend(BLOCK.blockout())
  3348. f_lastwasblank = 0
  3349. continue
  3350. # tables are mapped to verb when target is not table-aware
  3351. if not rules['tableable'] and regex['table'].search(line):
  3352. if not BLOCK.isblock('verb'):
  3353. ret.extend(BLOCK.blockin('verb'))
  3354. BLOCK.propset('mapped', 'table')
  3355. BLOCK.holdadd(line)
  3356. continue
  3357. #---------------------[ blank lines ]-----------------------
  3358. if regex['blankline'].search(line):
  3359. # close open paragraph
  3360. if BLOCK.isblock('para'):
  3361. ret.extend(BLOCK.blockout())
  3362. f_lastwasblank = 1
  3363. continue
  3364. # close all open quotes
  3365. while BLOCK.isblock('quote'):
  3366. ret.extend(BLOCK.blockout())
  3367. # closing all open lists
  3368. if f_lastwasblank: # 2nd consecutive blank
  3369. if BLOCK.block()[-4:] == 'list':
  3370. BLOCK.holdaddsub('') # helps parser
  3371. while BLOCK.depth: # closes list (if any)
  3372. ret.extend(BLOCK.blockout())
  3373. continue # ignore consecutive blanks
  3374. # paragraph (if any) is wanted inside lists also
  3375. if BLOCK.block()[-4:] == 'list':
  3376. BLOCK.holdaddsub('')
  3377. else:
  3378. # html: show blank line (needs tag)
  3379. if target in ['html','xhtml']:
  3380. ret.append(TAGS['paragraphOpen']+\
  3381. TAGS['paragraphClose'])
  3382. # otherwise we just show a blank line
  3383. else:
  3384. ret.append('')
  3385. f_lastwasblank = 1
  3386. continue
  3387. #---------------------[ special ]---------------------------
  3388. if regex['special'].search(line):
  3389. # include command
  3390. targ, key, val = ConfigLines().parse_line(
  3391. line, 'include', target)
  3392. if key:
  3393. Debug("Found config '%s', value '%s'"%(
  3394. key,val),1,linenr)
  3395. incpath = os.path.dirname(CONF['sourcefile'])
  3396. incfile = val
  3397. err = _('A file cannot include itself (loop!)')
  3398. if CONF['sourcefile'] == incfile:
  3399. Error("%s: %s"%(err,incfile))
  3400. inctype, inclines = get_include_contents(
  3401. incfile, incpath)
  3402. # verb, raw and passthru are easy
  3403. if inctype != 't2t':
  3404. ret.extend(BLOCK.blockin(inctype))
  3405. BLOCK.holdextend(inclines)
  3406. ret.extend(BLOCK.blockout())
  3407. else:
  3408. # insert include lines into body
  3409. #TODO del %!include command call
  3410. #TODO include maxdepth limit
  3411. bodylines = bodylines[:lineref] \
  3412. +inclines \
  3413. +bodylines[lineref:]
  3414. continue
  3415. else:
  3416. Debug('Bogus Special Line',1,linenr)
  3417. #---------------------[ comments ]--------------------------
  3418. # just skip them (if not macro)
  3419. if regex['comment'].search(line) and not \
  3420. regex['macros'].match(line) and not \
  3421. regex['toc'].match(line):
  3422. continue
  3423. # valid line, reset blank status
  3424. f_lastwasblank = 0
  3425. #---------------------[ Horizontal Bar ]--------------------
  3426. if regex['bar'].search(line):
  3427. # a bar closes a paragraph
  3428. if BLOCK.isblock('para'):
  3429. ret.extend(BLOCK.blockout())
  3430. # we need to close all opened quote blocks
  3431. # if bar isn't allowed inside or if not a quote line
  3432. if BLOCK.isblock('quote'):
  3433. if not rules['barinsidequote'] or \
  3434. not regex['quote'].search(line):
  3435. while BLOCK.isblock('quote'):
  3436. ret.extend(BLOCK.blockout())
  3437. # quote + bar: continue processing for quoting
  3438. if rules['barinsidequote'] and \
  3439. regex['quote'].search(line):
  3440. pass
  3441. # just bar: save tagged line and we're done
  3442. else:
  3443. line = get_tagged_bar(line)
  3444. if BLOCK.block()[-4:] == 'list':
  3445. BLOCK.holdaddsub(line)
  3446. elif BLOCK.block():
  3447. BLOCK.holdadd(line)
  3448. else:
  3449. ret.append(line)
  3450. Debug("BAR: %s"%line, 6)
  3451. continue
  3452. #---------------------[ Title ]-----------------------------
  3453. #TODO set next blank and set f_lastwasblank or f_lasttitle
  3454. if (regex['title'].search(line) or
  3455. regex['numtitle'].search(line)) and \
  3456. BLOCK.block()[-4:] != 'list':
  3457. # a title closes a paragraph
  3458. if BLOCK.isblock('para'):
  3459. ret.extend(BLOCK.blockout())
  3460. TITLE.add(line)
  3461. tagged_title = TITLE.get()
  3462. ret.extend(tagged_title)
  3463. Debug("TITLE: %s"%tagged_title, 6)
  3464. f_lastwasblank = 1
  3465. continue
  3466. #---------------------[ %%toc ]-----------------------
  3467. # %%toc line closes paragraph
  3468. if BLOCK.block() == 'para' and regex['toc'].search(line):
  3469. ret.extend(BLOCK.blockout())
  3470. #---------------------[ apply masks ]-----------------------
  3471. line = MASK.mask(line)
  3472. #XXX from here, only block-inside lines will pass
  3473. #---------------------[ Quote ]-----------------------------
  3474. if regex['quote'].search(line):
  3475. # store number of leading TABS
  3476. quotedepth = len(regex['quote'].search(line).group(0))
  3477. # SGML doesn't support nested quotes
  3478. if rules['quotenotnested']: quotedepth = 1
  3479. # new quote
  3480. if not BLOCK.isblock('quote'):
  3481. ret.extend(BLOCK.blockin('quote'))
  3482. # new subquotes
  3483. while BLOCK.depth < quotedepth:
  3484. BLOCK.blockin('quote')
  3485. # closing quotes
  3486. while quotedepth < BLOCK.depth:
  3487. ret.extend(BLOCK.blockout())
  3488. #---------------------[ Lists ]-----------------------------
  3489. # an empty item also closes the current list
  3490. if BLOCK.block()[-4:] == 'list':
  3491. m = regex['listclose'].match(line)
  3492. if m:
  3493. listindent = m.group(1)
  3494. listtype = m.group(2)
  3495. currlisttype = BLOCK.prop('type')
  3496. currlistindent = BLOCK.prop('indent')
  3497. if listindent == currlistindent and \
  3498. listtype == currlisttype:
  3499. ret.extend(BLOCK.blockout())
  3500. continue
  3501. if regex['list'].search(line) or \
  3502. regex['numlist'].search(line) or \
  3503. regex['deflist'].search(line):
  3504. listindent = BLOCK.prop('indent')
  3505. listids = string.join(LISTNAMES.keys(), '')
  3506. m = re.match('^( *)([%s]) '%listids, line)
  3507. listitemindent = m.group(1)
  3508. listtype = m.group(2)
  3509. listname = LISTNAMES[listtype]
  3510. results_box = BLOCK.holdadd
  3511. # del list ID (and separate term from definition)
  3512. if listname == 'deflist':
  3513. term = parse_deflist_term(line)
  3514. line = regex['deflist'].sub(term+SEPARATOR,line)
  3515. else:
  3516. line = regex[listname].sub(SEPARATOR,line)
  3517. # don't cross depth limit
  3518. maxdepth = rules['listmaxdepth']
  3519. if maxdepth and BLOCK.depth == maxdepth:
  3520. if len(listitemindent) > len(listindent):
  3521. listitemindent = listindent
  3522. # open mother list or sublist
  3523. if BLOCK.block()[-4:] != 'list' or \
  3524. len(listitemindent) > len(listindent):
  3525. ret.extend(BLOCK.blockin(listname))
  3526. BLOCK.propset('indent',listitemindent)
  3527. BLOCK.propset('type',listtype)
  3528. # closing sublists
  3529. while len(listitemindent) < len(BLOCK.prop('indent')):
  3530. ret.extend(BLOCK.blockout())
  3531. # o-oh, sublist before list ("\n\n - foo\n- foo")
  3532. # fix: close sublist (as mother), open another list
  3533. if BLOCK.block()[-4:] != 'list':
  3534. ret.extend(BLOCK.blockin(listname))
  3535. BLOCK.propset('indent',listitemindent)
  3536. BLOCK.propset('type',listtype)
  3537. #---------------------[ Table ]-----------------------------
  3538. #TODO escape undesired format inside table
  3539. #TODO add pm6 target
  3540. if regex['table'].search(line):
  3541. if not BLOCK.isblock('table'): # first table line!
  3542. ret.extend(BLOCK.blockin('table'))
  3543. BLOCK.tableparser.__init__(line)
  3544. tablerow = TableMaster().parse_row(line)
  3545. BLOCK.tableparser.add_row(tablerow) # save config
  3546. # maintain line to unmask and inlines
  3547. line = string.join(tablerow['cells'], SEPARATOR)
  3548. #---------------------[ Paragraph ]-------------------------
  3549. if not BLOCK.block() and \
  3550. not string.count(line, MASK.tocmask): # new para!
  3551. ret.extend(BLOCK.blockin('para'))
  3552. ############################################################
  3553. ############################################################
  3554. ############################################################
  3555. #---------------------[ Final Parses ]----------------------
  3556. # the target-specific special char escapes for body lines
  3557. line = doEscape(target,line)
  3558. line = add_inline_tags(line)
  3559. line = MASK.undo(line)
  3560. #---------------------[ Hold or Return? ]-------------------
  3561. ### now we must choose here to put the parsed line
  3562. #
  3563. if not results_box:
  3564. # list item extra lines
  3565. if BLOCK.block()[-4:] == 'list':
  3566. results_box = BLOCK.holdaddsub
  3567. # other blocks
  3568. elif BLOCK.block():
  3569. results_box = BLOCK.holdadd
  3570. # no blocks
  3571. else:
  3572. line = doFinalEscape(target, line)
  3573. results_box = ret.append
  3574. results_box(line)
  3575. # EOF: close any open para/verb/lists/table/quotes
  3576. Debug('EOF',7)
  3577. while BLOCK.block():
  3578. ret.extend(BLOCK.blockout())
  3579. # maybe close some opened title area?
  3580. if rules['titleblocks']:
  3581. ret.extend(TITLE.close_all())
  3582. # maybe a major tag to enclose body? (like DIV for CSS)
  3583. if TAGS['bodyOpen' ]: ret.insert(0, TAGS['bodyOpen'])
  3584. if TAGS['bodyClose']: ret.append(TAGS['bodyClose'])
  3585. if CONF['toc-only']: ret = []
  3586. marked_toc = TITLE.dump_marked_toc(CONF['toc-level'])
  3587. return ret, marked_toc
  3588. ##############################################################################
  3589. ################################### GUI ######################################
  3590. ##############################################################################
  3591. #
  3592. # tk help: http://python.org/topics/tkinter/
  3593. # tuto: http://ibiblio.org/obp/py4fun/gui/tkPhone.html
  3594. # /usr/lib/python*/lib-tk/Tkinter.py
  3595. #
  3596. # grid table : row=0, column=0, columnspan=2, rowspan=2
  3597. # grid align : sticky='n,s,e,w' (North, South, East, West)
  3598. # pack place : side='top,bottom,right,left'
  3599. # pack fill : fill='x,y,both,none', expand=1
  3600. # pack align : anchor='n,s,e,w' (North, South, East, West)
  3601. # padding : padx=10, pady=10, ipadx=10, ipady=10 (internal)
  3602. # checkbox : offvalue is return if the _user_ deselected the box
  3603. # label align: justify=left,right,center
  3604. def load_GUI_resources():
  3605. "Load all extra modules and methods used by GUI"
  3606. global askopenfilename, showinfo, showwarning, showerror, Tkinter
  3607. from tkFileDialog import askopenfilename
  3608. from tkMessageBox import showinfo,showwarning,showerror
  3609. import Tkinter
  3610. class Gui:
  3611. "Graphical Tk Interface"
  3612. def __init__(self, conf={}):
  3613. self.root = Tkinter.Tk() # mother window, come to butthead
  3614. self.root.title(my_name) # window title bar text
  3615. self.window = self.root # variable "focus" for inclusion
  3616. self.row = 0 # row count for grid()
  3617. self.action_lenght = 150 # left column lenght (pixel)
  3618. self.frame_margin = 10 # frame margin size (pixel)
  3619. self.frame_border = 6 # frame border size (pixel)
  3620. # the default Gui colors, can be changed by %!guicolors
  3621. self.dft_gui_colors = ['blue','white','lightblue','black']
  3622. self.gui_colors = []
  3623. self.bg1 = self.fg1 = self.bg2 = self.fg2 = ''
  3624. # on Tk, vars need to be set/get using setvar()/get()
  3625. self.infile = self.setvar('')
  3626. self.target = self.setvar('')
  3627. self.target_name = self.setvar('')
  3628. # the checks appearance order
  3629. self.checks = [
  3630. 'headers','enum-title','toc','mask-email',
  3631. 'toc-only','stdout']
  3632. # creating variables for all checks
  3633. for check in self.checks:
  3634. setattr(self, 'f_'+check, self.setvar(''))
  3635. # load RC config
  3636. self.conf = {}
  3637. if conf: self.load_config(conf)
  3638. def load_config(self, conf):
  3639. self.conf = conf
  3640. self.gui_colors = conf.get('guicolors') or self.dft_gui_colors
  3641. self.bg1, self.fg1, self.bg2, self.fg2 = self.gui_colors
  3642. self.root.config(bd=15,bg=self.bg1)
  3643. ### config as dic for python 1.5 compat (**opts don't work :( )
  3644. def entry(self, **opts): return Tkinter.Entry(self.window, opts)
  3645. def label(self, txt='', bg=None, **opts):
  3646. opts.update({'text':txt,'bg':bg or self.bg1})
  3647. return Tkinter.Label(self.window, opts)
  3648. def button(self,name,cmd,**opts):
  3649. opts.update({'text':name,'command':cmd})
  3650. return Tkinter.Button(self.window, opts)
  3651. def check(self,name,checked=0,**opts):
  3652. bg, fg = self.bg2, self.fg2
  3653. opts.update({
  3654. 'text':name, 'onvalue':1, 'offvalue':0,
  3655. 'activeforeground':fg, 'fg':fg,
  3656. 'activebackground':bg, 'bg':bg,
  3657. 'highlightbackground':bg, 'anchor':'w'
  3658. })
  3659. chk = Tkinter.Checkbutton(self.window, opts)
  3660. if checked: chk.select()
  3661. chk.grid(columnspan=2, sticky='w', padx=0)
  3662. def menu(self,sel,items):
  3663. return apply(Tkinter.OptionMenu,(self.window,sel)+tuple(items))
  3664. # handy auxiliar functions
  3665. def action(self, txt):
  3666. self.label(txt, fg=self.fg1, bg=self.bg1,
  3667. wraplength=self.action_lenght).grid(column=0,row=self.row)
  3668. def frame_open(self):
  3669. self.window = Tkinter.Frame(self.root,bg=self.bg2,
  3670. borderwidth=self.frame_border)
  3671. def frame_close(self):
  3672. self.window.grid(column=1, row=self.row, sticky='w',
  3673. padx=self.frame_margin)
  3674. self.window = self.root
  3675. self.label('').grid()
  3676. self.row = self.row + 2 # update row count
  3677. def target_name2key(self):
  3678. name = self.target_name.get()
  3679. target = filter(lambda x: TARGET_NAMES[x] == name, TARGETS)
  3680. try : key = target[0]
  3681. except: key = ''
  3682. self.target = self.setvar(key)
  3683. def target_key2name(self):
  3684. key = self.target.get()
  3685. name = TARGET_NAMES.get(key) or key
  3686. self.target_name = self.setvar(name)
  3687. def exit(self): self.root.destroy()
  3688. def setvar(self, val): z = Tkinter.StringVar() ; z.set(val) ; return z
  3689. def askfile(self):
  3690. ftypes= [(_('txt2tags files'),('*.t2t','*.txt')),
  3691. (_('All files'),'*')]
  3692. newfile = askopenfilename(filetypes=ftypes)
  3693. if newfile:
  3694. self.infile.set(newfile)
  3695. newconf = process_source_file(newfile)[0]
  3696. newconf = ConfigMaster().sanity(newconf, gui=1)
  3697. # restate all checkboxes after file selection
  3698. #TODO how to make a refresh without killing it?
  3699. self.root.destroy()
  3700. self.__init__(newconf)
  3701. self.mainwindow()
  3702. def scrollwindow(self, txt='no text!', title=''):
  3703. # create components
  3704. win = Tkinter.Toplevel() ; win.title(title)
  3705. frame = Tkinter.Frame(win)
  3706. scroll = Tkinter.Scrollbar(frame)
  3707. text = Tkinter.Text(frame,yscrollcommand=scroll.set)
  3708. button = Tkinter.Button(win)
  3709. # config
  3710. text.insert(Tkinter.END, string.join(txt,'\n'))
  3711. scroll.config(command=text.yview)
  3712. button.config(text=_('Close'), command=win.destroy)
  3713. button.focus_set()
  3714. # packing
  3715. text.pack(side='left', fill='both', expand=1)
  3716. scroll.pack(side='right', fill='y')
  3717. frame.pack(fill='both', expand=1)
  3718. button.pack(ipadx=30)
  3719. def runprogram(self):
  3720. global CMDLINE_RAW
  3721. # prepare
  3722. self.target_name2key()
  3723. infile, target = self.infile.get(), self.target.get()
  3724. # sanity
  3725. if not target:
  3726. showwarning(my_name,_("You must select a target type!"))
  3727. return
  3728. if not infile:
  3729. showwarning(my_name,
  3730. _("You must provide the source file location!"))
  3731. return
  3732. # compose cmdline
  3733. guiflags = []
  3734. real_cmdline_conf = ConfigMaster(CMDLINE_RAW).parse()
  3735. if real_cmdline_conf.has_key('infile'):
  3736. del real_cmdline_conf['infile']
  3737. if real_cmdline_conf.has_key('target'):
  3738. del real_cmdline_conf['target']
  3739. real_cmdline = CommandLine().compose_cmdline(real_cmdline_conf)
  3740. default_outfile = ConfigMaster().get_outfile_name(
  3741. {'sourcefile':infile, 'outfile':'', 'target':target})
  3742. for opt in self.checks:
  3743. val = int(getattr(self, 'f_%s'%opt).get() or "0")
  3744. if opt == 'stdout': opt = 'outfile'
  3745. on_config = self.conf.get(opt) or 0
  3746. on_cmdline = real_cmdline_conf.get(opt) or 0
  3747. if opt == 'outfile':
  3748. if on_config == STDOUT: on_config = 1
  3749. else: on_config = 0
  3750. if on_cmdline == STDOUT: on_cmdline = 1
  3751. else: on_cmdline = 0
  3752. if val != on_config or (
  3753. val == on_config == on_cmdline and
  3754. real_cmdline_conf.has_key(opt)):
  3755. if val:
  3756. # was not set, but user selected on GUI
  3757. Debug("user turned ON: %s"%opt)
  3758. if opt == 'outfile': opt = '-o-'
  3759. else: opt = '--%s'%opt
  3760. else:
  3761. # was set, but user deselected on GUI
  3762. Debug("user turned OFF: %s"%opt)
  3763. if opt == 'outfile':
  3764. opt = "-o%s"%default_outfile
  3765. else: opt = '--no-%s'%opt
  3766. guiflags.append(opt)
  3767. cmdline = [my_name, '-t', target] +real_cmdline \
  3768. +guiflags +[infile]
  3769. Debug('Gui/Tk cmdline: %s'%cmdline,5)
  3770. # run!
  3771. cmdline_raw_orig = CMDLINE_RAW
  3772. try:
  3773. # fake the GUI cmdline as the real one, and parse file
  3774. CMDLINE_RAW = CommandLine().get_raw_config(cmdline[1:])
  3775. data = process_source_file(infile)
  3776. # on GUI, convert_* returns the data, not finish_him()
  3777. outlist, config = convert_this_files([data])
  3778. # on GUI and STDOUT, finish_him() returns the data
  3779. result = finish_him(outlist, config)
  3780. # show outlist in s a nice new window
  3781. if result:
  3782. outlist, config = result
  3783. title = _('%s: %s converted to %s')%(
  3784. my_name, os.path.basename(infile),
  3785. string.upper(config['target']))
  3786. self.scrollwindow(outlist, title)
  3787. # show the "file saved" message
  3788. else:
  3789. msg = "%s\n\n %s\n%s\n\n %s\n%s"%(
  3790. _('Conversion done!'),
  3791. _('FROM:'), infile,
  3792. _('TO:'), config['outfile'])
  3793. showinfo(my_name, msg)
  3794. except error: # common error (windowed), not quit
  3795. pass
  3796. except: # fatal error (windowed and printed)
  3797. errormsg = getUnknownErrorMessage()
  3798. print errormsg
  3799. showerror(_('%s FATAL ERROR!')%my_name,errormsg)
  3800. self.exit()
  3801. CMDLINE_RAW = cmdline_raw_orig
  3802. def mainwindow(self):
  3803. self.infile.set(self.conf.get('sourcefile') or '')
  3804. self.target.set(self.conf.get('target') or \
  3805. _('-- select one --'))
  3806. outfile = self.conf.get('outfile')
  3807. if outfile == STDOUT: # map -o-
  3808. self.conf['stdout'] = 1
  3809. if self.conf.get('headers') == None:
  3810. self.conf['headers'] = 1 # map default
  3811. action1 = _("Enter the source file location:")
  3812. action2 = _("Choose the target document type:")
  3813. action3 = _("Some options you may check:")
  3814. action4 = _("Some extra options:")
  3815. checks_txt = {
  3816. 'headers' : _("Include headers on output"),
  3817. 'enum-title': _("Number titles (1, 1.1, 1.1.1, etc)"),
  3818. 'toc' : _("Do TOC also (Table of Contents)"),
  3819. 'mask-email': _("Hide e-mails from SPAM robots"),
  3820. 'toc-only' : _("Just do TOC, nothing more"),
  3821. 'stdout' : _("Dump to screen (Don't save target file)")
  3822. }
  3823. targets_menu = map(lambda x: TARGET_NAMES[x], TARGETS)
  3824. # header
  3825. self.label("%s %s"%(string.upper(my_name), my_version),
  3826. bg=self.bg2, fg=self.fg2).grid(columnspan=2, ipadx=10)
  3827. self.label(_("ONE source, MULTI targets")+'\n%s\n'%my_url,
  3828. bg=self.bg1, fg=self.fg1).grid(columnspan=2)
  3829. self.row = 2
  3830. # choose input file
  3831. self.action(action1) ; self.frame_open()
  3832. e_infile = self.entry(textvariable=self.infile,width=25)
  3833. e_infile.grid(row=self.row, column=0, sticky='e')
  3834. if not self.infile.get(): e_infile.focus_set()
  3835. self.button(_("Browse"), self.askfile).grid(
  3836. row=self.row, column=1, sticky='w', padx=10)
  3837. # show outfile name, style and encoding (if any)
  3838. txt = ''
  3839. if outfile:
  3840. txt = outfile
  3841. if outfile == STDOUT: txt = _('<screen>')
  3842. l_output = self.label(_('Output: ')+txt,
  3843. fg=self.fg2,bg=self.bg2)
  3844. l_output.grid(columnspan=2, sticky='w')
  3845. for setting in ['style','encoding']:
  3846. if self.conf.get(setting):
  3847. name = string.capitalize(setting)
  3848. val = self.conf[setting]
  3849. self.label('%s: %s'%(name, val),
  3850. fg=self.fg2, bg=self.bg2).grid(
  3851. columnspan=2, sticky='w')
  3852. # choose target
  3853. self.frame_close() ; self.action(action2)
  3854. self.frame_open()
  3855. self.target_key2name()
  3856. self.menu(self.target_name, targets_menu).grid(
  3857. columnspan=2, sticky='w')
  3858. # options checkboxes label
  3859. self.frame_close() ; self.action(action3)
  3860. self.frame_open()
  3861. # compose options check boxes, example:
  3862. # self.check(checks_txt['toc'],1,variable=self.f_toc)
  3863. for check in self.checks:
  3864. # extra options label
  3865. if check == 'toc-only':
  3866. self.frame_close() ; self.action(action4)
  3867. self.frame_open()
  3868. txt = checks_txt[check]
  3869. var = getattr(self, 'f_'+check)
  3870. checked = self.conf.get(check)
  3871. self.check(txt,checked,variable=var)
  3872. self.frame_close()
  3873. # spacer and buttons
  3874. self.label('').grid() ; self.row = self.row + 1
  3875. b_quit = self.button(_("Quit"), self.exit)
  3876. b_quit.grid(row=self.row, column=0, sticky='w', padx=30)
  3877. b_conv = self.button(_("Convert!"), self.runprogram)
  3878. b_conv.grid(row=self.row, column=1, sticky='e', padx=30)
  3879. if self.target.get() and self.infile.get():
  3880. b_conv.focus_set()
  3881. # as documentation told me
  3882. if sys.platform[:3] == 'win':
  3883. self.root.iconify()
  3884. self.root.update()
  3885. self.root.deiconify()
  3886. self.root.mainloop()
  3887. ##############################################################################
  3888. ##############################################################################
  3889. def exec_command_line(user_cmdline=[]):
  3890. global CMDLINE_RAW, RC_RAW, DEBUG, VERBOSE, QUIET, GUI, Error
  3891. # extract command line data
  3892. cmdline_data = user_cmdline or sys.argv[1:]
  3893. CMDLINE_RAW = CommandLine().get_raw_config(cmdline_data, relative=1)
  3894. cmdline_parsed = ConfigMaster(CMDLINE_RAW).parse()
  3895. DEBUG = cmdline_parsed.get('debug' ) or 0
  3896. VERBOSE = cmdline_parsed.get('verbose') or 0
  3897. QUIET = cmdline_parsed.get('quiet' ) or 0
  3898. GUI = cmdline_parsed.get('gui' ) or 0
  3899. infiles = cmdline_parsed.get('infile' ) or []
  3900. Message(_("Txt2tags %s processing begins")%my_version,1)
  3901. # the easy ones
  3902. if cmdline_parsed.get('help' ): Quit(USAGE)
  3903. if cmdline_parsed.get('version'): Quit(VERSIONSTR)
  3904. # multifile haters
  3905. if len(infiles) > 1:
  3906. errmsg=_("Option --%s can't be used with multiple input files")
  3907. for option in ['gui','dump-config']:
  3908. if cmdline_parsed.get(option):
  3909. Error(errmsg%option)
  3910. Debug("system platform: %s"%sys.platform)
  3911. Debug("python version: %s"%(string.split(sys.version,'(')[0]))
  3912. Debug("line break char: %s"%repr(LB))
  3913. Debug("command line: %s"%sys.argv)
  3914. Debug("command line raw config: %s"%CMDLINE_RAW,1)
  3915. # extract RC file config
  3916. if cmdline_parsed.get('rc') == 0:
  3917. Message(_("Ignoring user configuration file"),1)
  3918. else:
  3919. rc_file = get_rc_path()
  3920. if os.path.isfile(rc_file):
  3921. Message(_("Loading user configuration file"),1)
  3922. RC_RAW = ConfigLines(file=rc_file).get_raw_config()
  3923. Debug("rc file: %s"%rc_file)
  3924. Debug("rc file raw config: %s"%RC_RAW,1)
  3925. # get all infiles config (if any)
  3926. infiles_config = get_infiles_config(infiles)
  3927. # is GUI available?
  3928. # try to load and start GUI interface for --gui
  3929. # if program was called with no arguments, try GUI also
  3930. if GUI or not infiles:
  3931. try:
  3932. load_GUI_resources()
  3933. Debug("GUI resources OK (Tk module is installed)")
  3934. winbox = Gui()
  3935. Debug("GUI display OK")
  3936. GUI = 1
  3937. except:
  3938. Debug("GUI Error: no Tk module or no DISPLAY")
  3939. GUI = 0
  3940. # user forced --gui, but it's not available
  3941. if cmdline_parsed.get('gui') and not GUI:
  3942. print getTraceback(); print
  3943. Error("Sorry, I can't run my Graphical Interface - GUI\n"
  3944. "- Check if Python Tcl/Tk module is installed (Tkinter)\n"
  3945. "- Make sure you are in a graphical environment (like X)")
  3946. # Okay, we will use GUI
  3947. if GUI:
  3948. Message(_("We are on GUI interface"),1)
  3949. # redefine Error function to raise exception instead sys.exit()
  3950. def Error(msg):
  3951. showerror(_('txt2tags ERROR!'), msg)
  3952. raise error
  3953. # if no input file, get RC+cmdline config, else full config
  3954. if not infiles:
  3955. gui_conf = ConfigMaster(RC_RAW+CMDLINE_RAW).parse()
  3956. else:
  3957. try : gui_conf = infiles_config[0][0]
  3958. except: gui_conf = {}
  3959. # sanity is needed to set outfile and other things
  3960. gui_conf = ConfigMaster().sanity(gui_conf, gui=1)
  3961. Debug("GUI config: %s"%gui_conf,5)
  3962. # insert config and populate the nice window!
  3963. winbox.load_config(gui_conf)
  3964. winbox.mainwindow()
  3965. # console mode rocks forever!
  3966. else:
  3967. Message(_("We are on Command Line interface"),1)
  3968. # called with no arguments, show error
  3969. if not infiles: Error(_('Missing input file (try --help)'))
  3970. convert_this_files(infiles_config)
  3971. Message(_("Txt2tags finished sucessfuly"),1)
  3972. if __name__ == '__main__':
  3973. try:
  3974. exec_command_line()
  3975. except error, msg:
  3976. sys.stderr.write("%s\n"%msg)
  3977. sys.stderr.flush()
  3978. sys.exit(1)
  3979. except SystemExit:
  3980. pass
  3981. except:
  3982. print getUnknownErrorMessage()
  3983. Quit()
  3984. # vim: ts=8