Package doconce :: Module html
[hide private]
[frames] | no frames]

Source Code for Module doconce.html

  1  import re, os, glob, sys 
  2  from common import table_analysis, plain_exercise 
  3   
  4  # how to replace code and LaTeX blocks by html (<pre>) environment: 
5 -def html_code(filestr, format):
6 c = re.compile(r'^!bc(.*?)\n', re.MULTILINE) 7 # Do not use <code> here, it gives an extra line at the top 8 filestr = c.sub(r'<blockquote> <!-- begin verbatim block \g<1>-->\n<pre>\n', 9 filestr) 10 filestr = re.sub(r'!ec\n', 11 r'</pre>\n</blockquote> <! -- end verbatim block -->\n', 12 filestr) 13 c = re.compile(r'^!bt\n', re.MULTILINE) 14 filestr = c.sub(r'<blockquote><pre>\n', filestr) 15 filestr = re.sub(r'!et\n', r'</pre></blockquote>\n', filestr) 16 return filestr
17
18 -def html_figure(m):
19 caption = m.group('caption').strip() 20 filename = m.group('filename').strip() 21 opts = m.group('options').strip() 22 23 if opts: 24 info = [s.split('=') for s in opts.split()] 25 opts = ['%s=%s' % (option, value) 26 for option, value in info if option not in ['frac']] 27 28 if caption: 29 # Caption above figure and a horizontal rule (fine for anchoring): 30 return '<center><hr>\n<caption><i>%s</i></caption>\n<p><img src="%s" align="bottom" %s></p>\n</center>' % (caption, filename, opts) 31 else: 32 # Just insert image file 33 return '<center><p><img src="%s" align="bottom" %s></p></center>' % \ 34 (filename, opts)
35
36 -def html_table(table):
37 column_width = table_analysis(table['rows']) 38 ncolumns = len(column_width) 39 column_spec = table.get('columns_align', 'c'*ncolumns).replace('|', '') 40 heading_spec = table.get('headings_align', 'c'*ncolumns).replace('|', '') 41 a2html = {'r': 'right', 'l': 'left', 'c': 'center'} 42 43 s = '<table border="1">\n' 44 for i, row in enumerate(table['rows']): 45 if row == ['horizontal rule']: 46 continue 47 if i == 1 and \ 48 table['rows'][i-1] == ['horizontal rule'] and \ 49 table['rows'][i+1] == ['horizontal rule']: 50 headline = True 51 else: 52 headline = False 53 54 s += '<tr>' 55 for column, w, ha, ca in \ 56 zip(row, column_width, heading_spec, column_spec): 57 if headline: 58 s += '<td align="%s"><b>%s</b></td> ' % \ 59 (a2html[ha], column.center(w)) 60 else: 61 s += '<td align="%s"> %s </td> ' % \ 62 (a2html[ca], column.ljust(w)) 63 s += '</tr>\n' 64 s += '</table>\n' 65 return s
66
67 -def html_movie(m):
68 filename = m.group('filename') 69 options = m.group('options') 70 caption = m.group('caption') 71 72 # Turn options to dictionary 73 if ',' in options: 74 options = options.split(',') 75 else: 76 options = options.split() 77 kwargs = {} 78 for opt in options: 79 if opt.startswith('width') or opt.startswith('WIDTH'): 80 kwargs['width'] = int(opt.split('=')[1]) 81 if opt.startswith('height') or opt.startswith('HEIGHT'): 82 kwargs['height'] = int(opt.split('=')[1]) 83 84 if '*' in filename: 85 # Glob files and use DocWriter.html_movie to make a separate 86 # html page for viewing the set of files 87 plotfiles = glob.glob(filename) 88 if not plotfiles: 89 print 'No plotfiles on the form', filename 90 sys.exit(1) 91 plotfiles.sort() 92 basename = os.path.basename(plotfiles[0]) 93 stem, ext = os.path.splitext(basename) 94 kwargs['casename'] = stem 95 import DocWriter 96 header, jscode, form, footer = DocWriter.html_movie(plotfiles, **kwargs) 97 #text = jscode + form # does not work well with several movies 98 moviehtml = stem + '.html' 99 f = open(moviehtml, 'w') 100 f.write(header + jscode + form + footer) 101 f.close() 102 text = """ 103 <p><a href="%s">Movie of files <tt>%s</tt></a>\n<em>%s</em></p>""" % \ 104 (moviehtml, filename, caption) 105 elif 'youtube.com' in filename: 106 if not 'youtube.com/embed/' in filename: 107 filename = filename.replace('embed/', 'watch?v=') 108 # Make html for a local YouTube frame 109 width = kwargs.get('width', 425) 110 height = kwargs.get('height', 349) 111 text = """ 112 <iframe width="%s" height="%s" src="%s" frameborder="0" allowfullscreen></iframe> 113 """ % (width, height, filename) 114 else: 115 text = """ 116 <embed src="%s" %s autoplay="false" loop="true"></embed> 117 <p> 118 <em>%s</em> 119 </p> 120 """ % (filename, ' '.join(options), caption) 121 return text
122
123 -def html_author(authors_and_institutions, auth2index, 124 inst2index, index2inst, auth2email):
125 text = '' 126 for author in auth2index: 127 email = auth2email[author] 128 if email is None: 129 email_text = '' 130 else: 131 name, adr = email.split('@') 132 email_text = ' (<tt>%s</tt> at <tt>%s</tt>)' % (name, adr) 133 134 text += '\n<center>\n<b>%s</b> %s%s\n</center>\n' % \ 135 (author, str(auth2index[author]), email_text) 136 text += '\n<p>\n' 137 for index in index2inst: 138 text += '<center>[%d] <b>%s</b></center>\n' % (index, index2inst[index]) 139 text += '\n\n' 140 return text
141 142
143 -def html_ref_and_label(section_label2title, format, filestr):
144 # .... see section ref{my:sec} is replaced by 145 # see the section "...section heading..." 146 pattern = r'[Ss]ection(s?)\s+ref\{' 147 replacement = r'the section\g<1> ref{' 148 filestr = re.sub(pattern, replacement, filestr) 149 pattern = r'[Cc]hapter(s?)\s+ref\{' 150 replacement = r'the chapter\g<1> ref{' 151 filestr = re.sub(pattern, replacement, filestr) 152 153 # turn label{myname} to anchors <A NAME="myname"></a> 154 filestr = re.sub(r'label\{(.+?)\}', r'<a name="\g<1>"></A>', filestr) 155 156 # make special anchors for all the section titles: 157 for label in section_label2title: 158 # first remove the anchor with this label as created above: 159 filestr = filestr.replace('<a name="%s"></A>' % label, '') 160 # make new anchor for this label (put in title): 161 title = section_label2title[label] 162 title_pattern = r'(_{3,7}|={3,7})\s*%s\s*(_{3,7}|={3,7})' % re.escape(title) # title may contain ? () etc. 163 filestr, n = re.subn(title_pattern, 164 '\g<1> %s <a name="%s"></A> \g<2>' % (title, label), 165 filestr) 166 # (a little odd with mix of doconce title syntax and html NAME tag...) 167 if n == 0: 168 raise Exception('problem with substituting "%s"' % title) 169 170 # replace all references to sections by section titles: 171 for label in section_label2title: 172 title = section_label2title[label] 173 filestr = filestr.replace('ref{%s}' % label, 174 '<a href="#%s">%s</a>' % (label, title)) 175 176 # replace all other references ref{myname} by <a href="#myname">myname</a>: 177 filestr = re.sub(r'ref\{(.+?)\}', r'<a href="#\g<1>">\g<1></a>', filestr) 178 179 from common import ref2equations 180 filestr = ref2equations(filestr) 181 182 return filestr
183
184 -def bibdict2htmllist(pyfile, citations):
185 """Transform dict with bibliography to an HTML ordered list with anchors.""" 186 f = open(pyfile, 'r') 187 bibstr = f.read() 188 try: 189 bibdict = eval(bibstr) 190 except: 191 print 'Error in Python dictionary for bibliography in', pyfile 192 sys.exit(1) 193 text = '\n\n<h1>Bibliography</h1>\n\n<ol>\n' 194 for label in citations: 195 # remove newlines in reference data: 196 text += ' <p><li><a name="%s"> ' % label + \ 197 ' '.join(bibdict[label].splitlines()) + '\n' 198 text += '</ol>\n\n' 199 return text
200
201 -def html_index_bib(filestr, index, citations, bibfile):
202 for label in citations: 203 filestr = filestr.replace('cite{%s}' % label, 204 '<a href="#%s">[%d]</a>' % \ 205 (label, citations[label])) 206 if 'py' in bibfile: 207 bibtext = bibdict2htmllist(bibfile['py'], citations) 208 #filestr = re.sub(r'^BIBFILE:.+$', bibtext, filestr, flags=re.MULTILINE) 209 cpattern = re.compile(r'^BIBFILE:.+$', flags=re.MULTILINE) 210 filestr = cpattern.sub(bibtext, filestr) # v2.6 211 212 # could use anchors for idx{...}, but multiple entries of an index 213 # would lead to multiple anchors, so remove them all: 214 filestr = re.sub(r'idx\{.+?\}\n?', '', filestr) 215 216 return filestr
217 218
219 -def define(FILENAME_EXTENSION, 220 BLANKLINE, 221 INLINE_TAGS_SUBST, 222 CODE, 223 LIST, 224 ARGLIST, 225 TABLE, 226 EXERCISE, 227 FIGURE_EXT, 228 CROSS_REFS, 229 INDEX_BIB, 230 INTRO, 231 OUTRO):
232 # all arguments are dicts and accept in-place modifications (extensions) 233 234 FILENAME_EXTENSION['html'] = '.html' # output file extension 235 BLANKLINE['html'] = '\n<P>\n' # blank input line => new paragraph 236 237 INLINE_TAGS_SUBST['html'] = { # from inline tags to HTML tags 238 # keep math as is: 239 'math': r'\g<begin>\g<subst>\g<end>', 240 'math2': r'\g<begin>\g<puretext>\g<end>', 241 'emphasize': r'\g<begin><em>\g<subst></em>\g<end>', 242 'bold': r'\g<begin><b>\g<subst></b>\g<end>', 243 'verbatim': r'\g<begin><tt>\g<subst></tt>\g<end>', 244 'citation': '', # no citations 245 'linkURL': r'\g<begin><a href="\g<url>">\g<link></a>\g<end>', 246 'linkURL2': r'<a href="\g<url>">\g<link></a>', 247 'linkURL3': r'<a href="\g<url>">\g<link></a>', 248 'linkURL2v': r'<a href="\g<url>"><tt>\g<link></tt></a>', 249 'linkURL3v': r'<a href="\g<url>"><tt>\g<link></tt></a>', 250 'plainURL': r'<a href="\g<url>"><tt>\g<url></tt></a>', 251 'inlinecomment': r'[<b>\g<name></b>: <em>\g<comment></em>]', 252 'chapter': r'<h1>\g<subst></h1>', 253 'section': r'<h2>\g<subst></h2>', 254 'subsection': r'<h3>\g<subst></h3>', 255 'subsubsection': r'<h4>\g<subst></h4>', 256 'paragraph': r'<b>\g<subst></b> ', 257 'abstract': r'<b>\g<type>.</b> \g<text>\n\g<rest>', 258 'title': r'<title>\g<subst></title>\n<center><h1>\g<subst></h1></center>', 259 'date': r'<center><h3>\g<subst></h3></center>', 260 'author': html_author, 261 #'figure': r'<p><em>\g<caption></em></p><img src="\g<filename>" align="bottom" \g<options>>', 262 #'figure': r'<img src="\g<filename>" align="bottom" \g<options>> <p><em>\g<caption></em></p>', 263 #'figure': r'<center><img src="\g<filename>" align="bottom" \g<options>> <br><caption><i>\g<caption></i></caption></center>', 264 'figure': html_figure, 265 'movie': html_movie, 266 'comment': '<!-- %s -->', 267 } 268 269 CODE['html'] = html_code 270 271 # how to typeset lists and their items in html: 272 LIST['html'] = { 273 'itemize': 274 {'begin': '\n<ul>\n', 'item': '<li>', 'end': '</ul>\n\n'}, 275 276 'enumerate': 277 {'begin': '\n<ol>\n', 'item': '<li>', 'end': '</ol>\n\n'}, 278 279 'description': 280 {'begin': '\n<dl>\n', 'item': '<dt>%s<dd>', 'end': '</dl>\n\n'}, 281 282 'separator': '', # no need for blank lines between items and before/after 283 } 284 285 # how to typeset description lists for function arguments, return 286 # values, and module/class variables: 287 ARGLIST['html'] = { 288 'parameter': '<b>argument</b>', 289 'keyword': '<b>keyword argument</b>', 290 'return': '<b>return value(s)</b>', 291 'instance variable': '<b>instance variable</b>', 292 'class variable': '<b>class variable</b>', 293 'module variable': '<b>module variable</b>', 294 } 295 296 FIGURE_EXT['html'] = ('.png', '.gif', '.jpg', '.jpeg') 297 CROSS_REFS['html'] = html_ref_and_label 298 TABLE['html'] = html_table 299 INDEX_BIB['html'] = html_index_bib 300 EXERCISE['html'] = plain_exercise 301 302 # document start: 303 INTRO['html'] = """\ 304 <?xml version="1.0" encoding="utf-8" ?> 305 <!-- 306 Automatically generated HTML file from Doconce source 307 (http://code.google.com/p/doconce/) 308 --> 309 310 <html> 311 <head> 312 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 313 <meta name="generator" content="Doconce: http://code.google.com/p/doconce/" /> 314 </head> 315 316 <body bgcolor="white"> 317 """ 318 # document ending: 319 OUTRO['html'] = """ 320 </body> 321 </html> 322 """
323
324 -def latin2html(text):
325 """ 326 Transform a text with possible latin-1 characters to the 327 equivalent valid text in HTML with all special characters 328 with ordinal > 159 encoded as &#number; 329 330 Method: convert from plain text (open(filename, 'r')) to utf-8, 331 run through each character c, if ord(c) > 159, 332 add the HTML encoded text to a list, otherwise just add c to the list, 333 then finally join the list to make the new version of the text. 334 335 Note: A simpler method is just to set 336 <?xml version="1.0" encoding="utf-8" ?> 337 as the first line in the HTML file, see how rst2html.py 338 starts the HTML file. 339 (However, the method below shows how to cope with special 340 European characters in general.) 341 """ 342 text_new = [] 343 try: 344 text = text.decode('utf-8') 345 except UnicodeDecodeError: 346 try: 347 text = text.decode('latin-1') 348 except UnicodeDecodeError, e: 349 print 'Tried to interpret the file as utf-8 (failed) and latin-1 (failed) - aborted' 350 raise e 351 for c in text: 352 try: 353 if ord(c) > 159: 354 text_new.append('&#%d;' % ord(c)) 355 else: 356 text_new.append(c) 357 except Exception, e: 358 print e 359 print 'character causing problems:', c 360 raise e.__class__('%s: character causing problems: %s' % \ 361 (e.__class__.__name__, c)) 362 return ''.join(text_new)
363