Debian Codegraph @

docs/backdoc.py

raw
1 #!/usr/bin/env python
2 """
3 Backdoc is a tool for backbone-like documentation generation.
4 Backdoc main goal is to help to generate one page documentation from one markdown source file.
5
6 https://github.com/chibisov/backdoc
7 """
8 import sys
9 import argparse
10
11 # Copyright (c) 2012 Trent Mick.
12 # Copyright (c) 2007-2008 ActiveState Corp.
13 # License: MIT (http://www.opensource.org/licenses/mit-license.php)
14
15 r"""A fast and complete Python implementation of Markdown.
16
17 [from http://daringfireball.net/projects/markdown/]
18 > Markdown is a text-to-HTML filter; it translates an easy-to-read /
19 > easy-to-write structured text format into HTML. Markdown's text
20 > format is most similar to that of plain text email, and supports
21 > features such as headers, *emphasis*, code blocks, blockquotes, and
22 > links.
23 >
24 > Markdown's syntax is designed not as a generic markup language, but
25 > specifically to serve as a front-end to (X)HTML. You can use span-level
26 > HTML tags anywhere in a Markdown document, and you can use block level
27 > HTML tags (like <div> and <table> as well).
28
29 Module usage:
30
31 >>> import markdown2
32 >>> markdown2.markdown("*boo!*") # or use `html = markdown_path(PATH)`
33 u'<p><em>boo!</em></p>\n'
34
35 >>> markdowner = Markdown()
36 >>> markdowner.convert("*boo!*")
37 u'<p><em>boo!</em></p>\n'
38 >>> markdowner.convert("**boom!**")
39 u'<p><strong>boom!</strong></p>\n'
40
41 This implementation of Markdown implements the full "core" syntax plus a
42 number of extras (e.g., code syntax coloring, footnotes) as described on
43 <https://github.com/trentm/python-markdown2/wiki/Extras>.
44 """
45
46 cmdln_desc = """A fast and complete Python implementation of Markdown, a
47 text-to-HTML conversion tool for web writers.
48
49 Supported extra syntax options (see -x|--extras option below and
50 see <https://github.com/trentm/python-markdown2/wiki/Extras> for details):
51
52 * code-friendly: Disable _ and __ for em and strong.
53 * cuddled-lists: Allow lists to be cuddled to the preceding paragraph.
54 * fenced-code-blocks: Allows a code block to not have to be indented
55 by fencing it with '```' on a line before and after. Based on
56 <http://github.github.com/github-flavored-markdown/> with support for
57 syntax highlighting.
58 * footnotes: Support footnotes as in use on daringfireball.net and
59 implemented in other Markdown processors (tho not in Markdown.pl v1.0.1).
60 * header-ids: Adds "id" attributes to headers. The id value is a slug of
61 the header text.
62 * html-classes: Takes a dict mapping html tag names (lowercase) to a
63 string to use for a "class" tag attribute. Currently only supports
64 "pre" and "code" tags. Add an issue if you require this for other tags.
65 * markdown-in-html: Allow the use of `markdown="1"` in a block HTML tag to
66 have markdown processing be done on its contents. Similar to
67 <http://michelf.com/projects/php-markdown/extra/#markdown-attr> but with
68 some limitations.
69 * metadata: Extract metadata from a leading '---'-fenced block.
70 See <https://github.com/trentm/python-markdown2/issues/77> for details.
71 * nofollow: Add `rel="nofollow"` to add `<a>` tags with an href. See
72 <http://en.wikipedia.org/wiki/Nofollow>.
73 * pyshell: Treats unindented Python interactive shell sessions as <code>
74 blocks.
75 * link-patterns: Auto-link given regex patterns in text (e.g. bug number
76 references, revision number references).
77 * smarty-pants: Replaces ' and " with curly quotation marks or curly
78 apostrophes. Replaces --, ---, ..., and . . . with en dashes, em dashes,
79 and ellipses.
80 * toc: The returned HTML string gets a new "toc_html" attribute which is
81 a Table of Contents for the document. (experimental)
82 * xml: Passes one-liner processing instructions and namespaced XML tags.
83 * wiki-tables: Google Code Wiki-style tables. See
84 <http://code.google.com/p/support/wiki/WikiSyntax#Tables>.
85 """
86
87 # Dev Notes:
88 # - Python's regex syntax doesn't have '\z', so I'm using '\Z'. I'm
89 # not yet sure if there implications with this. Compare 'pydoc sre'
90 # and 'perldoc perlre'.
91
92 __version_info__ = (2, 1, 1)
93 __version__ = '.'.join(map(str, __version_info__))
94 __author__ = "Trent Mick"
95
96 import os
97 import sys
98 from pprint import pprint
99 import re
100 import logging
101 try:
102 from hashlib import md5
103 except ImportError:
104 from md5 import md5
105 import optparse
106 from random import random, randint
107 import codecs
108
109
110 #---- Python version compat
111
112 try:
113 from urllib.parse import quote # python3
114 except ImportError:
115 from urllib import quote # python2
116
117 if sys.version_info[:2] < (2,4):
118 from sets import Set as set
119 def reversed(sequence):
120 for i in sequence[::-1]:
121 yield i
122
123 # Use `bytes` for byte strings and `unicode` for unicode strings (str in Py3).
124 if sys.version_info[0] <= 2:
125 py3 = False
126 try:
127 bytes
128 except NameError:
129 bytes = str
130 base_string_type = basestring
131 elif sys.version_info[0] >= 3:
132 py3 = True
133 unicode = str
134 base_string_type = str
135
136
137
138 #---- globals
139
140 DEBUG = False
141 log = logging.getLogger("markdown")
142
143 DEFAULT_TAB_WIDTH = 4
144
145
146 SECRET_SALT = bytes(randint(0, 1000000))
147 def _hash_text(s):
148 return 'md5-' + md5(SECRET_SALT + s.encode("utf-8")).hexdigest()
149
150 # Table of hash values for escaped characters:
151 g_escape_table = dict([(ch, _hash_text(ch))
152 for ch in '\\`*_{}[]()>#+-.!'])
153
154
155
156 #---- exceptions
157
158 class MarkdownError(Exception):
159 pass
160
161
162
163 #---- public api
164
165 def markdown_path(path, encoding="utf-8",
166 html4tags=False, tab_width=DEFAULT_TAB_WIDTH,
167 safe_mode=None, extras=None, link_patterns=None,
168 use_file_vars=False):
169 fp = codecs.open(path, 'r', encoding)
170 text = fp.read()
171 fp.close()
172 return Markdown(html4tags=html4tags, tab_width=tab_width,
173 safe_mode=safe_mode, extras=extras,
174 link_patterns=link_patterns,
175 use_file_vars=use_file_vars).convert(text)
176
177 def markdown(text, html4tags=False, tab_width=DEFAULT_TAB_WIDTH,
178 safe_mode=None, extras=None, link_patterns=None,
179 use_file_vars=False):
180 return Markdown(html4tags=html4tags, tab_width=tab_width,
181 safe_mode=safe_mode, extras=extras,
182 link_patterns=link_patterns,
183 use_file_vars=use_file_vars).convert(text)
184
185 class Markdown:
186 # The dict of "extras" to enable in processing -- a mapping of
187 # extra name to argument for the extra. Most extras do not have an
188 # argument, in which case the value is None.
189 #
190 # This can be set via (a) subclassing and (b) the constructor
191 # "extras" argument.
192 extras = None
193
194 urls = None
195 titles = None
196 html_blocks = None
197 html_spans = None
198 html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py
199
200 # Used to track when we're inside an ordered or unordered list
201 # (see _ProcessListItems() for details):
202 list_level = 0
203
204 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M)
205
206 def __init__(self, html4tags=False, tab_width=4, safe_mode=None,
207 extras=None, link_patterns=None, use_file_vars=False):
208 if html4tags:
209 self.empty_element_suffix = ">"
210 else:
211 self.empty_element_suffix = " />"
212 self.tab_width = tab_width
213
214 # For compatibility with earlier markdown2.py and with
215 # markdown.py's safe_mode being a boolean,
216 # safe_mode == True -> "replace"
217 if safe_mode is True:
218 self.safe_mode = "replace"
219 else:
220 self.safe_mode = safe_mode
221
222 # Massaging and building the "extras" info.
223 if self.extras is None:
224 self.extras = {}
225 elif not isinstance(self.extras, dict):
226 self.extras = dict([(e, None) for e in self.extras])
227 if extras:
228 if not isinstance(extras, dict):
229 extras = dict([(e, None) for e in extras])
230 self.extras.update(extras)
231 assert isinstance(self.extras, dict)
232 if "toc" in self.extras and not "header-ids" in self.extras:
233 self.extras["header-ids"] = None # "toc" implies "header-ids"
234 self._instance_extras = self.extras.copy()
235
236 self.link_patterns = link_patterns
237 self.use_file_vars = use_file_vars
238 self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M)
239
240 self._escape_table = g_escape_table.copy()
241 if "smarty-pants" in self.extras:
242 self._escape_table['"'] = _hash_text('"')
243 self._escape_table["'"] = _hash_text("'")
244
245 def reset(self):
246 self.urls = {}
247 self.titles = {}
248 self.html_blocks = {}
249 self.html_spans = {}
250 self.list_level = 0
251 self.extras = self._instance_extras.copy()
252 if "footnotes" in self.extras:
253 self.footnotes = {}
254 self.footnote_ids = []
255 if "header-ids" in self.extras:
256 self._count_from_header_id = {} # no `defaultdict` in Python 2.4
257 if "metadata" in self.extras:
258 self.metadata = {}
259
260 # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel"
261 # should only be used in <a> tags with an "href" attribute.
262 _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE)
263
264 def convert(self, text):
265 """Convert the given text."""
266 # Main function. The order in which other subs are called here is
267 # essential. Link and image substitutions need to happen before
268 # _EscapeSpecialChars(), so that any *'s or _'s in the <a>
269 # and <img> tags get encoded.
270
271 # Clear the global hashes. If we don't clear these, you get conflicts
272 # from other articles when generating a page which contains more than
273 # one article (e.g. an index page that shows the N most recent
274 # articles):
275 self.reset()
276
277 if not isinstance(text, unicode):
278 #TODO: perhaps shouldn't presume UTF-8 for string input?
279 text = unicode(text, 'utf-8')
280
281 if self.use_file_vars:
282 # Look for emacs-style file variable hints.
283 emacs_vars = self._get_emacs_vars(text)
284 if "markdown-extras" in emacs_vars:
285 splitter = re.compile("[ ,]+")
286 for e in splitter.split(emacs_vars["markdown-extras"]):
287 if '=' in e:
288 ename, earg = e.split('=', 1)
289 try:
290 earg = int(earg)
291 except ValueError:
292 pass
293 else:
294 ename, earg = e, None
295 self.extras[ename] = earg
296
297 # Standardize line endings:
298 text = re.sub("\r\n|\r", "\n", text)
299
300 # Make sure $text ends with a couple of newlines:
301 text += "\n\n"
302
303 # Convert all tabs to spaces.
304 text = self._detab(text)
305
306 # Strip any lines consisting only of spaces and tabs.
307 # This makes subsequent regexen easier to write, because we can
308 # match consecutive blank lines with /\n+/ instead of something
309 # contorted like /[ \t]*\n+/ .
310 text = self._ws_only_line_re.sub("", text)
311
312 # strip metadata from head and extract
313 if "metadata" in self.extras:
314 text = self._extract_metadata(text)
315
316 text = self.preprocess(text)
317
318 if self.safe_mode:
319 text = self._hash_html_spans(text)
320
321 # Turn block-level HTML blocks into hash entries
322 text = self._hash_html_blocks(text, raw=True)
323
324 # Strip link definitions, store in hashes.
325 if "footnotes" in self.extras:
326 # Must do footnotes first because an unlucky footnote defn
327 # looks like a link defn:
328 # [^4]: this "looks like a link defn"
329 text = self._strip_footnote_definitions(text)
330 text = self._strip_link_definitions(text)
331
332 text = self._run_block_gamut(text)
333
334 if "footnotes" in self.extras:
335 text = self._add_footnotes(text)
336
337 text = self.postprocess(text)
338
339 text = self._unescape_special_chars(text)
340
341 if self.safe_mode:
342 text = self._unhash_html_spans(text)
343
344 if "nofollow" in self.extras:
345 text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text)
346
347 text += "\n"
348
349 rv = UnicodeWithAttrs(text)
350 if "toc" in self.extras:
351 rv._toc = self._toc
352 if "metadata" in self.extras:
353 rv.metadata = self.metadata
354 return rv
355
356 def postprocess(self, text):
357 """A hook for subclasses to do some postprocessing of the html, if
358 desired. This is called before unescaping of special chars and
359 unhashing of raw HTML spans.
360 """
361 return text
362
363 def preprocess(self, text):
364 """A hook for subclasses to do some preprocessing of the Markdown, if
365 desired. This is called after basic formatting of the text, but prior
366 to any extras, safe mode, etc. processing.
367 """
368 return text
369
370 # Is metadata if the content starts with '---'-fenced `key: value`
371 # pairs. E.g. (indented for presentation):
372 # ---
373 # foo: bar
374 # another-var: blah blah
375 # ---
376 _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""")
377
378 def _extract_metadata(self, text):
379 # fast test
380 if not text.startswith("---"):
381 return text
382 match = self._metadata_pat.match(text)
383 if not match:
384 return text
385
386 tail = text[len(match.group(0)):]
387 metadata_str = match.group(1).strip()
388 for line in metadata_str.split('\n'):
389 key, value = line.split(':', 1)
390 self.metadata[key.strip()] = value.strip()
391
392 return tail
393
394
395 _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE)
396 # This regular expression is intended to match blocks like this:
397 # PREFIX Local Variables: SUFFIX
398 # PREFIX mode: Tcl SUFFIX
399 # PREFIX End: SUFFIX
400 # Some notes:
401 # - "[ \t]" is used instead of "\s" to specifically exclude newlines
402 # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does
403 # not like anything other than Unix-style line terminators.
404 _emacs_local_vars_pat = re.compile(r"""^
405 (?P<prefix>(?:[^\r\n|\n|\r])*?)
406 [\ \t]*Local\ Variables:[\ \t]*
407 (?P<suffix>.*?)(?:\r\n|\n|\r)
408 (?P<content>.*?\1End:)
409 """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE)
410
411 def _get_emacs_vars(self, text):
412 """Return a dictionary of emacs-style local variables.
413
414 Parsing is done loosely according to this spec (and according to
415 some in-practice deviations from this):
416 http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables
417 """
418 emacs_vars = {}
419 SIZE = pow(2, 13) # 8kB
420
421 # Search near the start for a '-*-'-style one-liner of variables.
422 head = text[:SIZE]
423 if "-*-" in head:
424 match = self._emacs_oneliner_vars_pat.search(head)
425 if match:
426 emacs_vars_str = match.group(1)
427 assert '\n' not in emacs_vars_str
428 emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';')
429 if s.strip()]
430 if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]:
431 # While not in the spec, this form is allowed by emacs:
432 # -*- Tcl -*-
433 # where the implied "variable" is "mode". This form
434 # is only allowed if there are no other variables.
435 emacs_vars["mode"] = emacs_var_strs[0].strip()
436 else:
437 for emacs_var_str in emacs_var_strs:
438 try:
439 variable, value = emacs_var_str.strip().split(':', 1)
440 except ValueError:
441 log.debug("emacs variables error: malformed -*- "
442 "line: %r", emacs_var_str)
443 continue
444 # Lowercase the variable name because Emacs allows "Mode"
445 # or "mode" or "MoDe", etc.
446 emacs_vars[variable.lower()] = value.strip()
447
448 tail = text[-SIZE:]
449 if "Local Variables" in tail:
450 match = self._emacs_local_vars_pat.search(tail)
451 if match:
452 prefix = match.group("prefix")
453 suffix = match.group("suffix")
454 lines = match.group("content").splitlines(0)
455 #print "prefix=%r, suffix=%r, content=%r, lines: %s"\
456 # % (prefix, suffix, match.group("content"), lines)
457
458 # Validate the Local Variables block: proper prefix and suffix
459 # usage.
460 for i, line in enumerate(lines):
461 if not line.startswith(prefix):
462 log.debug("emacs variables error: line '%s' "
463 "does not use proper prefix '%s'"
464 % (line, prefix))
465 return {}
466 # Don't validate suffix on last line. Emacs doesn't care,
467 # neither should we.
468 if i != len(lines)-1 and not line.endswith(suffix):
469 log.debug("emacs variables error: line '%s' "
470 "does not use proper suffix '%s'"
471 % (line, suffix))
472 return {}
473
474 # Parse out one emacs var per line.
475 continued_for = None
476 for line in lines[:-1]: # no var on the last line ("PREFIX End:")
477 if prefix: line = line[len(prefix):] # strip prefix
478 if suffix: line = line[:-len(suffix)] # strip suffix
479 line = line.strip()
480 if continued_for:
481 variable = continued_for
482 if line.endswith('\\'):
483 line = line[:-1].rstrip()
484 else:
485 continued_for = None
486 emacs_vars[variable] += ' ' + line
487 else:
488 try:
489 variable, value = line.split(':', 1)
490 except ValueError:
491 log.debug("local variables error: missing colon "
492 "in local variables entry: '%s'" % line)
493 continue
494 # Do NOT lowercase the variable name, because Emacs only
495 # allows "mode" (and not "Mode", "MoDe", etc.) in this block.
496 value = value.strip()
497 if value.endswith('\\'):
498 value = value[:-1].rstrip()
499 continued_for = variable
500 else:
501 continued_for = None
502 emacs_vars[variable] = value
503
504 # Unquote values.
505 for var, val in list(emacs_vars.items()):
506 if len(val) > 1 and (val.startswith('"') and val.endswith('"')
507 or val.startswith('"') and val.endswith('"')):
508 emacs_vars[var] = val[1:-1]
509
510 return emacs_vars
511
512 # Cribbed from a post by Bart Lateur:
513 # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154>
514 _detab_re = re.compile(r'(.*?)\t', re.M)
515 def _detab_sub(self, match):
516 g1 = match.group(1)
517 return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width))
518 def _detab(self, text):
519 r"""Remove (leading?) tabs from a file.
520
521 >>> m = Markdown()
522 >>> m._detab("\tfoo")
523 ' foo'
524 >>> m._detab(" \tfoo")
525 ' foo'
526 >>> m._detab("\t foo")
527 ' foo'
528 >>> m._detab(" foo")
529 ' foo'
530 >>> m._detab(" foo\n\tbar\tblam")
531 ' foo\n bar blam'
532 """
533 if '\t' not in text:
534 return text
535 return self._detab_re.subn(self._detab_sub, text)[0]
536
537 # I broke out the html5 tags here and add them to _block_tags_a and
538 # _block_tags_b. This way html5 tags are easy to keep track of.
539 _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption'
540
541 _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del'
542 _block_tags_a += _html5tags
543
544 _strict_tag_block_re = re.compile(r"""
545 ( # save in \1
546 ^ # start of line (with re.M)
547 <(%s) # start tag = \2
548 \b # word break
549 (.*\n)*? # any number of lines, minimally matching
550 </\2> # the matching end tag
551 [ \t]* # trailing spaces/tabs
552 (?=\n+|\Z) # followed by a newline or end of document
553 )
554 """ % _block_tags_a,
555 re.X | re.M)
556
557 _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math'
558 _block_tags_b += _html5tags
559
560 _liberal_tag_block_re = re.compile(r"""
561 ( # save in \1
562 ^ # start of line (with re.M)
563 <(%s) # start tag = \2
564 \b # word break
565 (.*\n)*? # any number of lines, minimally matching
566 .*</\2> # the matching end tag
567 [ \t]* # trailing spaces/tabs
568 (?=\n+|\Z) # followed by a newline or end of document
569 )
570 """ % _block_tags_b,
571 re.X | re.M)
572
573 _html_markdown_attr_re = re.compile(
574 r'''\s+markdown=("1"|'1')''')
575 def _hash_html_block_sub(self, match, raw=False):
576 html = match.group(1)
577 if raw and self.safe_mode:
578 html = self._sanitize_html(html)
579 elif 'markdown-in-html' in self.extras and 'markdown=' in html:
580 first_line = html.split('\n', 1)[0]
581 m = self._html_markdown_attr_re.search(first_line)
582 if m:
583 lines = html.split('\n')
584 middle = '\n'.join(lines[1:-1])
585 last_line = lines[-1]
586 first_line = first_line[:m.start()] + first_line[m.end():]
587 f_key = _hash_text(first_line)
588 self.html_blocks[f_key] = first_line
589 l_key = _hash_text(last_line)
590 self.html_blocks[l_key] = last_line
591 return ''.join(["\n\n", f_key,
592 "\n\n", middle, "\n\n",
593 l_key, "\n\n"])
594 key = _hash_text(html)
595 self.html_blocks[key] = html
596 return "\n\n" + key + "\n\n"
597
598 def _hash_html_blocks(self, text, raw=False):
599 """Hashify HTML blocks
600
601 We only want to do this for block-level HTML tags, such as headers,
602 lists, and tables. That's because we still want to wrap <p>s around
603 "paragraphs" that are wrapped in non-block-level tags, such as anchors,
604 phrase emphasis, and spans. The list of tags we're looking for is
605 hard-coded.
606
607 @param raw {boolean} indicates if these are raw HTML blocks in
608 the original source. It makes a difference in "safe" mode.
609 """
610 if '<' not in text:
611 return text
612
613 # Pass `raw` value into our calls to self._hash_html_block_sub.
614 hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw)
615
616 # First, look for nested blocks, e.g.:
617 # <div>
618 # <div>
619 # tags for inner block must be indented.
620 # </div>
621 # </div>
622 #
623 # The outermost tags must start at the left margin for this to match, and
624 # the inner nested divs must be indented.
625 # We need to do this before the next, more liberal match, because the next
626 # match will start at the first `<div>` and stop at the first `</div>`.
627 text = self._strict_tag_block_re.sub(hash_html_block_sub, text)
628
629 # Now match more liberally, simply from `\n<tag>` to `</tag>\n`
630 text = self._liberal_tag_block_re.sub(hash_html_block_sub, text)
631
632 # Special case just for <hr />. It was easier to make a special
633 # case than to make the other regex more complicated.
634 if "<hr" in text:
635 _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width)
636 text = _hr_tag_re.sub(hash_html_block_sub, text)
637
638 # Special case for standalone HTML comments:
639 if "<!--" in text:
640 start = 0
641 while True:
642 # Delimiters for next comment block.
643 try:
644 start_idx = text.index("<!--", start)
645 except ValueError:
646 break
647 try:
648 end_idx = text.index("-->", start_idx) + 3
649 except ValueError:
650 break
651
652 # Start position for next comment block search.
653 start = end_idx
654
655 # Validate whitespace before comment.
656 if start_idx:
657 # - Up to `tab_width - 1` spaces before start_idx.
658 for i in range(self.tab_width - 1):
659 if text[start_idx - 1] != ' ':
660 break
661 start_idx -= 1
662 if start_idx == 0:
663 break
664 # - Must be preceded by 2 newlines or hit the start of
665 # the document.
666 if start_idx == 0:
667 pass
668 elif start_idx == 1 and text[0] == '\n':
669 start_idx = 0 # to match minute detail of Markdown.pl regex
670 elif text[start_idx-2:start_idx] == '\n\n':
671 pass
672 else:
673 break
674
675 # Validate whitespace after comment.
676 # - Any number of spaces and tabs.
677 while end_idx < len(text):
678 if text[end_idx] not in ' \t':
679 break
680 end_idx += 1
681 # - Must be following by 2 newlines or hit end of text.
682 if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'):
683 continue
684
685 # Escape and hash (must match `_hash_html_block_sub`).
686 html = text[start_idx:end_idx]
687 if raw and self.safe_mode:
688 html = self._sanitize_html(html)
689 key = _hash_text(html)
690 self.html_blocks[key] = html
691 text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:]
692
693 if "xml" in self.extras:
694 # Treat XML processing instructions and namespaced one-liner
695 # tags as if they were block HTML tags. E.g., if standalone
696 # (i.e. are their own paragraph), the following do not get
697 # wrapped in a <p> tag:
698 # <?foo bar?>
699 #
700 # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/>
701 _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width)
702 text = _xml_oneliner_re.sub(hash_html_block_sub, text)
703
704 return text
705
706 def _strip_link_definitions(self, text):
707 # Strips link definitions from text, stores the URLs and titles in
708 # hash references.
709 less_than_tab = self.tab_width - 1
710
711 # Link defs are in the form:
712 # [id]: url "optional title"
713 _link_def_re = re.compile(r"""
714 ^[ ]{0,%d}\[(.+)\]: # id = \1
715 [ \t]*
716 \n? # maybe *one* newline
717 [ \t]*
718 <?(.+?)>? # url = \2
719 [ \t]*
720 (?:
721 \n? # maybe one newline
722 [ \t]*
723 (?<=\s) # lookbehind for whitespace
724 ['"(]
725 ([^\n]*) # title = \3
726 ['")]
727 [ \t]*
728 )? # title is optional
729 (?:\n+|\Z)
730 """ % less_than_tab, re.X | re.M | re.U)
731 return _link_def_re.sub(self._extract_link_def_sub, text)
732
733 def _extract_link_def_sub(self, match):
734 id, url, title = match.groups()
735 key = id.lower() # Link IDs are case-insensitive
736 self.urls[key] = self._encode_amps_and_angles(url)
737 if title:
738 self.titles[key] = title
739 return ""
740
741 def _extract_footnote_def_sub(self, match):
742 id, text = match.groups()
743 text = _dedent(text, skip_first_line=not text.startswith('\n')).strip()
744 normed_id = re.sub(r'\W', '-', id)
745 # Ensure footnote text ends with a couple newlines (for some
746 # block gamut matches).
747 self.footnotes[normed_id] = text + "\n\n"
748 return ""
749
750 def _strip_footnote_definitions(self, text):
751 """A footnote definition looks like this:
752
753 [^note-id]: Text of the note.
754
755 May include one or more indented paragraphs.
756
757 Where,
758 - The 'note-id' can be pretty much anything, though typically it
759 is the number of the footnote.
760 - The first paragraph may start on the next line, like so:
761
762 [^note-id]:
763 Text of the note.
764 """
765 less_than_tab = self.tab_width - 1
766 footnote_def_re = re.compile(r'''
767 ^[ ]{0,%d}\[\^(.+)\]: # id = \1
768 [ \t]*
769 ( # footnote text = \2
770 # First line need not start with the spaces.
771 (?:\s*.*\n+)
772 (?:
773 (?:[ ]{%d} | \t) # Subsequent lines must be indented.
774 .*\n+
775 )*
776 )
777 # Lookahead for non-space at line-start, or end of doc.
778 (?:(?=^[ ]{0,%d}\S)|\Z)
779 ''' % (less_than_tab, self.tab_width, self.tab_width),
780 re.X | re.M)
781 return footnote_def_re.sub(self._extract_footnote_def_sub, text)
782
783
784 _hr_data = [
785 ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)),
786 ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)),
787 ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)),
788 ]
789
790 def _run_block_gamut(self, text):
791 # These are all the transformations that form block-level
792 # tags like paragraphs, headers, and list items.
793
794 if "fenced-code-blocks" in self.extras:
795 text = self._do_fenced_code_blocks(text)
796
797 text = self._do_headers(text)
798
799 # Do Horizontal Rules:
800 # On the number of spaces in horizontal rules: The spec is fuzzy: "If
801 # you wish, you may use spaces between the hyphens or asterisks."
802 # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the
803 # hr chars to one or two. We'll reproduce that limit here.
804 hr = "\n<hr"+self.empty_element_suffix+"\n"
805 for ch, regex in self._hr_data:
806 if ch in text:
807 for m in reversed(list(regex.finditer(text))):
808 tail = m.group(1).rstrip()
809 if not tail.strip(ch + ' ') and tail.count(" ") == 0:
810 start, end = m.span()
811 text = text[:start] + hr + text[end:]
812
813 text = self._do_lists(text)
814
815 if "pyshell" in self.extras:
816 text = self._prepare_pyshell_blocks(text)
817 if "wiki-tables" in self.extras:
818 text = self._do_wiki_tables(text)
819
820 text = self._do_code_blocks(text)
821
822 text = self._do_block_quotes(text)
823
824 # We already ran _HashHTMLBlocks() before, in Markdown(), but that
825 # was to escape raw HTML in the original Markdown source. This time,
826 # we're escaping the markup we've just created, so that we don't wrap
827 # <p> tags around block-level tags.
828 text = self._hash_html_blocks(text)
829
830 text = self._form_paragraphs(text)
831
832 return text
833
834 def _pyshell_block_sub(self, match):
835 lines = match.group(0).splitlines(0)
836 _dedentlines(lines)
837 indent = ' ' * self.tab_width
838 s = ('\n' # separate from possible cuddled paragraph
839 + indent + ('\n'+indent).join(lines)
840 + '\n\n')
841 return s
842
843 def _prepare_pyshell_blocks(self, text):
844 """Ensure that Python interactive shell sessions are put in
845 code blocks -- even if not properly indented.
846 """
847 if ">>>" not in text:
848 return text
849
850 less_than_tab = self.tab_width - 1
851 _pyshell_block_re = re.compile(r"""
852 ^([ ]{0,%d})>>>[ ].*\n # first line
853 ^(\1.*\S+.*\n)* # any number of subsequent lines
854 ^\n # ends with a blank line
855 """ % less_than_tab, re.M | re.X)
856
857 return _pyshell_block_re.sub(self._pyshell_block_sub, text)
858
859 def _wiki_table_sub(self, match):
860 ttext = match.group(0).strip()
861 #print 'wiki table: %r' % match.group(0)
862 rows = []
863 for line in ttext.splitlines(0):
864 line = line.strip()[2:-2].strip()
865 row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)]
866 rows.append(row)
867 #pprint(rows)
868 hlines = ['<table>', '<tbody>']
869 for row in rows:
870 hrow = ['<tr>']
871 for cell in row:
872 hrow.append('<td>')
873 hrow.append(self._run_span_gamut(cell))
874 hrow.append('</td>')
875 hrow.append('</tr>')
876 hlines.append(''.join(hrow))
877 hlines += ['</tbody>', '</table>']
878 return '\n'.join(hlines) + '\n'
879
880 def _do_wiki_tables(self, text):
881 # Optimization.
882 if "||" not in text:
883 return text
884
885 less_than_tab = self.tab_width - 1
886 wiki_table_re = re.compile(r'''
887 (?:(?<=\n\n)|\A\n?) # leading blank line
888 ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line
889 (^\1\|\|.+?\|\|\n)* # any number of subsequent lines
890 ''' % less_than_tab, re.M | re.X)
891 return wiki_table_re.sub(self._wiki_table_sub, text)
892
893 def _run_span_gamut(self, text):
894 # These are all the transformations that occur *within* block-level
895 # tags like paragraphs, headers, and list items.
896
897 text = self._do_code_spans(text)
898
899 text = self._escape_special_chars(text)
900
901 # Process anchor and image tags.
902 text = self._do_links(text)
903
904 # Make links out of things like `<http://example.com/>`
905 # Must come after _do_links(), because you can use < and >
906 # delimiters in inline links like [this](<url>).
907 text = self._do_auto_links(text)
908
909 if "link-patterns" in self.extras:
910 text = self._do_link_patterns(text)
911
912 text = self._encode_amps_and_angles(text)
913
914 text = self._do_italics_and_bold(text)
915
916 if "smarty-pants" in self.extras:
917 text = self._do_smart_punctuation(text)
918
919 # Do hard breaks:
920 text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text)
921
922 return text
923
924 # "Sorta" because auto-links are identified as "tag" tokens.
925 _sorta_html_tokenize_re = re.compile(r"""
926 (
927 # tag
928 </?
929 (?:\w+) # tag name
930 (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes
931 \s*/?>
932 |
933 # auto-link (e.g., <http://www.activestate.com/>)
934 <\w+[^>]*>
935 |
936 <!--.*?--> # comment
937 |
938 <\?.*?\?> # processing instruction
939 )
940 """, re.X)
941
942 def _escape_special_chars(self, text):
943 # Python markdown note: the HTML tokenization here differs from
944 # that in Markdown.pl, hence the behaviour for subtle cases can
945 # differ (I believe the tokenizer here does a better job because
946 # it isn't susceptible to unmatched '<' and '>' in HTML tags).
947 # Note, however, that '>' is not allowed in an auto-link URL
948 # here.
949 escaped = []
950 is_html_markup = False
951 for token in self._sorta_html_tokenize_re.split(text):
952 if is_html_markup:
953 # Within tags/HTML-comments/auto-links, encode * and _
954 # so they don't conflict with their use in Markdown for
955 # italics and strong. We're replacing each such
956 # character with its corresponding MD5 checksum value;
957 # this is likely overkill, but it should prevent us from
958 # colliding with the escape values by accident.
959 escaped.append(token.replace('*', self._escape_table['*'])
960 .replace('_', self._escape_table['_']))
961 else:
962 escaped.append(self._encode_backslash_escapes(token))
963 is_html_markup = not is_html_markup
964 return ''.join(escaped)
965
966 def _hash_html_spans(self, text):
967 # Used for safe_mode.
968
969 def _is_auto_link(s):
970 if ':' in s and self._auto_link_re.match(s):
971 return True
972 elif '@' in s and self._auto_email_link_re.match(s):
973 return True
974 return False
975
976 tokens = []
977 is_html_markup = False
978 for token in self._sorta_html_tokenize_re.split(text):
979 if is_html_markup and not _is_auto_link(token):
980 sanitized = self._sanitize_html(token)
981 key = _hash_text(sanitized)
982 self.html_spans[key] = sanitized
983 tokens.append(key)
984 else:
985 tokens.append(token)
986 is_html_markup = not is_html_markup
987 return ''.join(tokens)
988
989 def _unhash_html_spans(self, text):
990 for key, sanitized in list(self.html_spans.items()):
991 text = text.replace(key, sanitized)
992 return text
993
994 def _sanitize_html(self, s):
995 if self.safe_mode == "replace":
996 return self.html_removed_text
997 elif self.safe_mode == "escape":
998 replacements = [
999 ('&', '&amp;'),
1000 ('<', '&lt;'),
1001 ('>', '&gt;'),
1002 ]
1003 for before, after in replacements:
1004 s = s.replace(before, after)
1005 return s
1006 else:
1007 raise MarkdownError("invalid value for 'safe_mode': %r (must be "
1008 "'escape' or 'replace')" % self.safe_mode)
1009
1010 _tail_of_inline_link_re = re.compile(r'''
1011 # Match tail of: [text](/url/) or [text](/url/ "title")
1012 \( # literal paren
1013 [ \t]*
1014 (?P<url> # \1
1015 <.*?>
1016 |
1017 .*?
1018 )
1019 [ \t]*
1020 ( # \2
1021 (['"]) # quote char = \3
1022 (?P<title>.*?)
1023 \3 # matching quote
1024 )? # title is optional
1025 \)
1026 ''', re.X | re.S)
1027 _tail_of_reference_link_re = re.compile(r'''
1028 # Match tail of: [text][id]
1029 [ ]? # one optional space
1030 (?:\n[ ]*)? # one optional newline followed by spaces
1031 \[
1032 (?P<id>.*?)
1033 \]
1034 ''', re.X | re.S)
1035
1036 def _do_links(self, text):
1037 """Turn Markdown link shortcuts into XHTML <a> and <img> tags.
1038
1039 This is a combination of Markdown.pl's _DoAnchors() and
1040 _DoImages(). They are done together because that simplified the
1041 approach. It was necessary to use a different approach than
1042 Markdown.pl because of the lack of atomic matching support in
1043 Python's regex engine used in $g_nested_brackets.
1044 """
1045 MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24
1046
1047 # `anchor_allowed_pos` is used to support img links inside
1048 # anchors, but not anchors inside anchors. An anchor's start
1049 # pos must be `>= anchor_allowed_pos`.
1050 anchor_allowed_pos = 0
1051
1052 curr_pos = 0
1053 while True: # Handle the next link.
1054 # The next '[' is the start of:
1055 # - an inline anchor: [text](url "title")
1056 # - a reference anchor: [text][id]
1057 # - an inline img: ![text](url "title")
1058 # - a reference img: ![text][id]
1059 # - a footnote ref: [^id]
1060 # (Only if 'footnotes' extra enabled)
1061 # - a footnote defn: [^id]: ...
1062 # (Only if 'footnotes' extra enabled) These have already
1063 # been stripped in _strip_footnote_definitions() so no
1064 # need to watch for them.
1065 # - a link definition: [id]: url "title"
1066 # These have already been stripped in
1067 # _strip_link_definitions() so no need to watch for them.
1068 # - not markup: [...anything else...
1069 try:
1070 start_idx = text.index('[', curr_pos)
1071 except ValueError:
1072 break
1073 text_length = len(text)
1074
1075 # Find the matching closing ']'.
1076 # Markdown.pl allows *matching* brackets in link text so we
1077 # will here too. Markdown.pl *doesn't* currently allow
1078 # matching brackets in img alt text -- we'll differ in that
1079 # regard.
1080 bracket_depth = 0
1081 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL,
1082 text_length)):
1083 ch = text[p]
1084 if ch == ']':
1085 bracket_depth -= 1
1086 if bracket_depth < 0:
1087 break
1088 elif ch == '[':
1089 bracket_depth += 1
1090 else:
1091 # Closing bracket not found within sentinel length.
1092 # This isn't markup.
1093 curr_pos = start_idx + 1
1094 continue
1095 link_text = text[start_idx+1:p]
1096
1097 # Possibly a footnote ref?
1098 if "footnotes" in self.extras and link_text.startswith("^"):
1099 normed_id = re.sub(r'\W', '-', link_text[1:])
1100 if normed_id in self.footnotes:
1101 self.footnote_ids.append(normed_id)
1102 result = '<sup class="footnote-ref" id="fnref-%s">' \
1103 '<a href="#fn-%s">%s</a></sup>' \
1104 % (normed_id, normed_id, len(self.footnote_ids))
1105 text = text[:start_idx] + result + text[p+1:]
1106 else:
1107 # This id isn't defined, leave the markup alone.
1108 curr_pos = p+1
1109 continue
1110
1111 # Now determine what this is by the remainder.
1112 p += 1
1113 if p == text_length:
1114 return text
1115
1116 # Inline anchor or img?
1117 if text[p] == '(': # attempt at perf improvement
1118 match = self._tail_of_inline_link_re.match(text, p)
1119 if match:
1120 # Handle an inline anchor or img.
1121 is_img = start_idx > 0 and text[start_idx-1] == "!"
1122 if is_img:
1123 start_idx -= 1
1124
1125 url, title = match.group("url"), match.group("title")
1126 if url and url[0] == '<':
1127 url = url[1:-1] # '<url>' -> 'url'
1128 # We've got to encode these to avoid conflicting
1129 # with italics/bold.
1130 url = url.replace('*', self._escape_table['*']) \
1131 .replace('_', self._escape_table['_'])
1132 if title:
1133 title_str = ' title="%s"' % (
1134 _xml_escape_attr(title)
1135 .replace('*', self._escape_table['*'])
1136 .replace('_', self._escape_table['_']))
1137 else:
1138 title_str = ''
1139 if is_img:
1140 result = '<img src="%s" alt="%s"%s%s' \
1141 % (url.replace('"', '&quot;'),
1142 _xml_escape_attr(link_text),
1143 title_str, self.empty_element_suffix)
1144 if "smarty-pants" in self.extras:
1145 result = result.replace('"', self._escape_table['"'])
1146 curr_pos = start_idx + len(result)
1147 text = text[:start_idx] + result + text[match.end():]
1148 elif start_idx >= anchor_allowed_pos:
1149 result_head = '<a href="%s"%s>' % (url, title_str)
1150 result = '%s%s</a>' % (result_head, link_text)
1151 if "smarty-pants" in self.extras:
1152 result = result.replace('"', self._escape_table['"'])
1153 # <img> allowed from curr_pos on, <a> from
1154 # anchor_allowed_pos on.
1155 curr_pos = start_idx + len(result_head)
1156 anchor_allowed_pos = start_idx + len(result)
1157 text = text[:start_idx] + result + text[match.end():]
1158 else:
1159 # Anchor not allowed here.
1160 curr_pos = start_idx + 1
1161 continue
1162
1163 # Reference anchor or img?
1164 else:
1165 match = self._tail_of_reference_link_re.match(text, p)
1166 if match:
1167 # Handle a reference-style anchor or img.
1168 is_img = start_idx > 0 and text[start_idx-1] == "!"
1169 if is_img:
1170 start_idx -= 1
1171 link_id = match.group("id").lower()
1172 if not link_id:
1173 link_id = link_text.lower() # for links like [this][]
1174 if link_id in self.urls:
1175 url = self.urls[link_id]
1176 # We've got to encode these to avoid conflicting
1177 # with italics/bold.
1178 url = url.replace('*', self._escape_table['*']) \
1179 .replace('_', self._escape_table['_'])
1180 title = self.titles.get(link_id)
1181 if title:
1182 before = title
1183 title = _xml_escape_attr(title) \
1184 .replace('*', self._escape_table['*']) \
1185 .replace('_', self._escape_table['_'])
1186 title_str = ' title="%s"' % title
1187 else:
1188 title_str = ''
1189 if is_img:
1190 result = '<img src="%s" alt="%s"%s%s' \
1191 % (url.replace('"', '&quot;'),
1192 link_text.replace('"', '&quot;'),
1193 title_str, self.empty_element_suffix)
1194 if "smarty-pants" in self.extras:
1195 result = result.replace('"', self._escape_table['"'])
1196 curr_pos = start_idx + len(result)
1197 text = text[:start_idx] + result + text[match.end():]
1198 elif start_idx >= anchor_allowed_pos:
1199 result = '<a href="%s"%s>%s</a>' \
1200 % (url, title_str, link_text)
1201 result_head = '<a href="%s"%s>' % (url, title_str)
1202 result = '%s%s</a>' % (result_head, link_text)
1203 if "smarty-pants" in self.extras:
1204 result = result.replace('"', self._escape_table['"'])
1205 # <img> allowed from curr_pos on, <a> from
1206 # anchor_allowed_pos on.
1207 curr_pos = start_idx + len(result_head)
1208 anchor_allowed_pos = start_idx + len(result)
1209 text = text[:start_idx] + result + text[match.end():]
1210 else:
1211 # Anchor not allowed here.
1212 curr_pos = start_idx + 1
1213 else:
1214 # This id isn't defined, leave the markup alone.
1215 curr_pos = match.end()
1216 continue
1217
1218 # Otherwise, it isn't markup.
1219 curr_pos = start_idx + 1
1220
1221 return text
1222
1223 def header_id_from_text(self, text, prefix, n):
1224 """Generate a header id attribute value from the given header
1225 HTML content.
1226
1227 This is only called if the "header-ids" extra is enabled.
1228 Subclasses may override this for different header ids.
1229
1230 @param text {str} The text of the header tag
1231 @param prefix {str} The requested prefix for header ids. This is the
1232 value of the "header-ids" extra key, if any. Otherwise, None.
1233 @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag.
1234 @returns {str} The value for the header tag's "id" attribute. Return
1235 None to not have an id attribute and to exclude this header from
1236 the TOC (if the "toc" extra is specified).
1237 """
1238 header_id = _slugify(text)
1239 if prefix and isinstance(prefix, base_string_type):
1240 header_id = prefix + '-' + header_id
1241 if header_id in self._count_from_header_id:
1242 self._count_from_header_id[header_id] += 1
1243 header_id += '-%s' % self._count_from_header_id[header_id]
1244 else:
1245 self._count_from_header_id[header_id] = 1
1246 return header_id
1247
1248 _toc = None
1249 def _toc_add_entry(self, level, id, name):
1250 if self._toc is None:
1251 self._toc = []
1252 self._toc.append((level, id, self._unescape_special_chars(name)))
1253
1254 _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M)
1255 def _setext_h_sub(self, match):
1256 n = {"=": 1, "-": 2}[match.group(2)[0]]
1257 demote_headers = self.extras.get("demote-headers")
1258 if demote_headers:
1259 n = min(n + demote_headers, 6)
1260 header_id_attr = ""
1261 if "header-ids" in self.extras:
1262 header_id = self.header_id_from_text(match.group(1),
1263 self.extras["header-ids"], n)
1264 if header_id:
1265 header_id_attr = ' id="%s"' % header_id
1266 html = self._run_span_gamut(match.group(1))
1267 if "toc" in self.extras and header_id:
1268 self._toc_add_entry(n, header_id, html)
1269 return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n)
1270
1271 _atx_h_re = re.compile(r'''
1272 ^(\#{1,6}) # \1 = string of #'s
1273 [ \t]+
1274 (.+?) # \2 = Header text
1275 [ \t]*
1276 (?<!\\) # ensure not an escaped trailing '#'
1277 \#* # optional closing #'s (not counted)
1278 \n+
1279 ''', re.X | re.M)
1280 def _atx_h_sub(self, match):
1281 n = len(match.group(1))
1282 demote_headers = self.extras.get("demote-headers")
1283 if demote_headers:
1284 n = min(n + demote_headers, 6)
1285 header_id_attr = ""
1286 if "header-ids" in self.extras:
1287 header_id = self.header_id_from_text(match.group(2),
1288 self.extras["header-ids"], n)
1289 if header_id:
1290 header_id_attr = ' id="%s"' % header_id
1291 html = self._run_span_gamut(match.group(2))
1292 if "toc" in self.extras and header_id:
1293 self._toc_add_entry(n, header_id, html)
1294 return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n)
1295
1296 def _do_headers(self, text):
1297 # Setext-style headers:
1298 # Header 1
1299 # ========
1300 #
1301 # Header 2
1302 # --------
1303 text = self._setext_h_re.sub(self._setext_h_sub, text)
1304
1305 # atx-style headers:
1306 # # Header 1
1307 # ## Header 2
1308 # ## Header 2 with closing hashes ##
1309 # ...
1310 # ###### Header 6
1311 text = self._atx_h_re.sub(self._atx_h_sub, text)
1312
1313 return text
1314
1315
1316 _marker_ul_chars = '*+-'
1317 _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars
1318 _marker_ul = '(?:[%s])' % _marker_ul_chars
1319 _marker_ol = r'(?:\d+\.)'
1320
1321 def _list_sub(self, match):
1322 lst = match.group(1)
1323 lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol"
1324 result = self._process_list_items(lst)
1325 if self.list_level:
1326 return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type)
1327 else:
1328 return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type)
1329
1330 def _do_lists(self, text):
1331 # Form HTML ordered (numbered) and unordered (bulleted) lists.
1332
1333 # Iterate over each *non-overlapping* list match.
1334 pos = 0
1335 while True:
1336 # Find the *first* hit for either list style (ul or ol). We
1337 # match ul and ol separately to avoid adjacent lists of different
1338 # types running into each other (see issue #16).
1339 hits = []
1340 for marker_pat in (self._marker_ul, self._marker_ol):
1341 less_than_tab = self.tab_width - 1
1342 whole_list = r'''
1343 ( # \1 = whole list
1344 ( # \2
1345 [ ]{0,%d}
1346 (%s) # \3 = first list item marker
1347 [ \t]+
1348 (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case.
1349 )
1350 (?:.+?)
1351 ( # \4
1352 \Z
1353 |
1354 \n{2,}
1355 (?=\S)
1356 (?! # Negative lookahead for another list item marker
1357 [ \t]*
1358 %s[ \t]+
1359 )
1360 )
1361 )
1362 ''' % (less_than_tab, marker_pat, marker_pat)
1363 if self.list_level: # sub-list
1364 list_re = re.compile("^"+whole_list, re.X | re.M | re.S)
1365 else:
1366 list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list,
1367 re.X | re.M | re.S)
1368 match = list_re.search(text, pos)
1369 if match:
1370 hits.append((match.start(), match))
1371 if not hits:
1372 break
1373 hits.sort()
1374 match = hits[0][1]
1375 start, end = match.span()
1376 text = text[:start] + self._list_sub(match) + text[end:]
1377 pos = end
1378
1379 return text
1380
1381 _list_item_re = re.compile(r'''
1382 (\n)? # leading line = \1
1383 (^[ \t]*) # leading whitespace = \2
1384 (?P<marker>%s) [ \t]+ # list marker = \3
1385 ((?:.+?) # list item text = \4
1386 (\n{1,2})) # eols = \5
1387 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+))
1388 ''' % (_marker_any, _marker_any),
1389 re.M | re.X | re.S)
1390
1391 _last_li_endswith_two_eols = False
1392 def _list_item_sub(self, match):
1393 item = match.group(4)
1394 leading_line = match.group(1)
1395 leading_space = match.group(2)
1396 if leading_line or "\n\n" in item or self._last_li_endswith_two_eols:
1397 item = self._run_block_gamut(self._outdent(item))
1398 else:
1399 # Recursion for sub-lists:
1400 item = self._do_lists(self._outdent(item))
1401 if item.endswith('\n'):
1402 item = item[:-1]
1403 item = self._run_span_gamut(item)
1404 self._last_li_endswith_two_eols = (len(match.group(5)) == 2)
1405 return "<li>%s</li>\n" % item
1406
1407 def _process_list_items(self, list_str):
1408 # Process the contents of a single ordered or unordered list,
1409 # splitting it into individual list items.
1410
1411 # The $g_list_level global keeps track of when we're inside a list.
1412 # Each time we enter a list, we increment it; when we leave a list,
1413 # we decrement. If it's zero, we're not in a list anymore.
1414 #
1415 # We do this because when we're not inside a list, we want to treat
1416 # something like this:
1417 #
1418 # I recommend upgrading to version
1419 # 8. Oops, now this line is treated
1420 # as a sub-list.
1421 #
1422 # As a single paragraph, despite the fact that the second line starts
1423 # with a digit-period-space sequence.
1424 #
1425 # Whereas when we're inside a list (or sub-list), that line will be
1426 # treated as the start of a sub-list. What a kludge, huh? This is
1427 # an aspect of Markdown's syntax that's hard to parse perfectly
1428 # without resorting to mind-reading. Perhaps the solution is to
1429 # change the syntax rules such that sub-lists must start with a
1430 # starting cardinal number; e.g. "1." or "a.".
1431 self.list_level += 1
1432 self._last_li_endswith_two_eols = False
1433 list_str = list_str.rstrip('\n') + '\n'
1434 list_str = self._list_item_re.sub(self._list_item_sub, list_str)
1435 self.list_level -= 1
1436 return list_str
1437
1438 def _get_pygments_lexer(self, lexer_name):
1439 try:
1440 from pygments import lexers, util
1441 except ImportError:
1442 return None
1443 try:
1444 return lexers.get_lexer_by_name(lexer_name)
1445 except util.ClassNotFound:
1446 return None
1447
1448 def _color_with_pygments(self, codeblock, lexer, **formatter_opts):
1449 import pygments
1450 import pygments.formatters
1451
1452 class HtmlCodeFormatter(pygments.formatters.HtmlFormatter):
1453 def _wrap_code(self, inner):
1454 """A function for use in a Pygments Formatter which
1455 wraps in <code> tags.
1456 """
1457 yield 0, "<code>"
1458 for tup in inner:
1459 yield tup
1460 yield 0, "</code>"
1461
1462 def wrap(self, source, outfile):
1463 """Return the source with a code, pre, and div."""
1464 return self._wrap_div(self._wrap_pre(self._wrap_code(source)))
1465
1466 formatter_opts.setdefault("cssclass", "codehilite")
1467 formatter = HtmlCodeFormatter(**formatter_opts)
1468 return pygments.highlight(codeblock, lexer, formatter)
1469
1470 def _code_block_sub(self, match, is_fenced_code_block=False):
1471 lexer_name = None
1472 if is_fenced_code_block:
1473 lexer_name = match.group(1)
1474 if lexer_name:
1475 formatter_opts = self.extras['fenced-code-blocks'] or {}
1476 codeblock = match.group(2)
1477 codeblock = codeblock[:-1] # drop one trailing newline
1478 else:
1479 codeblock = match.group(1)
1480 codeblock = self._outdent(codeblock)
1481 codeblock = self._detab(codeblock)
1482 codeblock = codeblock.lstrip('\n') # trim leading newlines
1483 codeblock = codeblock.rstrip() # trim trailing whitespace
1484
1485 # Note: "code-color" extra is DEPRECATED.
1486 if "code-color" in self.extras and codeblock.startswith(":::"):
1487 lexer_name, rest = codeblock.split('\n', 1)
1488 lexer_name = lexer_name[3:].strip()
1489 codeblock = rest.lstrip("\n") # Remove lexer declaration line.
1490 formatter_opts = self.extras['code-color'] or {}
1491
1492 if lexer_name:
1493 lexer = self._get_pygments_lexer(lexer_name)
1494 if lexer:
1495 colored = self._color_with_pygments(codeblock, lexer,
1496 **formatter_opts)
1497 return "\n\n%s\n\n" % colored
1498
1499 codeblock = self._encode_code(codeblock)
1500 pre_class_str = self._html_class_str_from_tag("pre")
1501 code_class_str = self._html_class_str_from_tag("code")
1502 return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % (
1503 pre_class_str, code_class_str, codeblock)
1504
1505 def _html_class_str_from_tag(self, tag):
1506 """Get the appropriate ' class="..."' string (note the leading
1507 space), if any, for the given tag.
1508 """
1509 if "html-classes" not in self.extras:
1510 return ""
1511 try:
1512 html_classes_from_tag = self.extras["html-classes"]
1513 except TypeError:
1514 return ""
1515 else:
1516 if tag in html_classes_from_tag:
1517 return ' class="%s"' % html_classes_from_tag[tag]
1518 return ""
1519
1520 def _do_code_blocks(self, text):
1521 """Process Markdown `<pre><code>` blocks."""
1522 code_block_re = re.compile(r'''
1523 (?:\n\n|\A\n?)
1524 ( # $1 = the code block -- one or more lines, starting with a space/tab
1525 (?:
1526 (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces
1527 .*\n+
1528 )+
1529 )
1530 ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
1531 ''' % (self.tab_width, self.tab_width),
1532 re.M | re.X)
1533 return code_block_re.sub(self._code_block_sub, text)
1534
1535 _fenced_code_block_re = re.compile(r'''
1536 (?:\n\n|\A\n?)
1537 ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang
1538 (.*?) # $2 = code block content
1539 ^```[ \t]*\n # closing fence
1540 ''', re.M | re.X | re.S)
1541
1542 def _fenced_code_block_sub(self, match):
1543 return self._code_block_sub(match, is_fenced_code_block=True);
1544
1545 def _do_fenced_code_blocks(self, text):
1546 """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra)."""
1547 return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text)
1548
1549 # Rules for a code span:
1550 # - backslash escapes are not interpreted in a code span
1551 # - to include one or or a run of more backticks the delimiters must
1552 # be a longer run of backticks
1553 # - cannot start or end a code span with a backtick; pad with a
1554 # space and that space will be removed in the emitted HTML
1555 # See `test/tm-cases/escapes.text` for a number of edge-case
1556 # examples.
1557 _code_span_re = re.compile(r'''
1558 (?<!\\)
1559 (`+) # \1 = Opening run of `
1560 (?!`) # See Note A test/tm-cases/escapes.text
1561 (.+?) # \2 = The code block
1562 (?<!`)
1563 \1 # Matching closer
1564 (?!`)
1565 ''', re.X | re.S)
1566
1567 def _code_span_sub(self, match):
1568 c = match.group(2).strip(" \t")
1569 c = self._encode_code(c)
1570 return "<code>%s</code>" % c
1571
1572 def _do_code_spans(self, text):
1573 # * Backtick quotes are used for <code></code> spans.
1574 #
1575 # * You can use multiple backticks as the delimiters if you want to
1576 # include literal backticks in the code span. So, this input:
1577 #
1578 # Just type ``foo `bar` baz`` at the prompt.
1579 #
1580 # Will translate to:
1581 #
1582 # <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
1583 #
1584 # There's no arbitrary limit to the number of backticks you
1585 # can use as delimiter. If you need three consecutive backticks
1586 # in your code, use four for delimiters, etc.
1587 #
1588 # * You can use spaces to get literal backticks at the edges:
1589 #
1590 # ... type `` `bar` `` ...
1591 #
1592 # Turns to:
1593 #
1594 # ... type <code>`bar`</code> ...
1595 return self._code_span_re.sub(self._code_span_sub, text)
1596
1597 def _encode_code(self, text):
1598 """Encode/escape certain characters inside Markdown code runs.
1599 The point is that in code, these characters are literals,
1600 and lose their special Markdown meanings.
1601 """
1602 replacements = [
1603 # Encode all ampersands; HTML entities are not
1604 # entities within a Markdown code span.
1605 ('&', '&amp;'),
1606 # Do the angle bracket song and dance:
1607 ('<', '&lt;'),
1608 ('>', '&gt;'),
1609 ]
1610 for before, after in replacements:
1611 text = text.replace(before, after)
1612 hashed = _hash_text(text)
1613 self._escape_table[text] = hashed
1614 return hashed
1615
1616 _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S)
1617 _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S)
1618 _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S)
1619 _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S)
1620 def _do_italics_and_bold(self, text):
1621 # <strong> must go first:
1622 if "code-friendly" in self.extras:
1623 text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text)
1624 text = self._code_friendly_em_re.sub(r"<em>\1</em>", text)
1625 else:
1626 text = self._strong_re.sub(r"<strong>\2</strong>", text)
1627 text = self._em_re.sub(r"<em>\2</em>", text)
1628 return text
1629
1630 # "smarty-pants" extra: Very liberal in interpreting a single prime as an
1631 # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and
1632 # "twixt" can be written without an initial apostrophe. This is fine because
1633 # using scare quotes (single quotation marks) is rare.
1634 _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))")
1635 _contractions = ["tis", "twas", "twer", "neath", "o", "n",
1636 "round", "bout", "twixt", "nuff", "fraid", "sup"]
1637 def _do_smart_contractions(self, text):
1638 text = self._apostrophe_year_re.sub(r"&#8217;\1", text)
1639 for c in self._contractions:
1640 text = text.replace("'%s" % c, "&#8217;%s" % c)
1641 text = text.replace("'%s" % c.capitalize(),
1642 "&#8217;%s" % c.capitalize())
1643 return text
1644
1645 # Substitute double-quotes before single-quotes.
1646 _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)")
1647 _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)')
1648 _closing_single_quote_re = re.compile(r"(?<=\S)'")
1649 _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))')
1650 def _do_smart_punctuation(self, text):
1651 """Fancifies 'single quotes', "double quotes", and apostrophes.
1652 Converts --, ---, and ... into en dashes, em dashes, and ellipses.
1653
1654 Inspiration is: <http://daringfireball.net/projects/smartypants/>
1655 See "test/tm-cases/smarty_pants.text" for a full discussion of the
1656 support here and
1657 <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a
1658 discussion of some diversion from the original SmartyPants.
1659 """
1660 if "'" in text: # guard for perf
1661 text = self._do_smart_contractions(text)
1662 text = self._opening_single_quote_re.sub("&#8216;", text)
1663 text = self._closing_single_quote_re.sub("&#8217;", text)
1664
1665 if '"' in text: # guard for perf
1666 text = self._opening_double_quote_re.sub("&#8220;", text)
1667 text = self._closing_double_quote_re.sub("&#8221;", text)
1668
1669 text = text.replace("---", "&#8212;")
1670 text = text.replace("--", "&#8211;")
1671 text = text.replace("...", "&#8230;")
1672 text = text.replace(" . . . ", "&#8230;")
1673 text = text.replace(". . .", "&#8230;")
1674 return text
1675
1676 _block_quote_re = re.compile(r'''
1677 ( # Wrap whole match in \1
1678 (
1679 ^[ \t]*>[ \t]? # '>' at the start of a line
1680 .+\n # rest of the first line
1681 (.+\n)* # subsequent consecutive lines
1682 \n* # blanks
1683 )+
1684 )
1685 ''', re.M | re.X)
1686 _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M);
1687
1688 _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S)
1689 def _dedent_two_spaces_sub(self, match):
1690 return re.sub(r'(?m)^ ', '', match.group(1))
1691
1692 def _block_quote_sub(self, match):
1693 bq = match.group(1)
1694 bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting
1695 bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines
1696 bq = self._run_block_gamut(bq) # recurse
1697
1698 bq = re.sub('(?m)^', ' ', bq)
1699 # These leading spaces screw with <pre> content, so we need to fix that:
1700 bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq)
1701
1702 return "<blockquote>\n%s\n</blockquote>\n\n" % bq
1703
1704 def _do_block_quotes(self, text):
1705 if '>' not in text:
1706 return text
1707 return self._block_quote_re.sub(self._block_quote_sub, text)
1708
1709 def _form_paragraphs(self, text):
1710 # Strip leading and trailing lines:
1711 text = text.strip('\n')
1712
1713 # Wrap <p> tags.
1714 grafs = []
1715 for i, graf in enumerate(re.split(r"\n{2,}", text)):
1716 if graf in self.html_blocks:
1717 # Unhashify HTML blocks
1718 grafs.append(self.html_blocks[graf])
1719 else:
1720 cuddled_list = None
1721 if "cuddled-lists" in self.extras:
1722 # Need to put back trailing '\n' for `_list_item_re`
1723 # match at the end of the paragraph.
1724 li = self._list_item_re.search(graf + '\n')
1725 # Two of the same list marker in this paragraph: a likely
1726 # candidate for a list cuddled to preceding paragraph
1727 # text (issue 33). Note the `[-1]` is a quick way to
1728 # consider numeric bullets (e.g. "1." and "2.") to be
1729 # equal.
1730 if (li and len(li.group(2)) <= 3 and li.group("next_marker")
1731 and li.group("marker")[-1] == li.group("next_marker")[-1]):
1732 start = li.start()
1733 cuddled_list = self._do_lists(graf[start:]).rstrip("\n")
1734 assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>")
1735 graf = graf[:start]
1736
1737 # Wrap <p> tags.
1738 graf = self._run_span_gamut(graf)
1739 grafs.append("<p>" + graf.lstrip(" \t") + "</p>")
1740
1741 if cuddled_list:
1742 grafs.append(cuddled_list)
1743
1744 return "\n\n".join(grafs)
1745
1746 def _add_footnotes(self, text):
1747 if self.footnotes:
1748 footer = [
1749 '<div class="footnotes">',
1750 '<hr' + self.empty_element_suffix,
1751 '<ol>',
1752 ]
1753 for i, id in enumerate(self.footnote_ids):
1754 if i != 0:
1755 footer.append('')
1756 footer.append('<li id="fn-%s">' % id)
1757 footer.append(self._run_block_gamut(self.footnotes[id]))
1758 backlink = ('<a href="#fnref-%s" '
1759 'class="footnoteBackLink" '
1760 'title="Jump back to footnote %d in the text.">'
1761 '&#8617;</a>' % (id, i+1))
1762 if footer[-1].endswith("</p>"):
1763 footer[-1] = footer[-1][:-len("</p>")] \
1764 + '&nbsp;' + backlink + "</p>"
1765 else:
1766 footer.append("\n<p>%s</p>" % backlink)
1767 footer.append('</li>')
1768 footer.append('</ol>')
1769 footer.append('</div>')
1770 return text + '\n\n' + '\n'.join(footer)
1771 else:
1772 return text
1773
1774 # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
1775 # http://bumppo.net/projects/amputator/
1776 _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)')
1777 _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I)
1778 _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I)
1779
1780 def _encode_amps_and_angles(self, text):
1781 # Smart processing for ampersands and angle brackets that need
1782 # to be encoded.
1783 text = self._ampersand_re.sub('&amp;', text)
1784
1785 # Encode naked <'s
1786 text = self._naked_lt_re.sub('&lt;', text)
1787
1788 # Encode naked >'s
1789 # Note: Other markdown implementations (e.g. Markdown.pl, PHP
1790 # Markdown) don't do this.
1791 text = self._naked_gt_re.sub('&gt;', text)
1792 return text
1793
1794 def _encode_backslash_escapes(self, text):
1795 for ch, escape in list(self._escape_table.items()):
1796 text = text.replace("\\"+ch, escape)
1797 return text
1798
1799 _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I)
1800 def _auto_link_sub(self, match):
1801 g1 = match.group(1)
1802 return '<a href="%s">%s</a>' % (g1, g1)
1803
1804 _auto_email_link_re = re.compile(r"""
1805 <
1806 (?:mailto:)?
1807 (
1808 [-.\w]+
1809 \@
1810 [-\w]+(\.[-\w]+)*\.[a-z]+
1811 )
1812 >
1813 """, re.I | re.X | re.U)
1814 def _auto_email_link_sub(self, match):
1815 return self._encode_email_address(
1816 self._unescape_special_chars(match.group(1)))
1817
1818 def _do_auto_links(self, text):
1819 text = self._auto_link_re.sub(self._auto_link_sub, text)
1820 text = self._auto_email_link_re.sub(self._auto_email_link_sub, text)
1821 return text
1822
1823 def _encode_email_address(self, addr):
1824 # Input: an email address, e.g. "[email protected]"
1825 #
1826 # Output: the email address as a mailto link, with each character
1827 # of the address encoded as either a decimal or hex entity, in
1828 # the hopes of foiling most address harvesting spam bots. E.g.:
1829 #
1830 # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
1831 # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
1832 # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
1833 #
1834 # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
1835 # mailing list: <http://tinyurl.com/yu7ue>
1836 chars = [_xml_encode_email_char_at_random(ch)
1837 for ch in "mailto:" + addr]
1838 # Strip the mailto: from the visible part.
1839 addr = '<a href="%s">%s</a>' \
1840 % (''.join(chars), ''.join(chars[7:]))
1841 return addr
1842
1843 def _do_link_patterns(self, text):
1844 """Caveat emptor: there isn't much guarding against link
1845 patterns being formed inside other standard Markdown links, e.g.
1846 inside a [link def][like this].
1847
1848 Dev Notes: *Could* consider prefixing regexes with a negative
1849 lookbehind assertion to attempt to guard against this.
1850 """
1851 link_from_hash = {}
1852 for regex, repl in self.link_patterns:
1853 replacements = []
1854 for match in regex.finditer(text):
1855 if hasattr(repl, "__call__"):
1856 href = repl(match)
1857 else:
1858 href = match.expand(repl)
1859 replacements.append((match.span(), href))
1860 for (start, end), href in reversed(replacements):
1861 escaped_href = (
1862 href.replace('"', '&quot;') # b/c of attr quote
1863 # To avoid markdown <em> and <strong>:
1864 .replace('*', self._escape_table['*'])
1865 .replace('_', self._escape_table['_']))
1866 link = '<a href="%s">%s</a>' % (escaped_href, text[start:end])
1867 hash = _hash_text(link)
1868 link_from_hash[hash] = link
1869 text = text[:start] + hash + text[end:]
1870 for hash, link in list(link_from_hash.items()):
1871 text = text.replace(hash, link)
1872 return text
1873
1874 def _unescape_special_chars(self, text):
1875 # Swap back in all the special characters we've hidden.
1876 for ch, hash in list(self._escape_table.items()):
1877 text = text.replace(hash, ch)
1878 return text
1879
1880 def _outdent(self, text):
1881 # Remove one level of line-leading tabs or spaces
1882 return self._outdent_re.sub('', text)
1883
1884
1885 class MarkdownWithExtras(Markdown):
1886 """A markdowner class that enables most extras:
1887
1888 - footnotes
1889 - code-color (only has effect if 'pygments' Python module on path)
1890
1891 These are not included:
1892 - pyshell (specific to Python-related documenting)
1893 - code-friendly (because it *disables* part of the syntax)
1894 - link-patterns (because you need to specify some actual
1895 link-patterns anyway)
1896 """
1897 extras = ["footnotes", "code-color"]
1898
1899
1900 #---- internal support functions
1901
1902 class UnicodeWithAttrs(unicode):
1903 """A subclass of unicode used for the return value of conversion to
1904 possibly attach some attributes. E.g. the "toc_html" attribute when
1905 the "toc" extra is used.
1906 """
1907 metadata = None
1908 _toc = None
1909 def toc_html(self):
1910 """Return the HTML for the current TOC.
1911
1912 This expects the `_toc` attribute to have been set on this instance.
1913 """
1914 if self._toc is None:
1915 return None
1916
1917 def indent():
1918 return ' ' * (len(h_stack) - 1)
1919 lines = []
1920 h_stack = [0] # stack of header-level numbers
1921 for level, id, name in self._toc:
1922 if level > h_stack[-1]:
1923 lines.append("%s<ul>" % indent())
1924 h_stack.append(level)
1925 elif level == h_stack[-1]:
1926 lines[-1] += "</li>"
1927 else:
1928 while level < h_stack[-1]:
1929 h_stack.pop()
1930 if not lines[-1].endswith("</li>"):
1931 lines[-1] += "</li>"
1932 lines.append("%s</ul></li>" % indent())
1933 lines.append('%s<li><a href="#%s">%s</a>' % (
1934 indent(), id, name))
1935 while len(h_stack) > 1:
1936 h_stack.pop()
1937 if not lines[-1].endswith("</li>"):
1938 lines[-1] += "</li>"
1939 lines.append("%s</ul>" % indent())
1940 return '\n'.join(lines) + '\n'
1941 toc_html = property(toc_html)
1942
1943 ## {{{ http://code.activestate.com/recipes/577257/ (r1)
1944 import re
1945
1946 char_map = {u'À': 'A', u'Á': 'A', u'Â': 'A', u'Ã': 'A', u'Ä': 'Ae', u'Å': 'A', u'Æ': 'A', u'Ā': 'A', u'Ą': 'A', u'Ă': 'A', u'Ç': 'C', u'Ć': 'C', u'Č': 'C', u'Ĉ': 'C', u'Ċ': 'C', u'Ď': 'D', u'Đ': 'D', u'È': 'E', u'É': 'E', u'Ê': 'E', u'Ë': 'E', u'Ē': 'E', u'Ę': 'E', u'Ě': 'E', u'Ĕ': 'E', u'Ė': 'E', u'Ĝ': 'G', u'Ğ': 'G', u'Ġ': 'G', u'Ģ': 'G', u'Ĥ': 'H', u'Ħ': 'H', u'Ì': 'I', u'Í': 'I', u'Î': 'I', u'Ï': 'I', u'Ī': 'I', u'Ĩ': 'I', u'Ĭ': 'I', u'Į': 'I', u'İ': 'I', u'IJ': 'IJ', u'Ĵ': 'J', u'Ķ': 'K', u'Ľ': 'K', u'Ĺ': 'K', u'Ļ': 'K', u'Ŀ': 'K', u'Ł': 'L', u'Ñ': 'N', u'Ń': 'N', u'Ň': 'N', u'Ņ': 'N', u'Ŋ': 'N', u'Ò': 'O', u'Ó': 'O', u'Ô': 'O', u'Õ': 'O', u'Ö': 'Oe', u'Ø': 'O', u'Ō': 'O', u'Ő': 'O', u'Ŏ': 'O', u'Œ': 'OE', u'Ŕ': 'R', u'Ř': 'R', u'Ŗ': 'R', u'Ś': 'S', u'Ş': 'S', u'Ŝ': 'S', u'Ș': 'S', u'Š': 'S', u'Ť': 'T', u'Ţ': 'T', u'Ŧ': 'T', u'Ț': 'T', u'Ù': 'U', u'Ú': 'U', u'Û': 'U', u'Ü': 'Ue', u'Ū': 'U', u'Ů': 'U', u'Ű': 'U', u'Ŭ': 'U', u'Ũ': 'U', u'Ų': 'U', u'Ŵ': 'W', u'Ŷ': 'Y', u'Ÿ': 'Y', u'Ý': 'Y', u'Ź': 'Z', u'Ż': 'Z', u'Ž': 'Z', u'à': 'a', u'á': 'a', u'â': 'a', u'ã': 'a', u'ä': 'ae', u'ā': 'a', u'ą': 'a', u'ă': 'a', u'å': 'a', u'æ': 'ae', u'ç': 'c', u'ć': 'c', u'č': 'c', u'ĉ': 'c', u'ċ': 'c', u'ď': 'd', u'đ': 'd', u'è': 'e', u'é': 'e', u'ê': 'e', u'ë': 'e', u'ē': 'e', u'ę': 'e', u'ě': 'e', u'ĕ': 'e', u'ė': 'e', u'ƒ': 'f', u'ĝ': 'g', u'ğ': 'g', u'ġ': 'g', u'ģ': 'g', u'ĥ': 'h', u'ħ': 'h', u'ì': 'i', u'í': 'i', u'î': 'i', u'ï': 'i', u'ī': 'i', u'ĩ': 'i', u'ĭ': 'i', u'į': 'i', u'ı': 'i', u'ij': 'ij', u'ĵ': 'j', u'ķ': 'k', u'ĸ': 'k', u'ł': 'l', u'ľ': 'l', u'ĺ': 'l', u'ļ': 'l', u'ŀ': 'l', u'ñ': 'n', u'ń': 'n', u'ň': 'n', u'ņ': 'n', u'ʼn': 'n', u'ŋ': 'n', u'ò': 'o', u'ó': 'o', u'ô': 'o', u'õ': 'o', u'ö': 'oe', u'ø': 'o', u'ō': 'o', u'ő': 'o', u'ŏ': 'o', u'œ': 'oe', u'ŕ': 'r', u'ř': 'r', u'ŗ': 'r', u'ś': 's', u'š': 's', u'ť': 't', u'ù': 'u', u'ú': 'u', u'û': 'u', u'ü': 'ue', u'ū': 'u', u'ů': 'u', u'ű': 'u', u'ŭ': 'u', u'ũ': 'u', u'ų': 'u', u'ŵ': 'w', u'ÿ': 'y', u'ý': 'y', u'ŷ': 'y', u'ż': 'z', u'ź': 'z', u'ž': 'z', u'ß': 'ss', u'ſ': 'ss', u'Α': 'A', u'Ά': 'A', u'Ἀ': 'A', u'Ἁ': 'A', u'Ἂ': 'A', u'Ἃ': 'A', u'Ἄ': 'A', u'Ἅ': 'A', u'Ἆ': 'A', u'Ἇ': 'A', u'ᾈ': 'A', u'ᾉ': 'A', u'ᾊ': 'A', u'ᾋ': 'A', u'ᾌ': 'A', u'ᾍ': 'A', u'ᾎ': 'A', u'ᾏ': 'A', u'Ᾰ': 'A', u'Ᾱ': 'A', u'Ὰ': 'A', u'Ά': 'A', u'ᾼ': 'A', u'Β': 'B', u'Γ': 'G', u'Δ': 'D', u'Ε': 'E', u'Έ': 'E', u'Ἐ': 'E', u'Ἑ': 'E', u'Ἒ': 'E', u'Ἓ': 'E', u'Ἔ': 'E', u'Ἕ': 'E', u'Έ': 'E', u'Ὲ': 'E', u'Ζ': 'Z', u'Η': 'I', u'Ή': 'I', u'Ἠ': 'I', u'Ἡ': 'I', u'Ἢ': 'I', u'Ἣ': 'I', u'Ἤ': 'I', u'Ἥ': 'I', u'Ἦ': 'I', u'Ἧ': 'I', u'ᾘ': 'I', u'ᾙ': 'I', u'ᾚ': 'I', u'ᾛ': 'I', u'ᾜ': 'I', u'ᾝ': 'I', u'ᾞ': 'I', u'ᾟ': 'I', u'Ὴ': 'I', u'Ή': 'I', u'ῌ': 'I', u'Θ': 'TH', u'Ι': 'I', u'Ί': 'I', u'Ϊ': 'I', u'Ἰ': 'I', u'Ἱ': 'I', u'Ἲ': 'I', u'Ἳ': 'I', u'Ἴ': 'I', u'Ἵ': 'I', u'Ἶ': 'I', u'Ἷ': 'I', u'Ῐ': 'I', u'Ῑ': 'I', u'Ὶ': 'I', u'Ί': 'I', u'Κ': 'K', u'Λ': 'L', u'Μ': 'M', u'Ν': 'N', u'Ξ': 'KS', u'Ο': 'O', u'Ό': 'O', u'Ὀ': 'O', u'Ὁ': 'O', u'Ὂ': 'O', u'Ὃ': 'O', u'Ὄ': 'O', u'Ὅ': 'O', u'Ὸ': 'O', u'Ό': 'O', u'Π': 'P', u'Ρ': 'R', u'Ῥ': 'R', u'Σ': 'S', u'Τ': 'T', u'Υ': 'Y', u'Ύ': 'Y', u'Ϋ': 'Y', u'Ὑ': 'Y', u'Ὓ': 'Y', u'Ὕ': 'Y', u'Ὗ': 'Y', u'Ῠ': 'Y', u'Ῡ': 'Y', u'Ὺ': 'Y', u'Ύ': 'Y', u'Φ': 'F', u'Χ': 'X', u'Ψ': 'PS', u'Ω': 'O', u'Ώ': 'O', u'Ὠ': 'O', u'Ὡ': 'O', u'Ὢ': 'O', u'Ὣ': 'O', u'Ὤ': 'O', u'Ὥ': 'O', u'Ὦ': 'O', u'Ὧ': 'O', u'ᾨ': 'O', u'ᾩ': 'O', u'ᾪ': 'O', u'ᾫ': 'O', u'ᾬ': 'O', u'ᾭ': 'O', u'ᾮ': 'O', u'ᾯ': 'O', u'Ὼ': 'O', u'Ώ': 'O', u'ῼ': 'O', u'α': 'a', u'ά': 'a', u'ἀ': 'a', u'ἁ': 'a', u'ἂ': 'a', u'ἃ': 'a', u'ἄ': 'a', u'ἅ': 'a', u'ἆ': 'a', u'ἇ': 'a', u'ᾀ': 'a', u'ᾁ': 'a', u'ᾂ': 'a', u'ᾃ': 'a', u'ᾄ': 'a', u'ᾅ': 'a', u'ᾆ': 'a', u'ᾇ': 'a', u'ὰ': 'a', u'ά': 'a', u'ᾰ': 'a', u'ᾱ': 'a', u'ᾲ': 'a', u'ᾳ': 'a', u'ᾴ': 'a', u'ᾶ': 'a', u'ᾷ': 'a', u'β': 'b', u'γ': 'g', u'δ': 'd', u'ε': 'e', u'έ': 'e', u'ἐ': 'e', u'ἑ': 'e', u'ἒ': 'e', u'ἓ': 'e', u'ἔ': 'e', u'ἕ': 'e', u'ὲ': 'e', u'έ': 'e', u'ζ': 'z', u'η': 'i', u'ή': 'i', u'ἠ': 'i', u'ἡ': 'i', u'ἢ': 'i', u'ἣ': 'i', u'ἤ': 'i', u'ἥ': 'i', u'ἦ': 'i', u'ἧ': 'i', u'ᾐ': 'i', u'ᾑ': 'i', u'ᾒ': 'i', u'ᾓ': 'i', u'ᾔ': 'i', u'ᾕ': 'i', u'ᾖ': 'i', u'ᾗ': 'i', u'ὴ': 'i', u'ή': 'i', u'ῂ': 'i', u'ῃ': 'i', u'ῄ': 'i', u'ῆ': 'i', u'ῇ': 'i', u'θ': 'th', u'ι': 'i', u'ί': 'i', u'ϊ': 'i', u'ΐ': 'i', u'ἰ': 'i', u'ἱ': 'i', u'ἲ': 'i', u'ἳ': 'i', u'ἴ': 'i', u'ἵ': 'i', u'ἶ': 'i', u'ἷ': 'i', u'ὶ': 'i', u'ί': 'i', u'ῐ': 'i', u'ῑ': 'i', u'ῒ': 'i', u'ΐ': 'i', u'ῖ': 'i', u'ῗ': 'i', u'κ': 'k', u'λ': 'l', u'μ': 'm', u'ν': 'n', u'ξ': 'ks', u'ο': 'o', u'ό': 'o', u'ὀ': 'o', u'ὁ': 'o', u'ὂ': 'o', u'ὃ': 'o', u'ὄ': 'o', u'ὅ': 'o', u'ὸ': 'o', u'ό': 'o', u'π': 'p', u'ρ': 'r', u'ῤ': 'r', u'ῥ': 'r', u'σ': 's', u'ς': 's', u'τ': 't', u'υ': 'y', u'ύ': 'y', u'ϋ': 'y', u'ΰ': 'y', u'ὐ': 'y', u'ὑ': 'y', u'ὒ': 'y', u'ὓ': 'y', u'ὔ': 'y', u'ὕ': 'y', u'ὖ': 'y', u'ὗ': 'y', u'ὺ': 'y', u'ύ': 'y', u'ῠ': 'y', u'ῡ': 'y', u'ῢ': 'y', u'ΰ': 'y', u'ῦ': 'y', u'ῧ': 'y', u'φ': 'f', u'χ': 'x', u'ψ': 'ps', u'ω': 'o', u'ώ': 'o', u'ὠ': 'o', u'ὡ': 'o', u'ὢ': 'o', u'ὣ': 'o', u'ὤ': 'o', u'ὥ': 'o', u'ὦ': 'o', u'ὧ': 'o', u'ᾠ': 'o', u'ᾡ': 'o', u'ᾢ': 'o', u'ᾣ': 'o', u'ᾤ': 'o', u'ᾥ': 'o', u'ᾦ': 'o', u'ᾧ': 'o', u'ὼ': 'o', u'ώ': 'o', u'ῲ': 'o', u'ῳ': 'o', u'ῴ': 'o', u'ῶ': 'o', u'ῷ': 'o', u'¨': '', u'΅': '', u'᾿': '', u'῾': '', u'῍': '', u'῝': '', u'῎': '', u'῞': '', u'῏': '', u'῟': '', u'῀': '', u'῁': '', u'΄': '', u'΅': '', u'`': '', u'῭': '', u'ͺ': '', u'᾽': '', u'А': 'A', u'Б': 'B', u'В': 'V', u'Г': 'G', u'Д': 'D', u'Е': 'E', u'Ё': 'YO', u'Ж': 'ZH', u'З': 'Z', u'И': 'I', u'Й': 'J', u'К': 'K', u'Л': 'L', u'М': 'M', u'Н': 'N', u'О': 'O', u'П': 'P', u'Р': 'R', u'С': 'S', u'Т': 'T', u'У': 'U', u'Ф': 'F', u'Х': 'H', u'Ц': 'TS', u'Ч': 'CH', u'Ш': 'SH', u'Щ': 'SCH', u'Ы': 'YI', u'Э': 'E', u'Ю': 'YU', u'Я': 'YA', u'а': 'A', u'б': 'B', u'в': 'V', u'г': 'G', u'д': 'D', u'е': 'E', u'ё': 'YO', u'ж': 'ZH', u'з': 'Z', u'и': 'I', u'й': 'J', u'к': 'K', u'л': 'L', u'м': 'M', u'н': 'N', u'о': 'O', u'п': 'P', u'р': 'R', u'с': 'S', u'т': 'T', u'у': 'U', u'ф': 'F', u'х': 'H', u'ц': 'TS', u'ч': 'CH', u'ш': 'SH', u'щ': 'SCH', u'ы': 'YI', u'э': 'E', u'ю': 'YU', u'я': 'YA', u'Ъ': '', u'ъ': '', u'Ь': '', u'ь': '', u'ð': 'd', u'Ð': 'D', u'þ': 'th', u'Þ': 'TH',u'ა': 'a', u'ბ': 'b', u'გ': 'g', u'დ': 'd', u'ე': 'e', u'ვ': 'v', u'ზ': 'z', u'თ': 't', u'ი': 'i', u'კ': 'k', u'ლ': 'l', u'მ': 'm', u'ნ': 'n', u'ო': 'o', u'პ': 'p', u'ჟ': 'zh', u'რ': 'r', u'ს': 's', u'ტ': 't', u'უ': 'u', u'ფ': 'p', u'ქ': 'k', u'ღ': 'gh', u'ყ': 'q', u'შ': 'sh', u'ჩ': 'ch', u'ც': 'ts', u'ძ': 'dz', u'წ': 'ts', u'ჭ': 'ch', u'ხ': 'kh', u'ჯ': 'j', u'ჰ': 'h' }
1947
1948 def replace_char(m):
1949 char = m.group()
1950 if char_map.has_key(char):
1951 return char_map[char]
1952 else:
1953 return char
1954
1955 _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
1956
1957
1958 def _slugify(text, delim=u'-'):
1959 """Generates an ASCII-only slug."""
1960 result = []
1961 for word in _punct_re.split(text.lower()):
1962 word = word.encode('utf-8')
1963 if word:
1964 result.append(word)
1965 slugified = delim.join([i.decode('utf-8') for i in result])
1966 return re.sub('[^a-zA-Z0-9\\s\\-]{1}', replace_char, slugified).lower()
1967 ## end of http://code.activestate.com/recipes/577257/ }}}
1968
1969
1970 # From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549
1971 def _curry(*args, **kwargs):
1972 function, args = args[0], args[1:]
1973 def result(*rest, **kwrest):
1974 combined = kwargs.copy()
1975 combined.update(kwrest)
1976 return function(*args + rest, **combined)
1977 return result
1978
1979 # Recipe: regex_from_encoded_pattern (1.0)
1980 def _regex_from_encoded_pattern(s):
1981 """'foo' -> re.compile(re.escape('foo'))
1982 '/foo/' -> re.compile('foo')
1983 '/foo/i' -> re.compile('foo', re.I)
1984 """
1985 if s.startswith('/') and s.rfind('/') != 0:
1986 # Parse it: /PATTERN/FLAGS
1987 idx = s.rfind('/')
1988 pattern, flags_str = s[1:idx], s[idx+1:]
1989 flag_from_char = {
1990 "i": re.IGNORECASE,
1991 "l": re.LOCALE,
1992 "s": re.DOTALL,
1993 "m": re.MULTILINE,
1994 "u": re.UNICODE,
1995 }
1996 flags = 0
1997 for char in flags_str:
1998 try:
1999 flags |= flag_from_char[char]
2000 except KeyError:
2001 raise ValueError("unsupported regex flag: '%s' in '%s' "
2002 "(must be one of '%s')"
2003 % (char, s, ''.join(list(flag_from_char.keys()))))
2004 return re.compile(s[1:idx], flags)
2005 else: # not an encoded regex
2006 return re.compile(re.escape(s))
2007
2008 # Recipe: dedent (0.1.2)
2009 def _dedentlines(lines, tabsize=8, skip_first_line=False):
2010 """_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines
2011
2012 "lines" is a list of lines to dedent.
2013 "tabsize" is the tab width to use for indent width calculations.
2014 "skip_first_line" is a boolean indicating if the first line should
2015 be skipped for calculating the indent width and for dedenting.
2016 This is sometimes useful for docstrings and similar.
2017
2018 Same as dedent() except operates on a sequence of lines. Note: the
2019 lines list is modified **in-place**.
2020 """
2021 DEBUG = False
2022 if DEBUG:
2023 print("dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\
2024 % (tabsize, skip_first_line))
2025 indents = []
2026 margin = None
2027 for i, line in enumerate(lines):
2028 if i == 0 and skip_first_line: continue
2029 indent = 0
2030 for ch in line:
2031 if ch == ' ':
2032 indent += 1
2033 elif ch == '\t':
2034 indent += tabsize - (indent % tabsize)
2035 elif ch in '\r\n':
2036 continue # skip all-whitespace lines
2037 else:
2038 break
2039 else:
2040 continue # skip all-whitespace lines
2041 if DEBUG: print("dedent: indent=%d: %r" % (indent, line))
2042 if margin is None:
2043 margin = indent
2044 else:
2045 margin = min(margin, indent)
2046 if DEBUG: print("dedent: margin=%r" % margin)
2047
2048 if margin is not None and margin > 0:
2049 for i, line in enumerate(lines):
2050 if i == 0 and skip_first_line: continue
2051 removed = 0
2052 for j, ch in enumerate(line):
2053 if ch == ' ':
2054 removed += 1
2055 elif ch == '\t':
2056 removed += tabsize - (removed % tabsize)
2057 elif ch in '\r\n':
2058 if DEBUG: print("dedent: %r: EOL -> strip up to EOL" % line)
2059 lines[i] = lines[i][j:]
2060 break
2061 else:
2062 raise ValueError("unexpected non-whitespace char %r in "
2063 "line %r while removing %d-space margin"
2064 % (ch, line, margin))
2065 if DEBUG:
2066 print("dedent: %r: %r -> removed %d/%d"\
2067 % (line, ch, removed, margin))
2068 if removed == margin:
2069 lines[i] = lines[i][j+1:]
2070 break
2071 elif removed > margin:
2072 lines[i] = ' '*(removed-margin) + lines[i][j+1:]
2073 break
2074 else:
2075 if removed:
2076 lines[i] = lines[i][removed:]
2077 return lines
2078
2079 def _dedent(text, tabsize=8, skip_first_line=False):
2080 """_dedent(text, tabsize=8, skip_first_line=False) -> dedented text
2081
2082 "text" is the text to dedent.
2083 "tabsize" is the tab width to use for indent width calculations.
2084 "skip_first_line" is a boolean indicating if the first line should
2085 be skipped for calculating the indent width and for dedenting.
2086 This is sometimes useful for docstrings and similar.
2087
2088 textwrap.dedent(s), but don't expand tabs to spaces
2089 """
2090 lines = text.splitlines(1)
2091 _dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line)
2092 return ''.join(lines)
2093
2094
2095 class _memoized:
2096 """Decorator that caches a function's return value each time it is called.
2097 If called later with the same arguments, the cached value is returned, and
2098 not re-evaluated.
2099
2100 http://wiki.python.org/moin/PythonDecoratorLibrary
2101 """
2102 def __init__(self, func):
2103 self.func = func
2104 self.cache = {}
2105 def __call__(self, *args):
2106 try:
2107 return self.cache[args]
2108 except KeyError:
2109 self.cache[args] = value = self.func(*args)
2110 return value
2111 except TypeError:
2112 # uncachable -- for instance, passing a list as an argument.
2113 # Better to not cache than to blow up entirely.
2114 return self.func(*args)
2115 def __repr__(self):
2116 """Return the function's docstring."""
2117 return self.func.__doc__
2118
2119
2120 def _xml_oneliner_re_from_tab_width(tab_width):
2121 """Standalone XML processing instruction regex."""
2122 return re.compile(r"""
2123 (?:
2124 (?<=\n\n) # Starting after a blank line
2125 | # or
2126 \A\n? # the beginning of the doc
2127 )
2128 ( # save in $1
2129 [ ]{0,%d}
2130 (?:
2131 <\?\w+\b\s+.*?\?> # XML processing instruction
2132 |
2133 <\w+:\w+\b\s+.*?/> # namespaced single tag
2134 )
2135 [ \t]*
2136 (?=\n{2,}|\Z) # followed by a blank line or end of document
2137 )
2138 """ % (tab_width - 1), re.X)
2139 _xml_oneliner_re_from_tab_width = _memoized(_xml_oneliner_re_from_tab_width)
2140
2141 def _hr_tag_re_from_tab_width(tab_width):
2142 return re.compile(r"""
2143 (?:
2144 (?<=\n\n) # Starting after a blank line
2145 | # or
2146 \A\n? # the beginning of the doc
2147 )
2148 ( # save in \1
2149 [ ]{0,%d}
2150 <(hr) # start tag = \2
2151 \b # word break
2152 ([^<>])*? #
2153 /?> # the matching end tag
2154 [ \t]*
2155 (?=\n{2,}|\Z) # followed by a blank line or end of document
2156 )
2157 """ % (tab_width - 1), re.X)
2158 _hr_tag_re_from_tab_width = _memoized(_hr_tag_re_from_tab_width)
2159
2160
2161 def _xml_escape_attr(attr, skip_single_quote=True):
2162 """Escape the given string for use in an HTML/XML tag attribute.
2163
2164 By default this doesn't bother with escaping `'` to `&#39;`, presuming that
2165 the tag attribute is surrounded by double quotes.
2166 """
2167 escaped = (attr
2168 .replace('&', '&amp;')
2169 .replace('"', '&quot;')
2170 .replace('<', '&lt;')
2171 .replace('>', '&gt;'))
2172 if not skip_single_quote:
2173 escaped = escaped.replace("'", "&#39;")
2174 return escaped
2175
2176
2177 def _xml_encode_email_char_at_random(ch):
2178 r = random()
2179 # Roughly 10% raw, 45% hex, 45% dec.
2180 # '@' *must* be encoded. I [John Gruber] insist.
2181 # Issue 26: '_' must be encoded.
2182 if r > 0.9 and ch not in "@_":
2183 return ch
2184 elif r < 0.45:
2185 # The [1:] is to drop leading '0': 0x63 -> x63
2186 return '&#%s;' % hex(ord(ch))[1:]
2187 else:
2188 return '&#%s;' % ord(ch)
2189
2190
2191
2192 #---- mainline
2193
2194 class _NoReflowFormatter(optparse.IndentedHelpFormatter):
2195 """An optparse formatter that does NOT reflow the description."""
2196 def format_description(self, description):
2197 return description or ""
2198
2199 def _test():
2200 import doctest
2201 doctest.testmod()
2202
2203 def main(argv=None):
2204 if argv is None:
2205 argv = sys.argv
2206 if not logging.root.handlers:
2207 logging.basicConfig()
2208
2209 usage = "usage: %prog [PATHS...]"
2210 version = "%prog "+__version__
2211 parser = optparse.OptionParser(prog="markdown2", usage=usage,
2212 version=version, description=cmdln_desc,
2213 formatter=_NoReflowFormatter())
2214 parser.add_option("-v", "--verbose", dest="log_level",
2215 action="store_const", const=logging.DEBUG,
2216 help="more verbose output")
2217 parser.add_option("--encoding",
2218 help="specify encoding of text content")
2219 parser.add_option("--html4tags", action="store_true", default=False,
2220 help="use HTML 4 style for empty element tags")
2221 parser.add_option("-s", "--safe", metavar="MODE", dest="safe_mode",
2222 help="sanitize literal HTML: 'escape' escapes "
2223 "HTML meta chars, 'replace' replaces with an "
2224 "[HTML_REMOVED] note")
2225 parser.add_option("-x", "--extras", action="append",
2226 help="Turn on specific extra features (not part of "
2227 "the core Markdown spec). See above.")
2228 parser.add_option("--use-file-vars",
2229 help="Look for and use Emacs-style 'markdown-extras' "
2230 "file var to turn on extras. See "
2231 "<https://github.com/trentm/python-markdown2/wiki/Extras>")
2232 parser.add_option("--link-patterns-file",
2233 help="path to a link pattern file")
2234 parser.add_option("--self-test", action="store_true",
2235 help="run internal self-tests (some doctests)")
2236 parser.add_option("--compare", action="store_true",
2237 help="run against Markdown.pl as well (for testing)")
2238 parser.set_defaults(log_level=logging.INFO, compare=False,
2239 encoding="utf-8", safe_mode=None, use_file_vars=False)
2240 opts, paths = parser.parse_args()
2241 log.setLevel(opts.log_level)
2242
2243 if opts.self_test:
2244 return _test()
2245
2246 if opts.extras:
2247 extras = {}
2248 for s in opts.extras:
2249 splitter = re.compile("[,;: ]+")
2250 for e in splitter.split(s):
2251 if '=' in e:
2252 ename, earg = e.split('=', 1)
2253 try:
2254 earg = int(earg)
2255 except ValueError:
2256 pass
2257 else:
2258 ename, earg = e, None
2259 extras[ename] = earg
2260 else:
2261 extras = None
2262
2263 if opts.link_patterns_file:
2264 link_patterns = []
2265 f = open(opts.link_patterns_file)
2266 try:
2267 for i, line in enumerate(f.readlines()):
2268 if not line.strip(): continue
2269 if line.lstrip().startswith("#"): continue
2270 try:
2271 pat, href = line.rstrip().rsplit(None, 1)
2272 except ValueError:
2273 raise MarkdownError("%s:%d: invalid link pattern line: %r"
2274 % (opts.link_patterns_file, i+1, line))
2275 link_patterns.append(
2276 (_regex_from_encoded_pattern(pat), href))
2277 finally:
2278 f.close()
2279 else:
2280 link_patterns = None
2281
2282 from os.path import join, dirname, abspath, exists
2283 markdown_pl = join(dirname(dirname(abspath(__file__))), "test",
2284 "Markdown.pl")
2285 if not paths:
2286 paths = ['-']
2287 for path in paths:
2288 if path == '-':
2289 text = sys.stdin.read()
2290 else:
2291 fp = codecs.open(path, 'r', opts.encoding)
2292 text = fp.read()
2293 fp.close()
2294 if opts.compare:
2295 from subprocess import Popen, PIPE
2296 print("==== Markdown.pl ====")
2297 p = Popen('perl %s' % markdown_pl, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True)
2298 p.stdin.write(text.encode('utf-8'))
2299 p.stdin.close()
2300 perl_html = p.stdout.read().decode('utf-8')
2301 if py3:
2302 sys.stdout.write(perl_html)
2303 else:
2304 sys.stdout.write(perl_html.encode(
2305 sys.stdout.encoding or "utf-8", 'xmlcharrefreplace'))
2306 print("==== markdown2.py ====")
2307 html = markdown(text,
2308 html4tags=opts.html4tags,
2309 safe_mode=opts.safe_mode,
2310 extras=extras, link_patterns=link_patterns,
2311 use_file_vars=opts.use_file_vars)
2312 if py3:
2313 sys.stdout.write(html)
2314 else:
2315 sys.stdout.write(html.encode(
2316 sys.stdout.encoding or "utf-8", 'xmlcharrefreplace'))
2317 if extras and "toc" in extras:
2318 log.debug("toc_html: " +
2319 html.toc_html.encode(sys.stdout.encoding or "utf-8", 'xmlcharrefreplace'))
2320 if opts.compare:
2321 test_dir = join(dirname(dirname(abspath(__file__))), "test")
2322 if exists(join(test_dir, "test_markdown2.py")):
2323 sys.path.insert(0, test_dir)
2324 from test_markdown2 import norm_html_from_html
2325 norm_html = norm_html_from_html(html)
2326 norm_perl_html = norm_html_from_html(perl_html)
2327 else:
2328 norm_html = html
2329 norm_perl_html = perl_html
2330 print("==== match? %r ====" % (norm_perl_html == norm_html))
2331
2332
2333 template_html = u'''<!DOCTYPE html>
2334 <!--
2335 Backdoc is a tool for backbone-like documentation generation.
2336 Backdoc main goal is to help to generate one page documentation from one markdown source file.
2337
2338 https://github.com/chibisov/backdoc
2339 -->
2340 <html lang="ru">
2341 <head>
2342 <meta charset="UTF-8"/>
2343 <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
2344 <meta name="HandheldFriendly" content="true" />
2345 <title><!-- title --></title>
2346
2347 <!-- Bootstrap -->
2348 <style type="text/css">
2349 /*!
2350 * Bootstrap v3.0.0
2351 *
2352 * Copyright 2013 Twitter, Inc
2353 * Licensed under the Apache License v2.0
2354 * http://www.apache.org/licenses/LICENSE-2.0
2355 *
2356 * Designed and built with all the love in the world by @mdo and @fat.
2357 *//*! normalize.css v2.1.0 | MIT License | git.io/normalize */
2358 article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,video{display:inline-block}audio:not([controls]){display:none;height:0}[hidden]{display:none}html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}a:focus{outline:thin dotted}a:active,a:hover{outline:0}h1{margin:.67em 0;font-size:2em}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}hr{height:0;-moz-box-sizing:content-box;box-sizing:content-box}mark{color:#000;background:#ff0}code,kbd,pre,samp{font-family:monospace,serif;font-size:1em}pre{white-space:pre-wrap}q{quotes:"\201C" "\201D" "\2018" "\2019"}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:0}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid #c0c0c0}legend{padding:0;border:0}button,input,select,textarea{margin:0;font-family:inherit;font-size:100%}button,input{line-height:normal}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}button[disabled],html input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{padding:0;box-sizing:border-box}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:2cm .5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}.navbar{display:none}.table td,.table th{background-color:#fff!important}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:62.5%;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.428571429;color:#333;background-color:#fff}input,button,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#428bca;text-decoration:none}a:hover,a:focus{color:#2a6496;text-decoration:underline}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}img{vertical-align:middle}.img-responsive{display:inline-block;height:auto;max-width:100%}.img-rounded{border-radius:6px}.img-circle{border-radius:500px}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16.099999999999998px;font-weight:200;line-height:1.4}@media(min-width:768px){.lead{font-size:21px}}small{font-size:85%}cite{font-style:normal}.text-muted{color:#999}.text-primary{color:#428bca}.text-warning{color:#c09853}.text-danger{color:#b94a48}.text-success{color:#468847}.text-info{color:#3a87ad}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:500;line-height:1.1}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small{font-weight:normal;line-height:1;color:#999}h1,h2,h3{margin-top:20px;margin-bottom:10px}h4,h5,h6{margin-top:10px;margin-bottom:10px}h1,.h1{font-size:38px}h2,.h2{font-size:32px}h3,.h3{font-size:24px}h4,.h4{font-size:18px}h5,.h5{font-size:14px}h6,.h6{font-size:12px}h1 small,.h1 small{font-size:24px}h2 small,.h2 small{font-size:18px}h3 small,.h3 small,h4 small,.h4 small{font-size:14px}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ul,ol{margin-top:0;margin-bottom:10px}ul ul,ol ul,ul ol,ol ol{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-bottom:20px}dt,dd{line-height:1.428571429}dt{font-weight:bold}dd{margin-left:0}.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}abbr.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;border-left:5px solid #eee}blockquote p{font-size:17.5px;font-weight:300;line-height:1.25}blockquote p:last-child{margin-bottom:0}blockquote small{display:block;line-height:1.428571429;color:#999}blockquote small:before{content:'\2014 \00A0'}blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}blockquote.pull-right p,blockquote.pull-right small{text-align:right}blockquote.pull-right small:before{content:''}blockquote.pull-right small:after{content:'\00A0 \2014'}q:before,q:after,blockquote:before,blockquote:after{content:""}address{display:block;margin-bottom:20px;font-style:normal;line-height:1.428571429}code,pre{font-family:Monaco,Menlo,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;white-space:nowrap;background-color:#f9f2f4;border-radius:4px}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.428571429;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre.prettyprint{margin-bottom:20px}pre code{padding:0;color:inherit;white-space:pre-wrap;background-color:transparent;border:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{margin-right:auto;margin-left:auto}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}@media(min-width:768px){.row{margin-right:-15px;margin-left:-15px}}.row .row{margin-right:-15px;margin-left:-15px}.col-1,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-10,.col-11,.col-12,.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12,.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-1,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-10,.col-11,.col-12{float:left}.col-1{width:8.333333333333332%}.col-2{width:16.666666666666664%}.col-3{width:25%}.col-4{width:33.33333333333333%}.col-5{width:41.66666666666667%}.col-6{width:50%}.col-7{width:58.333333333333336%}.col-8{width:66.66666666666666%}.col-9{width:75%}.col-10{width:83.33333333333334%}.col-11{width:91.66666666666666%}.col-12{width:100%}@media(min-width:768px){.container{max-width:728px}.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12{float:left}.col-sm-1{width:8.333333333333332%}.col-sm-2{width:16.666666666666664%}.col-sm-3{width:25%}.col-sm-4{width:33.33333333333333%}.col-sm-5{width:41.66666666666667%}.col-sm-6{width:50%}.col-sm-7{width:58.333333333333336%}.col-sm-8{width:66.66666666666666%}.col-sm-9{width:75%}.col-sm-10{width:83.33333333333334%}.col-sm-11{width:91.66666666666666%}.col-sm-12{width:100%}.col-push-1{left:8.333333333333332%}.col-push-2{left:16.666666666666664%}.col-push-3{left:25%}.col-push-4{left:33.33333333333333%}.col-push-5{left:41.66666666666667%}.col-push-6{left:50%}.col-push-7{left:58.333333333333336%}.col-push-8{left:66.66666666666666%}.col-push-9{left:75%}.col-push-10{left:83.33333333333334%}.col-push-11{left:91.66666666666666%}.col-pull-1{right:8.333333333333332%}.col-pull-2{right:16.666666666666664%}.col-pull-3{right:25%}.col-pull-4{right:33.33333333333333%}.col-pull-5{right:41.66666666666667%}.col-pull-6{right:50%}.col-pull-7{right:58.333333333333336%}.col-pull-8{right:66.66666666666666%}.col-pull-9{right:75%}.col-pull-10{right:83.33333333333334%}.col-pull-11{right:91.66666666666666%}}@media(min-width:992px){.container{max-width:940px}.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{float:left}.col-lg-1{width:8.333333333333332%}.col-lg-2{width:16.666666666666664%}.col-lg-3{width:25%}.col-lg-4{width:33.33333333333333%}.col-lg-5{width:41.66666666666667%}.col-lg-6{width:50%}.col-lg-7{width:58.333333333333336%}.col-lg-8{width:66.66666666666666%}.col-lg-9{width:75%}.col-lg-10{width:83.33333333333334%}.col-lg-11{width:91.66666666666666%}.col-lg-12{width:100%}.col-offset-1{margin-left:8.333333333333332%}.col-offset-2{margin-left:16.666666666666664%}.col-offset-3{margin-left:25%}.col-offset-4{margin-left:33.33333333333333%}.col-offset-5{margin-left:41.66666666666667%}.col-offset-6{margin-left:50%}.col-offset-7{margin-left:58.333333333333336%}.col-offset-8{margin-left:66.66666666666666%}.col-offset-9{margin-left:75%}.col-offset-10{margin-left:83.33333333333334%}.col-offset-11{margin-left:91.66666666666666%}}@media(min-width:1200px){.container{max-width:1170px}}table{max-width:100%;background-color:transparent}th{text-align:left}.table{width:100%;margin-bottom:20px}.table thead>tr>th,.table tbody>tr>th,.table tfoot>tr>th,.table thead>tr>td,.table tbody>tr>td,.table tfoot>tr>td{padding:8px;line-height:1.428571429;vertical-align:top;border-top:1px solid #ddd}.table thead>tr>th{vertical-align:bottom}.table caption+thead tr:first-child th,.table colgroup+thead tr:first-child th,.table thead:first-child tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child td{border-top:0}.table tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed thead>tr>th,.table-condensed tbody>tr>th,.table-condensed tfoot>tr>th,.table-condensed thead>tr>td,.table-condensed tbody>tr>td,.table-condensed tfoot>tr>td{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td{border:1px solid #ddd}.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th{background-color:#f5f5f5}table col[class^="col-"]{display:table-column;float:none}table td[class^="col-"],table th[class^="col-"]{display:table-cell;float:none}.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th{background-color:#f5f5f5}.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th{background-color:#dff0d8;border-color:#d6e9c6}.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th{background-color:#f2dede;border-color:#eed3d7}.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th{background-color:#fcf8e3;border-color:#fbeed5}.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td{background-color:#d0e9c6;border-color:#c9e2b3}.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td{background-color:#ebcccc;border-color:#e6c1c7}.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td{background-color:#faf2cc;border-color:#f8e5be}fieldset{padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;margin-bottom:5px;font-weight:bold}input[type="search"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type="radio"],input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type="file"]{display:block}select[multiple],select[size]{height:auto}select optgroup{font-family:inherit;font-size:inherit;font-style:inherit}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}input[type="number"]::-webkit-outer-spin-button,input[type="number"]::-webkit-inner-spin-button{height:auto}.form-control:-moz-placeholder{color:#999}.form-control::-moz-placeholder{color:#999}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control{display:block;width:100%;height:38px;padding:8px 12px;font-size:14px;line-height:1.428571429;color:#555;vertical-align:middle;background-color:#fff;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:rgba(82,168,236,0.8);outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee}textarea.form-control{height:auto}.form-group{margin-bottom:15px}.radio,.checkbox{display:block;min-height:20px;padding-left:20px;margin-top:10px;margin-bottom:10px;vertical-align:middle}.radio label,.checkbox label{display:inline;margin-bottom:0;font-weight:normal;cursor:pointer}.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"]{float:left;margin-left:-20px}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;font-weight:normal;vertical-align:middle;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}.form-control.input-large{height:56px;padding:14px 16px;font-size:18px;border-radius:6px}.form-control.input-small{height:30px;padding:5px 10px;font-size:12px;border-radius:3px}select.input-large{height:56px;line-height:56px}select.input-small{height:30px;line-height:30px}.has-warning .help-block,.has-warning .control-label{color:#c09853}.has-warning .form-control{padding-right:32px;border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-warning .form-control:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.has-warning .input-group-addon{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.has-error .help-block,.has-error .control-label{color:#b94a48}.has-error .form-control{padding-right:32px;border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-error .form-control:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.has-error .input-group-addon{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.has-success .help-block,.has-success .control-label{color:#468847}.has-success .form-control{padding-right:32px;border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-success .form-control:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.has-success .input-group-addon{color:#468847;background-color:#dff0d8;border-color:#468847}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}.input-group{display:table;border-collapse:separate}.input-group.col{float:none;padding-right:0;padding-left:0}.input-group .form-control{width:100%;margin-bottom:0}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:8px 12px;font-size:14px;font-weight:normal;line-height:1.428571429;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.input-group-addon.input-small{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-large{padding:14px 16px;font-size:18px;border-radius:6px}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-4px}.input-group-btn>.btn:hover,.input-group-btn>.btn:active{z-index:2}.form-inline .form-control,.form-inline .radio,.form-inline .checkbox{display:inline-block}.form-inline .radio,.form-inline .checkbox{margin-top:0;margin-bottom:0}.form-horizontal .control-label{padding-top:6px}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}@media(min-width:768px){.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}}.form-horizontal .form-group .row{margin-right:-15px;margin-left:-15px}@media(min-width:768px){.form-horizontal .control-label{text-align:right}}.btn{display:inline-block;padding:8px 12px;margin-bottom:0;font-size:14px;font-weight:500;line-height:1.428571429;text-align:center;white-space:nowrap;vertical-align:middle;cursor:pointer;border:1px solid transparent;border-radius:4px}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#fff;text-decoration:none}.btn:active,.btn.active{outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{pointer-events:none;cursor:default;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none}.btn-default{color:#fff;background-color:#474949;border-color:#474949}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active{background-color:#3a3c3c;border-color:#2e2f2f}.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active{background-color:#474949;border-color:#474949}.btn-primary{color:#fff;background-color:#428bca;border-color:#428bca}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active{background-color:#357ebd;border-color:#3071a9}.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#428bca}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#f0ad4e}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active{background-color:#eea236;border-color:#ec971f}.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#f0ad4e}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d9534f}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active{background-color:#d43f3a;border-color:#c9302c}.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d9534f}.btn-success{color:#fff;background-color:#5cb85c;border-color:#5cb85c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active{background-color:#4cae4c;border-color:#449d44}.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#5cb85c}.btn-info{color:#fff;background-color:#5bc0de;border-color:#5bc0de}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active{background-color:#46b8da;border-color:#31b0d5}.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#5bc0de}.btn-link{font-weight:normal;color:#428bca;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus{color:#333;text-decoration:none}.btn-large{padding:14px 16px;font-size:18px;border-radius:6px}.btn-small{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%;padding-right:0;padding-left:0}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid #000;border-right:4px solid transparent;border-left:4px solid transparent;content:""}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,0.175);box-shadow:0 6px 12px rgba(0,0,0,0.175);background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:1.428571429;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{color:#fff;text-decoration:none;background-color:#357ebd;background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#357ebd));background-image:-webkit-linear-gradient(top,#428bca,0%,#357ebd,100%);background-image:-moz-linear-gradient(top,#428bca 0,#357ebd 100%);background-image:linear-gradient(to bottom,#428bca 0,#357ebd 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff357ebd',GradientType=0)}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#357ebd;background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#357ebd));background-image:-webkit-linear-gradient(top,#428bca,0%,#357ebd,100%);background-image:-moz-linear-gradient(top,#428bca 0,#357ebd 100%);background-image:linear-gradient(to bottom,#428bca 0,#357ebd 100%);background-repeat:repeat-x;outline:0;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff357ebd',GradientType=0)}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.428571429;color:#999}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}.list-group{padding-left:0;margin-bottom:20px;background-color:#fff}.list-group-item{position:relative;display:block;padding:10px 30px 10px 15px;margin-bottom:-1px;border:1px solid #ddd}.list-group-item:first-child{border-top-right-radius:4px;border-top-left-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.list-group-item>.badge{float:right;margin-right:-15px}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item .list-group-item-text{color:#555}a.list-group-item:hover,a.list-group-item:focus{text-decoration:none;background-color:#f5f5f5}a.list-group-item.active{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca}a.list-group-item.active .list-group-item-heading{color:inherit}a.list-group-item.active .list-group-item-text{color:#e1edf7}.panel{padding:15px;margin-bottom:20px;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,0.05);box-shadow:0 1px 1px rgba(0,0,0,0.05)}.panel-heading{padding:10px 15px;margin:-15px -15px 15px;background-color:#f5f5f5;border-bottom:1px solid #ddd;border-top-right-radius:3px;border-top-left-radius:3px}.panel-title{margin-top:0;margin-bottom:0;font-size:17.5px;font-weight:500}.panel-footer{padding:10px 15px;margin:15px -15px -15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel-primary{border-color:#428bca}.panel-primary .panel-heading{color:#fff;background-color:#428bca;border-color:#428bca}.panel-success{border-color:#d6e9c6}.panel-success .panel-heading{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.panel-warning{border-color:#fbeed5}.panel-warning .panel-heading{color:#c09853;background-color:#fcf8e3;border-color:#fbeed5}.panel-danger{border-color:#eed3d7}.panel-danger .panel-heading{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.panel-info{border-color:#bce8f1}.panel-info .panel-heading{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.list-group-flush{margin:15px -15px -15px}.list-group-flush .list-group-item{border-width:1px 0}.list-group-flush .list-group-item:first-child{border-top-right-radius:0;border-top-left-radius:0}.list-group-flush .list-group-item:last-child{border-bottom:0}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.well-large{padding:24px;border-radius:6px}.well-small{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:bold;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#999}.nav>li.disabled>a:hover,.nav>li.disabled>a:focus{color:#999;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav>li+.nav-header{margin-top:9px}.nav.open>a,.nav.open>a:hover,.nav.open>a:focus{color:#fff;background-color:#428bca;border-color:#428bca}.nav.open>a .caret,.nav.open>a:hover .caret,.nav.open>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}.nav>.pull-right{float:right}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.428571429;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee}.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{display:table-cell;float:none;width:1%}.nav-tabs.nav-justified>li>a{text-align:center}.nav-tabs.nav-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs.nav-justified>.active>a{border-bottom-color:#fff}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:5px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus{color:#fff;background-color:#428bca}.nav-stacked>li{float:none}.nav-stacked>li+li>a{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{display:table-cell;float:none;width:1%}.nav-justified>li>a{text-align:center}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs-justified>.active>a{border-bottom-color:#fff}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tab-content>.tab-pane,.pill-content>.pill-pane{display:none}.tab-content>.active,.pill-content>.active{display:block}.nav .caret{border-top-color:#428bca;border-bottom-color:#428bca}.nav a:hover .caret{border-top-color:#2a6496;border-bottom-color:#2a6496}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.navbar{position:relative;min-height:50px;padding-right:15px;padding-left:15px;margin-bottom:20px;background-color:#eee;border-radius:4px}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar-nav{margin-top:10px;margin-bottom:15px}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px;line-height:20px;color:#777;border-radius:4px}.navbar-nav>li>a:hover,.navbar-nav>li>a:focus{color:#333;background-color:transparent}.navbar-nav>.active>a,.navbar-nav>.active>a:hover,.navbar-nav>.active>a:focus{color:#555;background-color:#d5d5d5}.navbar-nav>.disabled>a,.navbar-nav>.disabled>a:hover,.navbar-nav>.disabled>a:focus{color:#ccc;background-color:transparent}.navbar-nav.pull-right{width:100%}.navbar-static-top{border-radius:0}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;border-radius:0}.navbar-fixed-top{top:0}.navbar-fixed-bottom{bottom:0;margin-bottom:0}.navbar-brand{display:block;max-width:200px;padding:15px 15px;margin-right:auto;margin-left:auto;font-size:18px;font-weight:500;line-height:20px;color:#777;text-align:center}.navbar-brand:hover,.navbar-brand:focus{color:#5e5e5e;text-decoration:none;background-color:transparent}.navbar-toggle{position:absolute;top:9px;right:10px;width:48px;height:32px;padding:8px 12px;background-color:transparent;border:1px solid #ddd;border-radius:4px}.navbar-toggle:hover,.navbar-toggle:focus{background-color:#ddd}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;background-color:#ccc;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}.navbar-form{margin-top:6px;margin-bottom:6px}.navbar-form .form-control,.navbar-form .radio,.navbar-form .checkbox{display:inline-block}.navbar-form .radio,.navbar-form .checkbox{margin-top:0;margin-bottom:0}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-nav>.dropdown>a:hover .caret,.navbar-nav>.dropdown>a:focus .caret{border-top-color:#333;border-bottom-color:#333}.navbar-nav>.open>a,.navbar-nav>.open>a:hover,.navbar-nav>.open>a:focus{color:#555;background-color:#d5d5d5}.navbar-nav>.open>a .caret,.navbar-nav>.open>a:hover .caret,.navbar-nav>.open>a:focus .caret{border-top-color:#555;border-bottom-color:#555}.navbar-nav>.dropdown>a .caret{border-top-color:#777;border-bottom-color:#777}.navbar-nav.pull-right>li>.dropdown-menu,.navbar-nav>li>.dropdown-menu.pull-right{right:0;left:auto}.navbar-inverse{background-color:#222}.navbar-inverse .navbar-brand{color:#999}.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .navbar-nav>li>a{color:#999}.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.dropdown>a:hover .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .navbar-nav>.dropdown>a .caret{border-top-color:#999;border-bottom-color:#999}.navbar-inverse .navbar-nav>.open>a .caret,.navbar-inverse .navbar-nav>.open>a:hover .caret,.navbar-inverse .navbar-nav>.open>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}@media screen and (min-width:768px){.navbar-brand{float:left;margin-right:5px;margin-left:-15px}.navbar-nav{float:left;margin-top:0;margin-bottom:0}.navbar-nav>li{float:left}.navbar-nav>li>a{border-radius:0}.navbar-nav.pull-right{float:right;width:auto}.navbar-toggle{position:relative;top:auto;left:auto;display:none}.nav-collapse.collapse{display:block!important;height:auto!important;overflow:visible!important}}.navbar-btn{margin-top:6px}.navbar-text{margin-top:15px;margin-bottom:15px}.navbar-link{color:#777}.navbar-link:hover{color:#333}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover{color:#fff}.btn .caret{border-top-color:#fff}.dropup .btn .caret{border-bottom-color:#fff}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:active,.btn-group-vertical>.btn:active{z-index:2}.btn-group .btn+.btn{margin-left:-1px}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar .btn-group{float:left}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group,.btn-toolbar>.btn-group+.btn-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-large+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn .caret{margin-left:0}.btn-large .caret{border-width:5px}.dropup .btn-large .caret{border-bottom-width:5px}.btn-group-vertical>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn+.btn{margin-top:-1px}.btn-group-vertical .btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical .btn:first-child{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical .btn:last-child{border-top-right-radius:0;border-top-left-radius:0}.btn-group-justified{display:table;width:100%}.btn-group-justified .btn{display:table-cell;float:none;width:1%}.btn-group[data-toggle="buttons"]>.btn>input[type="radio"],.btn-group[data-toggle="buttons"]>.btn>input[type="checkbox"]{display:none}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#999}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{float:left;padding:4px 12px;line-height:1.428571429;text-decoration:none;background-color:#fff;border:1px solid #ddd;border-left-width:0}.pagination>li:first-child>a,.pagination>li:first-child>span{border-left-width:1px;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:hover,.pagination>li>a:focus,.pagination>.active>a,.pagination>.active>span{background-color:#f5f5f5}.pagination>.active>a,.pagination>.active>span{color:#999;cursor:default}.pagination>.disabled>span,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#999;cursor:not-allowed;background-color:#fff}.pagination-large>li>a,.pagination-large>li>span{padding:14px 16px;font-size:18px}.pagination-large>li:first-child>a,.pagination-large>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-large>li:last-child>a,.pagination-large>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-small>li>a,.pagination-small>li>span{padding:5px 10px;font-size:12px}.pagination-small>li:first-child>a,.pagination-small>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-small>li:last-child>a,.pagination-small>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#f5f5f5}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;cursor:not-allowed;background-color:#fff}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;display:none;overflow:auto;overflow-y:scroll}.modal.fade .modal-dialog{-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);transform:translate(0,-25%);-webkit-transition:-webkit-transform .3s ease-out;-moz-transition:-moz-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out}.modal.fade.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.modal-dialog{position:relative;top:0;right:0;left:0;z-index:1050;width:auto;padding:10px}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,0.5);box-shadow:0 3px 9px rgba(0,0,0,0.5);background-clip:padding-box}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1030;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.fade.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{min-height:16.428571429px;padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.428571429}.modal-body{position:relative;padding:20px}.modal-footer{padding:19px 20px 20px;margin-top:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}@media screen and (min-width:768px){.modal-dialog{right:auto;left:50%;width:560px;padding-top:30px;padding-bottom:30px;margin-left:-280px}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,0.5);box-shadow:0 5px 15px rgba(0,0,0,0.5)}}.tooltip{position:absolute;z-index:1030;display:block;font-size:12px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.tooltip.in{opacity:1;filter:alpha(opacity=100)}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:rgba(0,0,0,0.9);border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.top-left .tooltip-arrow{bottom:0;left:5px;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.top-right .tooltip-arrow{right:5px;bottom:0;border-top-color:rgba(0,0,0,0.9);border-width:5px 5px 0}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:rgba(0,0,0,0.9);border-width:5px 5px 5px 0}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:rgba(0,0,0,0.9);border-width:5px 0 5px 5px}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.tooltip.bottom-left .tooltip-arrow{top:0;left:5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.tooltip.bottom-right .tooltip-arrow{top:0;right:5px;border-bottom-color:rgba(0,0,0,0.9);border-width:0 5px 5px}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);background-clip:padding-box;-webkit-bg-clip:padding-box;-moz-bg-clip:padding}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover .arrow{border-width:11px}.popover .arrow:after{border-width:10px;content:""}.popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0;content:" "}.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0;content:" "}.popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0;content:" "}.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0;content:" "}.alert{padding:10px 35px 10px 15px;margin-bottom:20px;color:#c09853;background-color:#fcf8e3;border:1px solid #fbeed5;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert hr{border-top-color:#f8e5be}.alert .alert-link{font-weight:500;color:#a47e3c}.alert .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#356635}.alert-danger{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.alert-danger hr{border-top-color:#e6c1c7}.alert-danger .alert-link{color:#953b39}.alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#2d6987}.alert-block{padding-top:15px;padding-bottom:15px}.alert-block>p,.alert-block>ul{margin-bottom:0}.alert-block p+p{margin-top:5px}.thumbnail,.img-thumbnail{padding:4px;line-height:1.428571429;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.thumbnail{display:block}.thumbnail>img,.img-thumbnail{display:inline-block;height:auto;max-width:100%}a.thumbnail:hover,a.thumbnail:focus{border-color:#428bca}.thumbnail>img{margin-right:auto;margin-left:auto}.thumbnail .caption{padding:9px;color:#333}.media,.media-body{overflow:hidden;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{padding-left:0;list-style:none}.label{display:inline;padding:.25em .6em;font-size:75%;font-weight:500;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#999;border-radius:.25em}.label[href]:hover,.label[href]:focus{color:#fff;text-decoration:none;cursor:pointer;background-color:#808080}.label-danger{background-color:#d9534f}.label-danger[href]:hover,.label-danger[href]:focus{background-color:#c9302c}.label-success{background-color:#5cb85c}.label-success[href]:hover,.label-success[href]:focus{background-color:#449d44}.label-warning{background-color:#f0ad4e}.label-warning[href]:hover,.label-warning[href]:focus{background-color:#ec971f}.label-info{background-color:#5bc0de}.label-info[href]:hover,.label-info[href]:focus{background-color:#31b0d5}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:bold;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#999;border-radius:10px}.badge:empty{display:none}a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}.btn .badge{position:relative;top:-1px}a.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#428bca;background-color:#fff}.nav-pills>li>a>.badge{margin-left:3px}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:0 0}to{background-position:40px 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;color:#fff;text-align:center;background-color:#428bca;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-transition:width .6s ease;transition:width .6s ease}.progress-striped .progress-bar{background-color:#428bca;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-size:40px 40px}.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-color:#d9534f;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-color:#5cb85c;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-color:#f0ad4e;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.accordion{margin-bottom:20px}.accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;border-radius:4px}.accordion-heading{border-bottom:0}.accordion-heading .accordion-toggle{display:block;padding:8px 15px;cursor:pointer}.accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:inline-block;height:auto;max-width:100%;line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6);opacity:.5;filter:alpha(opacity=50)}.carousel-control.left{background-color:rgba(0,0,0,0.0001);background-color:transparent;background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.5)),to(rgba(0,0,0,0.0001)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.5) 0),color-stop(rgba(0,0,0,0.0001) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000',endColorstr='#00000000',GradientType=1)}.carousel-control.right{right:0;left:auto;background-color:rgba(0,0,0,0.5);background-color:transparent;background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.0001)),to(rgba(0,0,0,0.5)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.0001) 0),color-stop(rgba(0,0,0,0.5) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000',endColorstr='#80000000',GradientType=1)}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-control .glyphicon,.carousel-control .icon-prev,.carousel-control .icon-next{position:absolute;top:50%;left:50%;z-index:5;display:inline-block;width:20px;height:20px;margin-top:-10px;margin-left:-10px;font-family:serif}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:120px;padding-left:0;margin-left:-60px;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon,.carousel-control .icon-prev,.carousel-control .icon-next{width:30px;height:30px;margin-top:-15px;margin-left:-15px;font-size:30px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.jumbotron{padding:30px;margin-bottom:30px;font-size:21px;font-weight:200;line-height:2.1428571435;color:inherit;background-color:#eee}.jumbotron h1{line-height:1;color:inherit}.jumbotron p{line-height:1.4}@media screen and (min-width:768px){.jumbotron{padding:50px 60px;border-radius:6px}.jumbotron h1{font-size:63px}}.clearfix:before,.clearfix:after{display:table;content:" "}.clearfix:after{clear:both}.pull-right{float:right}.pull-left{float:left}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.affix{position:fixed}@-ms-viewport{width:device-width}@media screen and (max-width:400px){@-ms-viewport{width:320px}}.hidden{display:none!important;visibility:hidden!important}.visible-sm{display:block!important}tr.visible-sm{display:table-row!important}th.visible-sm,td.visible-sm{display:table-cell!important}.visible-md{display:none!important}tr.visible-md{display:none!important}th.visible-md,td.visible-md{display:none!important}.visible-lg{display:none!important}tr.visible-lg{display:none!important}th.visible-lg,td.visible-lg{display:none!important}.hidden-sm{display:none!important}tr.hidden-sm{display:none!important}th.hidden-sm,td.hidden-sm{display:none!important}.hidden-md{display:block!important}tr.hidden-md{display:table-row!important}th.hidden-md,td.hidden-md{display:table-cell!important}.hidden-lg{display:block!important}tr.hidden-lg{display:table-row!important}th.hidden-lg,td.hidden-lg{display:table-cell!important}@media(min-width:768px) and (max-width:991px){.visible-sm{display:none!important}tr.visible-sm{display:none!important}th.visible-sm,td.visible-sm{display:none!important}.visible-md{display:block!important}tr.visible-md{display:table-row!important}th.visible-md,td.visible-md{display:table-cell!important}.visible-lg{display:none!important}tr.visible-lg{display:none!important}th.visible-lg,td.visible-lg{display:none!important}.hidden-sm{display:block!important}tr.hidden-sm{display:table-row!important}th.hidden-sm,td.hidden-sm{display:table-cell!important}.hidden-md{display:none!important}tr.hidden-md{display:none!important}th.hidden-md,td.hidden-md{display:none!important}.hidden-lg{display:block!important}tr.hidden-lg{display:table-row!important}th.hidden-lg,td.hidden-lg{display:table-cell!important}}@media(min-width:992px){.visible-sm{display:none!important}tr.visible-sm{display:none!important}th.visible-sm,td.visible-sm{display:none!important}.visible-md{display:none!important}tr.visible-md{display:none!important}th.visible-md,td.visible-md{display:none!important}.visible-lg{display:block!important}tr.visible-lg{display:table-row!important}th.visible-lg,td.visible-lg{display:table-cell!important}.hidden-sm{display:block!important}tr.hidden-sm{display:table-row!important}th.hidden-sm,td.hidden-sm{display:table-cell!important}.hidden-md{display:block!important}tr.hidden-md{display:table-row!important}th.hidden-md,td.hidden-md{display:table-cell!important}.hidden-lg{display:none!important}tr.hidden-lg{display:none!important}th.hidden-lg,td.hidden-lg{display:none!important}}.visible-print{display:none!important}tr.visible-print{display:none!important}th.visible-print,td.visible-print{display:none!important}@media print{.visible-print{display:block!important}tr.visible-print{display:table-row!important}th.visible-print,td.visible-print{display:table-cell!important}.hidden-print{display:none!important}tr.hidden-print{display:none!important}th.hidden-print,td.hidden-print{display:none!important}}
2359 </style>
2360
2361 <!-- zepto -->
2362 <script type="text/javascript">
2363 /* Zepto v1.1.2 - zepto event ajax form ie - zeptojs.com/license */
2364 var Zepto=function(){function G(a){return a==null?String(a):z[A.call(a)]||"object"}function H(a){return G(a)=="function"}function I(a){return a!=null&&a==a.window}function J(a){return a!=null&&a.nodeType==a.DOCUMENT_NODE}function K(a){return G(a)=="object"}function L(a){return K(a)&&!I(a)&&Object.getPrototypeOf(a)==Object.prototype}function M(a){return a instanceof Array}function N(a){return typeof a.length=="number"}function O(a){return g.call(a,function(a){return a!=null})}function P(a){return a.length>0?c.fn.concat.apply([],a):a}function Q(a){return a.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function R(a){return a in j?j[a]:j[a]=new RegExp("(^|\\s)"+a+"(\\s|$)")}function S(a,b){return typeof b=="number"&&!k[Q(a)]?b+"px":b}function T(a){var b,c;return i[a]||(b=h.createElement(a),h.body.appendChild(b),c=getComputedStyle(b,"").getPropertyValue("display"),b.parentNode.removeChild(b),c=="none"&&(c="block"),i[a]=c),i[a]}function U(a){return"children"in a?f.call(a.children):c.map(a.childNodes,function(a){if(a.nodeType==1)return a})}function V(c,d,e){for(b in d)e&&(L(d[b])||M(d[b]))?(L(d[b])&&!L(c[b])&&(c[b]={}),M(d[b])&&!M(c[b])&&(c[b]=[]),V(c[b],d[b],e)):d[b]!==a&&(c[b]=d[b])}function W(a,b){return b==null?c(a):c(a).filter(b)}function X(a,b,c,d){return H(b)?b.call(a,c,d):b}function Y(a,b,c){c==null?a.removeAttribute(b):a.setAttribute(b,c)}function Z(b,c){var d=b.className,e=d&&d.baseVal!==a;if(c===a)return e?d.baseVal:d;e?d.baseVal=c:b.className=c}function $(a){var b;try{return a?a=="true"||(a=="false"?!1:a=="null"?null:!/^0/.test(a)&&!isNaN(b=Number(a))?b:/^[\[\{]/.test(a)?c.parseJSON(a):a):a}catch(d){return a}}function _(a,b){b(a);for(var c in a.childNodes)_(a.childNodes[c],b)}var a,b,c,d,e=[],f=e.slice,g=e.filter,h=window.document,i={},j={},k={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},l=/^\s*<(\w+|!)[^>]*>/,m=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,n=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,o=/^(?:body|html)$/i,p=/([A-Z])/g,q=["val","css","html","text","data","width","height","offset"],r=["after","prepend","before","append"],s=h.createElement("table"),t=h.createElement("tr"),u={tr:h.createElement("tbody"),tbody:s,thead:s,tfoot:s,td:t,th:t,"*":h.createElement("div")},v=/complete|loaded|interactive/,w=/^\.([\w-]+)$/,x=/^#([\w-]*)$/,y=/^[\w-]*$/,z={},A=z.toString,B={},C,D,E=h.createElement("div"),F={tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"};return B.matches=function(a,b){if(!b||!a||a.nodeType!==1)return!1;var c=a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.matchesSelector;if(c)return c.call(a,b);var d,e=a.parentNode,f=!e;return f&&(e=E).appendChild(a),d=~B.qsa(e,b).indexOf(a),f&&E.removeChild(a),d},C=function(a){return a.replace(/-+(.)?/g,function(a,b){return b?b.toUpperCase():""})},D=function(a){return g.call(a,function(b,c){return a.indexOf(b)==c})},B.fragment=function(b,d,e){var g,i,j;return m.test(b)&&(g=c(h.createElement(RegExp.$1))),g||(b.replace&&(b=b.replace(n,"<$1></$2>")),d===a&&(d=l.test(b)&&RegExp.$1),d in u||(d="*"),j=u[d],j.innerHTML=""+b,g=c.each(f.call(j.childNodes),function(){j.removeChild(this)})),L(e)&&(i=c(g),c.each(e,function(a,b){q.indexOf(a)>-1?i[a](b):i.attr(a,b)})),g},B.Z=function(a,b){return a=a||[],a.__proto__=c.fn,a.selector=b||"",a},B.isZ=function(a){return a instanceof B.Z},B.init=function(b,d){var e;if(!b)return B.Z();if(typeof b=="string"){b=b.trim();if(b[0]=="<"&&l.test(b))e=B.fragment(b,RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=B.qsa(h,b)}}else{if(H(b))return c(h).ready(b);if(B.isZ(b))return b;if(M(b))e=O(b);else if(K(b))e=[b],b=null;else if(l.test(b))e=B.fragment(b.trim(),RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=B.qsa(h,b)}}return B.Z(e,b)},c=function(a,b){return B.init(a,b)},c.extend=function(a){var b,c=f.call(arguments,1);return typeof a=="boolean"&&(b=a,a=c.shift()),c.forEach(function(c){V(a,c,b)}),a},B.qsa=function(a,b){var c,d=b[0]=="#",e=!d&&b[0]==".",g=d||e?b.slice(1):b,h=y.test(g);return J(a)&&h&&d?(c=a.getElementById(g))?[c]:[]:a.nodeType!==1&&a.nodeType!==9?[]:f.call(h&&!d?e?a.getElementsByClassName(g):a.getElementsByTagName(b):a.querySelectorAll(b))},c.contains=function(a,b){return a!==b&&a.contains(b)},c.type=G,c.isFunction=H,c.isWindow=I,c.isArray=M,c.isPlainObject=L,c.isEmptyObject=function(a){var b;for(b in a)return!1;return!0},c.inArray=function(a,b,c){return e.indexOf.call(b,a,c)},c.camelCase=C,c.trim=function(a){return a==null?"":String.prototype.trim.call(a)},c.uuid=0,c.support={},c.expr={},c.map=function(a,b){var c,d=[],e,f;if(N(a))for(e=0;e<a.length;e++)c=b(a[e],e),c!=null&&d.push(c);else for(f in a)c=b(a[f],f),c!=null&&d.push(c);return P(d)},c.each=function(a,b){var c,d;if(N(a)){for(c=0;c<a.length;c++)if(b.call(a[c],c,a[c])===!1)return a}else for(d in a)if(b.call(a[d],d,a[d])===!1)return a;return a},c.grep=function(a,b){return g.call(a,b)},window.JSON&&(c.parseJSON=JSON.parse),c.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){z["[object "+b+"]"]=b.toLowerCase()}),c.fn={forEach:e.forEach,reduce:e.reduce,push:e.push,sort:e.sort,indexOf:e.indexOf,concat:e.concat,map:function(a){return c(c.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return c(f.apply(this,arguments))},ready:function(a){return v.test(h.readyState)&&h.body?a(c):h.addEventListener("DOMContentLoaded",function(){a(c)},!1),this},get:function(b){return b===a?f.call(this):this[b>=0?b:b+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){this.parentNode!=null&&this.parentNode.removeChild(this)})},each:function(a){return e.every.call(this,function(b,c){return a.call(b,c,b)!==!1}),this},filter:function(a){return H(a)?this.not(this.not(a)):c(g.call(this,function(b){return B.matches(b,a)}))},add:function(a,b){return c(D(this.concat(c(a,b))))},is:function(a){return this.length>0&&B.matches(this[0],a)},not:function(b){var d=[];if(H(b)&&b.call!==a)this.each(function(a){b.call(this,a)||d.push(this)});else{var e=typeof b=="string"?this.filter(b):N(b)&&H(b.item)?f.call(b):c(b);this.forEach(function(a){e.indexOf(a)<0&&d.push(a)})}return c(d)},has:function(a){return this.filter(function(){return K(a)?c.contains(this,a):c(this).find(a).size()})},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){var a=this[0];return a&&!K(a)?a:c(a)},last:function(){var a=this[this.length-1];return a&&!K(a)?a:c(a)},find:function(a){var b,d=this;return typeof a=="object"?b=c(a).filter(function(){var a=this;return e.some.call(d,function(b){return c.contains(b,a)})}):this.length==1?b=c(B.qsa(this[0],a)):b=this.map(function(){return B.qsa(this,a)}),b},closest:function(a,b){var d=this[0],e=!1;typeof a=="object"&&(e=c(a));while(d&&!(e?e.indexOf(d)>=0:B.matches(d,a)))d=d!==b&&!J(d)&&d.parentNode;return c(d)},parents:function(a){var b=[],d=this;while(d.length>0)d=c.map(d,function(a){if((a=a.parentNode)&&!J(a)&&b.indexOf(a)<0)return b.push(a),a});return W(b,a)},parent:function(a){return W(D(this.pluck("parentNode")),a)},children:function(a){return W(this.map(function(){return U(this)}),a)},contents:function(){return this.map(function(){return f.call(this.childNodes)})},siblings:function(a){return W(this.map(function(a,b){return g.call(U(b.parentNode),function(a){return a!==b})}),a)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(a){return c.map(this,function(b){return b[a]})},show:function(){return this.each(function(){this.style.display=="none"&&(this.style.display=""),getComputedStyle(this,"").getPropertyValue("display")=="none"&&(this.style.display=T(this.nodeName))})},replaceWith:function(a){return this.before(a).remove()},wrap:function(a){var b=H(a);if(this[0]&&!b)var d=c(a).get(0),e=d.parentNode||this.length>1;return this.each(function(f){c(this).wrapAll(b?a.call(this,f):e?d.cloneNode(!0):d)})},wrapAll:function(a){if(this[0]){c(this[0]).before(a=c(a));var b;while((b=a.children()).length)a=b.first();c(a).append(this)}return this},wrapInner:function(a){var b=H(a);return this.each(function(d){var e=c(this),f=e.contents(),g=b?a.call(this,d):a;f.length?f.wrapAll(g):e.append(g)})},unwrap:function(){return this.parent().each(function(){c(this).replaceWith(c(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(b){return this.each(function(){var d=c(this);(b===a?d.css("display")=="none":b)?d.show():d.hide()})},prev:function(a){return c(this.pluck("previousElementSibling")).filter(a||"*")},next:function(a){return c(this.pluck("nextElementSibling")).filter(a||"*")},html:function(a){return arguments.length===0?this.length>0?this[0].innerHTML:null:this.each(function(b){var d=this.innerHTML;c(this).empty().append(X(this,a,b,d))})},text:function(b){return arguments.length===0?this.length>0?this[0].textContent:null:this.each(function(){this.textContent=b===a?"":""+b})},attr:function(c,d){var e;return typeof c=="string"&&d===a?this.length==0||this[0].nodeType!==1?a:c=="value"&&this[0].nodeName=="INPUT"?this.val():!(e=this[0].getAttribute(c))&&c in this[0]?this[0][c]:e:this.each(function(a){if(this.nodeType!==1)return;if(K(c))for(b in c)Y(this,b,c[b]);else Y(this,c,X(this,d,a,this.getAttribute(c)))})},removeAttr:function(a){return this.each(function(){this.nodeType===1&&Y(this,a)})},prop:function(b,c){return b=F[b]||b,c===a?this[0]&&this[0][b]:this.each(function(a){this[b]=X(this,c,a,this[b])})},data:function(b,c){var d=this.attr("data-"+b.replace(p,"-$1").toLowerCase(),c);return d!==null?$(d):a},val:function(a){return arguments.length===0?this[0]&&(this[0].multiple?c(this[0]).find("option").filter(function(){return this.selected}).pluck("value"):this[0].value):this.each(function(b){this.value=X(this,a,b,this.value)})},offset:function(a){if(a)return this.each(function(b){var d=c(this),e=X(this,a,b,d.offset()),f=d.offsetParent().offset(),g={top:e.top-f.top,left:e.left-f.left};d.css("position")=="static"&&(g.position="relative"),d.css(g)});if(this.length==0)return null;var b=this[0].getBoundingClientRect();return{left:b.left+window.pageXOffset,top:b.top+window.pageYOffset,width:Math.round(b.width),height:Math.round(b.height)}},css:function(a,d){if(arguments.length<2){var e=this[0],f=getComputedStyle(e,"");if(!e)return;if(typeof a=="string")return e.style[C(a)]||f.getPropertyValue(a);if(M(a)){var g={};return c.each(M(a)?a:[a],function(a,b){g[b]=e.style[C(b)]||f.getPropertyValue(b)}),g}}var h="";if(G(a)=="string")!d&&d!==0?this.each(function(){this.style.removeProperty(Q(a))}):h=Q(a)+":"+S(a,d);else for(b in a)!a[b]&&a[b]!==0?this.each(function(){this.style.removeProperty(Q(b))}):h+=Q(b)+":"+S(b,a[b])+";";return this.each(function(){this.style.cssText+=";"+h})},index:function(a){return a?this.indexOf(c(a)[0]):this.parent().children().indexOf(this[0])},hasClass:function(a){return a?e.some.call(this,function(a){return this.test(Z(a))},R(a)):!1},addClass:function(a){return a?this.each(function(b){d=[];var e=Z(this),f=X(this,a,b,e);f.split(/\s+/g).forEach(function(a){c(this).hasClass(a)||d.push(a)},this),d.length&&Z(this,e+(e?" ":"")+d.join(" "))}):this},removeClass:function(b){return this.each(function(c){if(b===a)return Z(this,"");d=Z(this),X(this,b,c,d).split(/\s+/g).forEach(function(a){d=d.replace(R(a)," ")}),Z(this,d.trim())})},toggleClass:function(b,d){return b?this.each(function(e){var f=c(this),g=X(this,b,e,Z(this));g.split(/\s+/g).forEach(function(b){(d===a?!f.hasClass(b):d)?f.addClass(b):f.removeClass(b)})}):this},scrollTop:function(b){if(!this.length)return;var c="scrollTop"in this[0];return b===a?c?this[0].scrollTop:this[0].pageYOffset:this.each(c?function(){this.scrollTop=b}:function(){this.scrollTo(this.scrollX,b)})},scrollLeft:function(b){if(!this.length)return;var c="scrollLeft"in this[0];return b===a?c?this[0].scrollLeft:this[0].pageXOffset:this.each(c?function(){this.scrollLeft=b}:function(){this.scrollTo(b,this.scrollY)})},position:function(){if(!this.length)return;var a=this[0],b=this.offsetParent(),d=this.offset(),e=o.test(b[0].nodeName)?{top:0,left:0}:b.offset();return d.top-=parseFloat(c(a).css("margin-top"))||0,d.left-=parseFloat(c(a).css("margin-left"))||0,e.top+=parseFloat(c(b[0]).css("border-top-width"))||0,e.left+=parseFloat(c(b[0]).css("border-left-width"))||0,{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||h.body;while(a&&!o.test(a.nodeName)&&c(a).css("position")=="static")a=a.offsetParent;return a})}},c.fn.detach=c.fn.remove,["width","height"].forEach(function(b){var d=b.replace(/./,function(a){return a[0].toUpperCase()});c.fn[b]=function(e){var f,g=this[0];return e===a?I(g)?g["inner"+d]:J(g)?g.documentElement["scroll"+d]:(f=this.offset())&&f[b]:this.each(function(a){g=c(this),g.css(b,X(this,e,a,g[b]()))})}}),r.forEach(function(a,b){var d=b%2;c.fn[a]=function(){var a,e=c.map(arguments,function(b){return a=G(b),a=="object"||a=="array"||b==null?b:B.fragment(b)}),f,g=this.length>1;return e.length<1?this:this.each(function(a,h){f=d?h:h.parentNode,h=b==0?h.nextSibling:b==1?h.firstChild:b==2?h:null,e.forEach(function(a){if(g)a=a.cloneNode(!0);else if(!f)return c(a).remove();_(f.insertBefore(a,h),function(a){a.nodeName!=null&&a.nodeName.toUpperCase()==="SCRIPT"&&(!a.type||a.type==="text/javascript")&&!a.src&&window.eval.call(window,a.innerHTML)})})})},c.fn[d?a+"To":"insert"+(b?"Before":"After")]=function(b){return c(b)[a](this),this}}),B.Z.prototype=c.fn,B.uniq=D,B.deserializeValue=$,c.zepto=B,c}();window.Zepto=Zepto,window.$===undefined&&(window.$=Zepto),function(a){function m(a){return a._zid||(a._zid=c++)}function n(a,b,c,d){b=o(b);if(b.ns)var e=p(b.ns);return(h[m(a)]||[]).filter(function(a){return a&&(!b.e||a.e==b.e)&&(!b.ns||e.test(a.ns))&&(!c||m(a.fn)===m(c))&&(!d||a.sel==d)})}function o(a){var b=(""+a).split(".");return{e:b[0],ns:b.slice(1).sort().join(" ")}}function p(a){return new RegExp("(?:^| )"+a.replace(" "," .* ?")+"(?: |$)")}function q(a,b){return a.del&&!j&&a.e in k||!!b}function r(a){return l[a]||j&&k[a]||a}function s(b,c,e,f,g,i,j){var k=m(b),n=h[k]||(h[k]=[]);c.split(/\s/).forEach(function(c){if(c=="ready")return a(document).ready(e);var h=o(c);h.fn=e,h.sel=g,h.e in l&&(e=function(b){var c=b.relatedTarget;if(!c||c!==this&&!a.contains(this,c))return h.fn.apply(this,arguments)}),h.del=i;var k=i||e;h.proxy=function(a){a=y(a);if(a.isImmediatePropagationStopped())return;a.data=f;var c=k.apply(b,a._args==d?[a]:[a].concat(a._args));return c===!1&&(a.preventDefault(),a.stopPropagation()),c},h.i=n.length,n.push(h),"addEventListener"in b&&b.addEventListener(r(h.e),h.proxy,q(h,j))})}function t(a,b,c,d,e){var f=m(a);(b||"").split(/\s/).forEach(function(b){n(a,b,c,d).forEach(function(b){delete h[f][b.i],"removeEventListener"in a&&a.removeEventListener(r(b.e),b.proxy,q(b,e))})})}function y(b,c){if(c||!b.isDefaultPrevented){c||(c=b),a.each(x,function(a,d){var e=c[a];b[a]=function(){return this[d]=u,e&&e.apply(c,arguments)},b[d]=v});if(c.defaultPrevented!==d?c.defaultPrevented:"returnValue"in c?c.returnValue===!1:c.getPreventDefault&&c.getPreventDefault())b.isDefaultPrevented=u}return b}function z(a){var b,c={originalEvent:a};for(b in a)!w.test(b)&&a[b]!==d&&(c[b]=a[b]);return y(c,a)}var b=a.zepto.qsa,c=1,d,e=Array.prototype.slice,f=a.isFunction,g=function(a){return typeof a=="string"},h={},i={},j="onfocusin"in window,k={focus:"focusin",blur:"focusout"},l={mouseenter:"mouseover",mouseleave:"mouseout"};i.click=i.mousedown=i.mouseup=i.mousemove="MouseEvents",a.event={add:s,remove:t},a.proxy=function(b,c){if(f(b)){var d=function(){return b.apply(c,arguments)};return d._zid=m(b),d}if(g(c))return a.proxy(b[c],b);throw new TypeError("expected function")},a.fn.bind=function(a,b,c){return this.on(a,b,c)},a.fn.unbind=function(a,b){return this.off(a,b)},a.fn.one=function(a,b,c,d){return this.on(a,b,c,d,1)};var u=function(){return!0},v=function(){return!1},w=/^([A-Z]|returnValue$|layer[XY]$)/,x={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};a.fn.delegate=function(a,b,c){return this.on(b,a,c)},a.fn.undelegate=function(a,b,c){return this.off(b,a,c)},a.fn.live=function(b,c){return a(document.body).delegate(this.selector,b,c),this},a.fn.die=function(b,c){return a(document.body).undelegate(this.selector,b,c),this},a.fn.on=function(b,c,h,i,j){var k,l,m=this;if(b&&!g(b))return a.each(b,function(a,b){m.on(a,c,h,b,j)}),m;!g(c)&&!f(i)&&i!==!1&&(i=h,h=c,c=d);if(f(h)||h===!1)i=h,h=d;return i===!1&&(i=v),m.each(function(d,f){j&&(k=function(a){return t(f,a.type,i),i.apply(this,arguments)}),c&&(l=function(b){var d,g=a(b.target).closest(c,f).get(0);if(g&&g!==f)return d=a.extend(z(b),{currentTarget:g,liveFired:f}),(k||i).apply(g,[d].concat(e.call(arguments,1)))}),s(f,b,i,h,c,l||k)})},a.fn.off=function(b,c,e){var h=this;return b&&!g(b)?(a.each(b,function(a,b){h.off(a,c,b)}),h):(!g(c)&&!f(e)&&e!==!1&&(e=c,c=d),e===!1&&(e=v),h.each(function(){t(this,b,e,c)}))},a.fn.trigger=function(b,c){return b=g(b)||a.isPlainObject(b)?a.Event(b):y(b),b._args=c,this.each(function(){"dispatchEvent"in this?this.dispatchEvent(b):a(this).triggerHandler(b,c)})},a.fn.triggerHandler=function(b,c){var d,e;return this.each(function(f,h){d=z(g(b)?a.Event(b):b),d._args=c,d.target=h,a.each(n(h,b.type||b),function(a,b){e=b.proxy(d);if(d.isImmediatePropagationStopped())return!1})}),e},"focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.trigger(b)}}),["focus","blur"].forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.each(function(){try{this[b]()}catch(a){}}),this}}),a.Event=function(a,b){g(a)||(b=a,a=b.type);var c=document.createEvent(i[a]||"Events"),d=!0;if(b)for(var e in b)e=="bubbles"?d=!!b[e]:c[e]=b[e];return c.initEvent(a,d,!0),y(c)}}(Zepto),function($){function triggerAndReturn(a,b,c){var d=$.Event(b);return $(a).trigger(d,c),!d.isDefaultPrevented()}function triggerGlobal(a,b,c,d){if(a.global)return triggerAndReturn(b||document,c,d)}function ajaxStart(a){a.global&&$.active++===0&&triggerGlobal(a,null,"ajaxStart")}function ajaxStop(a){a.global&&!--$.active&&triggerGlobal(a,null,"ajaxStop")}function ajaxBeforeSend(a,b){var c=b.context;if(b.beforeSend.call(c,a,b)===!1||triggerGlobal(b,c,"ajaxBeforeSend",[a,b])===!1)return!1;triggerGlobal(b,c,"ajaxSend",[a,b])}function ajaxSuccess(a,b,c,d){var e=c.context,f="success";c.success.call(e,a,f,b),d&&d.resolveWith(e,[a,f,b]),triggerGlobal(c,e,"ajaxSuccess",[b,c,a]),ajaxComplete(f,b,c)}function ajaxError(a,b,c,d,e){var f=d.context;d.error.call(f,c,b,a),e&&e.rejectWith(f,[c,b,a]),triggerGlobal(d,f,"ajaxError",[c,d,a||b]),ajaxComplete(b,c,d)}function ajaxComplete(a,b,c){var d=c.context;c.complete.call(d,b,a),triggerGlobal(c,d,"ajaxComplete",[b,c]),ajaxStop(c)}function empty(){}function mimeToDataType(a){return a&&(a=a.split(";",2)[0]),a&&(a==htmlType?"html":a==jsonType?"json":scriptTypeRE.test(a)?"script":xmlTypeRE.test(a)&&"xml")||"text"}function appendQuery(a,b){return b==""?a:(a+"&"+b).replace(/[&?]{1,2}/,"?")}function serializeData(a){a.processData&&a.data&&$.type(a.data)!="string"&&(a.data=$.param(a.data,a.traditional)),a.data&&(!a.type||a.type.toUpperCase()=="GET")&&(a.url=appendQuery(a.url,a.data),a.data=undefined)}function parseArguments(a,b,c,d){var e=!$.isFunction(b);return{url:a,data:e?b:undefined,success:e?$.isFunction(c)?c:undefined:b,dataType:e?d||c:c}}function serialize(a,b,c,d){var e,f=$.isArray(b),g=$.isPlainObject(b);$.each(b,function(b,h){e=$.type(h),d&&(b=c?d:d+"["+(g||e=="object"||e=="array"?b:"")+"]"),!d&&f?a.add(h.name,h.value):e=="array"||!c&&e=="object"?serialize(a,h,c,b):a.add(b,h)})}var jsonpID=0,document=window.document,key,name,rscript=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,scriptTypeRE=/^(?:text|application)\/javascript/i,xmlTypeRE=/^(?:text|application)\/xml/i,jsonType="application/json",htmlType="text/html",blankRE=/^\s*$/;$.active=0,$.ajaxJSONP=function(a,b){if("type"in a){var c=a.jsonpCallback,d=($.isFunction(c)?c():c)||"jsonp"+ ++jsonpID,e=document.createElement("script"),f=window[d],g,h=function(a){$(e).triggerHandler("error",a||"abort")},i={abort:h},j;return b&&b.promise(i),$(e).on("load error",function(c,h){clearTimeout(j),$(e).off().remove(),c.type=="error"||!g?ajaxError(null,h||"error",i,a,b):ajaxSuccess(g[0],i,a,b),window[d]=f,g&&$.isFunction(f)&&f(g[0]),f=g=undefined}),ajaxBeforeSend(i,a)===!1?(h("abort"),i):(window[d]=function(){g=arguments},e.src=a.url.replace(/=\?/,"="+d),document.head.appendChild(e),a.timeout>0&&(j=setTimeout(function(){h("timeout")},a.timeout)),i)}return $.ajax(a)},$.ajaxSettings={type:"GET",beforeSend:empty,success:empty,error:empty,complete:empty,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:jsonType,xml:"application/xml, text/xml",html:htmlType,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},$.ajax=function(options){var settings=$.extend({},options||{}),deferred=$.Deferred&&$.Deferred();for(key in $.ajaxSettings)settings[key]===undefined&&(settings[key]=$.ajaxSettings[key]);ajaxStart(settings),settings.crossDomain||(settings.crossDomain=/^([\w-]+:)?\/\/([^\/]+)/.test(settings.url)&&RegExp.$2!=window.location.host),settings.url||(settings.url=window.location.toString()),serializeData(settings),settings.cache===!1&&(settings.url=appendQuery(settings.url,"_="+Date.now()));var dataType=settings.dataType,hasPlaceholder=/=\?/.test(settings.url);if(dataType=="jsonp"||hasPlaceholder)return hasPlaceholder||(settings.url=appendQuery(settings.url,settings.jsonp?settings.jsonp+"=?":settings.jsonp===!1?"":"callback=?")),$.ajaxJSONP(settings,deferred);var mime=settings.accepts[dataType],headers={},setHeader=function(a,b){headers[a.toLowerCase()]=[a,b]},protocol=/^([\w-]+:)\/\//.test(settings.url)?RegExp.$1:window.location.protocol,xhr=settings.xhr(),nativeSetHeader=xhr.setRequestHeader,abortTimeout;deferred&&deferred.promise(xhr),settings.crossDomain||setHeader("X-Requested-With","XMLHttpRequest"),setHeader("Accept",mime||"*/*");if(mime=settings.mimeType||mime)mime.indexOf(",")>-1&&(mime=mime.split(",",2)[0]),xhr.overrideMimeType&&xhr.overrideMimeType(mime);(settings.contentType||settings.contentType!==!1&&settings.data&&settings.type.toUpperCase()!="GET")&&setHeader("Content-Type",settings.contentType||"application/x-www-form-urlencoded");if(settings.headers)for(name in settings.headers)setHeader(name,settings.headers[name]);xhr.setRequestHeader=setHeader,xhr.onreadystatechange=function(){if(xhr.readyState==4){xhr.onreadystatechange=empty,clearTimeout(abortTimeout);var result,error=!1;if(xhr.status>=200&&xhr.status<300||xhr.status==304||xhr.status==0&&protocol=="file:"){dataType=dataType||mimeToDataType(settings.mimeType||xhr.getResponseHeader("content-type")),result=xhr.responseText;try{dataType=="script"?(1,eval)(result):dataType=="xml"?result=xhr.responseXML:dataType=="json"&&(result=blankRE.test(result)?null:$.parseJSON(result))}catch(e){error=e}error?ajaxError(error,"parsererror",xhr,settings,deferred):ajaxSuccess(result,xhr,settings,deferred)}else ajaxError(xhr.statusText||null,xhr.status?"error":"abort",xhr,settings,deferred)}};if(ajaxBeforeSend(xhr,settings)===!1)return xhr.abort(),ajaxError(null,"abort",xhr,settings,deferred),xhr;if(settings.xhrFields)for(name in settings.xhrFields)xhr[name]=settings.xhrFields[name];var async="async"in settings?settings.async:!0;xhr.open(settings.type,settings.url,async,settings.username,settings.password);for(name in headers)nativeSetHeader.apply(xhr,headers[name]);return settings.timeout>0&&(abortTimeout=setTimeout(function(){xhr.onreadystatechange=empty,xhr.abort(),ajaxError(null,"timeout",xhr,settings,deferred)},settings.timeout)),xhr.send(settings.data?settings.data:null),xhr},$.get=function(a,b,c,d){return $.ajax(parseArguments.apply(null,arguments))},$.post=function(a,b,c,d){var e=parseArguments.apply(null,arguments);return e.type="POST",$.ajax(e)},$.getJSON=function(a,b,c){var d=parseArguments.apply(null,arguments);return d.dataType="json",$.ajax(d)},$.fn.load=function(a,b,c){if(!this.length)return this;var d=this,e=a.split(/\s/),f,g=parseArguments(a,b,c),h=g.success;return e.length>1&&(g.url=e[0],f=e[1]),g.success=function(a){d.html(f?$("<div>").html(a.replace(rscript,"")).find(f):a),h&&h.apply(d,arguments)},$.ajax(g),this};var escape=encodeURIComponent;$.param=function(a,b){var c=[];return c.add=function(a,b){this.push(escape(a)+"="+escape(b))},serialize(c,a,b),c.join("&").replace(/%20/g,"+")}}(Zepto),function(a){a.fn.serializeArray=function(){var b=[],c;return a([].slice.call(this.get(0).elements)).each(function(){c=a(this);var d=c.attr("type");this.nodeName.toLowerCase()!="fieldset"&&!this.disabled&&d!="submit"&&d!="reset"&&d!="button"&&(d!="radio"&&d!="checkbox"||this.checked)&&b.push({name:c.attr("name"),value:c.val()})}),b},a.fn.serialize=function(){var a=[];return this.serializeArray().forEach(function(b){a.push(encodeURIComponent(b.name)+"="+encodeURIComponent(b.value))}),a.join("&")},a.fn.submit=function(b){if(b)this.bind("submit",b);else if(this.length){var c=a.Event("submit");this.eq(0).trigger(c),c.isDefaultPrevented()||this.get(0).submit()}return this}}(Zepto),function(a){"__proto__"in{}||a.extend(a.zepto,{Z:function(b,c){return b=b||[],a.extend(b,a.fn),b.selector=c||"",b.__Z=!0,b},isZ:function(b){return a.type(b)==="array"&&"__Z"in b}});try{getComputedStyle(undefined)}catch(b){var c=getComputedStyle;window.getComputedStyle=function(a){try{return c(a)}catch(b){return null}}}}(Zepto)
2365 </script>
2366
2367 <style type="text/css">
2368 body {
2369 background: #F9F9F9;
2370 font-size: 14px;
2371 line-height: 22px;
2372 font-family: Helvetica Neue, Helvetica, Arial;
2373 }
2374
2375 a {
2376 color: #000;
2377 text-decoration: underline;
2378 }
2379
2380 li ul, li ol{
2381 margin: 0;
2382 }
2383
2384 .anchor {
2385 cursor: pointer;
2386 }
2387 .anchor .anchor_char{
2388 visibility: hidden;
2389 padding-left: 0.2em;
2390 font-size: 0.9em;
2391 opacity: 0.5;
2392 }
2393 .anchor:hover .anchor_char{
2394 visibility: visible;
2395 }
2396
2397 .sidebar{
2398 background: #FFF;
2399 position: fixed;
2400 z-index: 10;
2401 top: 0;
2402 left: 0;
2403 bottom: 0;
2404 width: 230px;
2405 overflow-y: auto;
2406 overflow-x: hidden;
2407 padding: 15px 0 30px 30px;
2408 border-right: 1px solid #bbb;
2409 font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important;
2410 }
2411
2412 .sidebar ul{
2413 margin: 0;
2414 list-style: none;
2415 padding: 0;
2416 }
2417
2418 .sidebar ul a:hover {
2419 text-decoration: underline;
2420 color: #333;
2421 }
2422
2423 .sidebar > ul > li {
2424 margin-top: 15px;
2425 }
2426
2427 .sidebar > ul > li > a {
2428 font-weight: bold;
2429 }
2430
2431 .sidebar ul ul {
2432 margin-top: 5px;
2433 font-size: 11px;
2434 line-height: 14px;
2435 }
2436
2437 .sidebar ul ul li:before {
2438 content: "- ";
2439 }
2440 .sidebar ul ul li {
2441 margin-bottom: 3px;
2442 }
2443 .sidebar ul ul li a {
2444 text-decoration: none;
2445 }
2446
2447 .toggle_sidebar_button{
2448 display: none;
2449 position: fixed;
2450 z-index: 11;
2451 top: 0;
2452 width: 44px;
2453 height: 44px;
2454 background: #000;
2455 background: rgba(0,0,0,0.7);
2456 margin-left: 230px;
2457 }
2458 .toggle_sidebar_button:hover {
2459 background: rgba(0,0,0,1);
2460 cursor: pointer;
2461 }
2462 .toggle_sidebar_button .line{
2463 height: 2px;
2464 width: 21px;
2465 margin-left: 11px;
2466 margin-top: 5px;
2467 background: #FFF;
2468 }
2469 .toggle_sidebar_button .line:first-child {
2470 margin-top: 15px;
2471 }
2472
2473 .main_container {
2474 width: 100%;
2475 padding-left: 260px;
2476 margin: 30px;
2477 margin-left: 0px;
2478 padding-right: 30px;
2479 }
2480
2481 .main_container p, ul{
2482 margin: 25px 0;
2483 }
2484
2485 .main_container ul {
2486 list-style: circle;
2487 font-size: 13px;
2488 line-height: 18px;
2489 padding-left: 15px;
2490 }
2491
2492 pre {
2493 font-size: 12px;
2494 border: 4px solid #bbb;
2495 border-top: 0;
2496 border-bottom: 0;
2497 margin: 0px 0 25px;
2498 padding-top: 0px;
2499 padding-bottom: 0px;
2500
2501 font-family: Monaco, Consolas, "Lucida Console", monospace;
2502 line-height: 18px;
2503 font-style: normal;
2504 background: none;
2505 border-radius: 0px;
2506 overflow-x: scroll;
2507
2508 word-wrap: normal;
2509 white-space: pre;
2510 }
2511
2512 .main_container {
2513 width: 840px;
2514 }
2515
2516 .main_container p, ul, pre {
2517 width: 100%;
2518 }
2519
2520 code {
2521 padding: 0px 3px;
2522 color: #333;
2523 background: #fff;
2524 border: 1px solid #ddd;
2525 zoom: 1;
2526 white-space: nowrap;
2527 border-radius: 0;
2528 font-family: Monaco, Consolas, "Lucida Console", monospace;
2529 font-size: 12px;
2530 line-height: 18px;
2531 font-style: normal;
2532 }
2533
2534 em {
2535 font-size: 12px;
2536 line-height: 18px;
2537 }
2538
2539 @media (max-width: 820px) {
2540 .sidebar {
2541 display: none;
2542 }
2543
2544 .main_container {
2545 padding: 0px;
2546 width: 100%;
2547 }
2548
2549 .main_container > *{
2550 padding-left: 10px;
2551 padding-right: 10px;
2552 }
2553 .main_container > ul,
2554 .main_container > ol {
2555 padding-left: 27px;
2556 }
2557 .force_show_sidebar .main_container {
2558 display: none;
2559 }
2560 .force_show_sidebar .sidebar {
2561 width: 100%;
2562 }
2563 .force_show_sidebar .sidebar a{
2564 font-size: 1.5em;
2565 line-height: 1.5em;
2566 }
2567 .force_show_sidebar .toggle_sidebar_button {
2568 right: 0;
2569 }
2570 .force_show_sidebar .toggle_sidebar_button .line:first-child,
2571 .force_show_sidebar .toggle_sidebar_button .line:last-child {
2572 visibility: hidden;
2573 }
2574
2575 .toggle_sidebar_button {
2576 margin-left: 0px;
2577 display: block;
2578 }
2579
2580 pre {
2581 font-size: 12px;
2582 border: 1px solid #bbb;
2583 border-left: 0;
2584 border-right: 0;
2585 padding: 9px;
2586 background: #FFF;
2587 }
2588
2589 code {
2590 word-wrap: break-word;
2591 white-space: normal;
2592 }
2593 }
2594
2595 .force_show_sidebar .sidebar {
2596 display: block;
2597 }
2598
2599 .force_show_sidebar .main_container {
2600 padding-left: 260px;
2601 }
2602
2603 .force_show_sidebar .toggle_sidebar_button{
2604 margin-left: 230px;
2605 }
2606 </style>
2607
2608 <script type="text/javascript">
2609 $(function(){
2610 $('.toggle_sidebar_button').on('click', function(){
2611 $('body').toggleClass('force_show_sidebar');
2612 });
2613
2614 // hide sidebar on every click in menu (if small screen)
2615 $('.sidebar').find('a').on('click', function(){
2616 $('body').removeClass('force_show_sidebar');
2617 });
2618
2619 // add anchors
2620 $.each($('.main_container').find('h1,h2,h3,h4,h5,h6'), function(key, item){
2621 if ($(item).attr('id')) {
2622 $(item).addClass('anchor');
2623 $(item).append($('<span class="anchor_char">¶</span>'))
2624 $(item).on('click', function(){
2625 window.location = '#' + $(item).attr('id');
2626 })
2627 }
2628 });
2629
2630 // remove <code> tag inside of <pre>
2631 $.each($('pre > code'), function(key, item){
2632 $(item).parent().html($(item).html())
2633 })
2634 })
2635 </script>
2636 </head>
2637 <body>
2638 <a class="toggle_sidebar_button">
2639 <div class="line"></div>
2640 <div class="line"></div>
2641 <div class="line"></div>
2642 </a>
2643 <div class="sidebar">
2644 <!-- toc -->
2645 </div>
2646 <div class="main_container">
2647 <!-- main_content -->
2648 </div>
2649 </body>
2650 </html>'''
2651
2652
2653 def force_text(text):
2654 if isinstance(text, unicode):
2655 return text
2656 else:
2657 return text.decode('utf-8')
2658
2659
2660 class BackDoc:
2661 def __init__(self, markdown_converter, template_html, stdin, stdout):
2662 self.markdown_converter = markdown_converter
2663 self.template_html = force_text(template_html)
2664 self.stdin = stdin
2665 self.stdout = stdout
2666 self.parser = self.get_parser()
2667
2668 def run(self, argv):
2669 kwargs = self.get_kwargs(argv)
2670 self.stdout.write(self.get_result_html(**kwargs))
2671
2672 def get_kwargs(self, argv):
2673 parsed = dict(self.parser.parse_args(argv)._get_kwargs())
2674 return self.prepare_kwargs_from_parsed_data(parsed)
2675
2676 def prepare_kwargs_from_parsed_data(self, parsed):
2677 kwargs = {}
2678 kwargs['title'] = force_text(parsed.get('title') or 'Documentation')
2679 if parsed.get('source'):
2680 kwargs['markdown_src'] = open(parsed['source'], 'r').read()
2681 else:
2682 kwargs['markdown_src'] = self.stdin.read()
2683 kwargs['markdown_src'] = force_text(kwargs['markdown_src'] or '')
2684 return kwargs
2685
2686 def get_result_html(self, title, markdown_src):
2687 response = self.get_converted_to_html_response(markdown_src)
2688 return (
2689 self.template_html.replace('<!-- title -->', title)
2690 .replace('<!-- toc -->', response.toc_html and force_text(response.toc_html) or '')
2691 .replace('<!-- main_content -->', force_text(response))
2692 )
2693
2694 def get_converted_to_html_response(self, markdown_src):
2695 return self.markdown_converter.convert(markdown_src)
2696
2697 def get_parser(self):
2698 parser = argparse.ArgumentParser()
2699 parser.add_argument(
2700 '-t',
2701 '--title',
2702 help='Documentation title header',
2703 required=False,
2704 )
2705 parser.add_argument(
2706 '-s',
2707 '--source',
2708 help='Markdown source file path',
2709 required=False,
2710 )
2711 return parser
2712
2713
2714 if __name__ == '__main__':
2715 BackDoc(
2716 markdown_converter=Markdown(extras=['toc']),
2717 template_html=template_html,
2718 stdin=sys.stdin,
2719 stdout=sys.stdout
2720 ).run(argv=sys.argv[1:])