repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
chibisov/drf-extensions
docs/backdoc.py
Markdown._get_emacs_vars
python
def _get_emacs_vars(self, text): emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars
Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L414-L513
null
class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text)
chibisov/drf-extensions
docs/backdoc.py
Markdown._detab
python
def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0]
r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam'
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L521-L538
null
class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text)
chibisov/drf-extensions
docs/backdoc.py
Markdown._hash_html_blocks
python
def _hash_html_blocks(self, text, raw=False): if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text
Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode.
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L601-L707
[ "def _hash_text(s):\n return 'md5-' + md5(SECRET_SALT + s.encode(\"utf-8\")).hexdigest()\n", "def _curry(*args, **kwargs):\n function, args = args[0], args[1:]\n def result(*rest, **kwrest):\n combined = kwargs.copy()\n combined.update(kwrest)\n return function(*args + rest, **combined)\n return result\n", "def _sanitize_html(self, s):\n if self.safe_mode == \"replace\":\n return self.html_removed_text\n elif self.safe_mode == \"escape\":\n replacements = [\n ('&', '&amp;'),\n ('<', '&lt;'),\n ('>', '&gt;'),\n ]\n for before, after in replacements:\n s = s.replace(before, after)\n return s\n else:\n raise MarkdownError(\"invalid value for 'safe_mode': %r (must be \"\n \"'escape' or 'replace')\" % self.safe_mode)\n" ]
class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text)
chibisov/drf-extensions
docs/backdoc.py
Markdown._strip_footnote_definitions
python
def _strip_footnote_definitions(self, text): less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text)
A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note.
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L753-L784
null
class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text)
chibisov/drf-extensions
docs/backdoc.py
Markdown._prepare_pyshell_blocks
python
def _prepare_pyshell_blocks(self, text): if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text)
Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented.
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L846-L860
null
class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text)
chibisov/drf-extensions
docs/backdoc.py
Markdown._do_links
python
def _do_links(self, text): MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text
Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets.
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L1039-L1224
null
class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text)
chibisov/drf-extensions
docs/backdoc.py
Markdown.header_id_from_text
python
def header_id_from_text(self, text, prefix, n): header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id
Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified).
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L1226-L1249
[ "def _slugify(text, delim=u'-'):\n \"\"\"Generates an ASCII-only slug.\"\"\"\n result = []\n for word in _punct_re.split(text.lower()):\n word = word.encode('utf-8')\n if word:\n result.append(word)\n slugified = delim.join([i.decode('utf-8') for i in result])\n return re.sub('[^a-zA-Z0-9\\\\s\\\\-]{1}', replace_char, slugified).lower()\n" ]
class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text)
chibisov/drf-extensions
docs/backdoc.py
Markdown._html_class_str_from_tag
python
def _html_class_str_from_tag(self, tag): if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return ""
Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag.
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L1508-L1521
null
class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text)
chibisov/drf-extensions
docs/backdoc.py
Markdown._do_code_blocks
python
def _do_code_blocks(self, text): code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text)
Process Markdown `<pre><code>` blocks.
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L1523-L1536
null
class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text)
chibisov/drf-extensions
docs/backdoc.py
Markdown._encode_code
python
def _encode_code(self, text): replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed
Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings.
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L1600-L1617
null
class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text)
chibisov/drf-extensions
docs/backdoc.py
Markdown._do_smart_punctuation
python
def _do_smart_punctuation(self, text): if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text
Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants.
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L1653-L1677
null
class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text)
chibisov/drf-extensions
docs/backdoc.py
Markdown._do_link_patterns
python
def _do_link_patterns(self, text): link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in list(link_from_hash.items()): text = text.replace(hash, link) return text
Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this.
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L1846-L1875
null
class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode # Massaging and building the "extras" info. if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) if "toc" in self.extras and not "header-ids" in self.extras: self.extras["header-ids"] = None # "toc" implies "header-ids" self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) self._escape_table = g_escape_table.copy() if "smarty-pants" in self.extras: self._escape_table['"'] = _hash_text('"') self._escape_table["'"] = _hash_text("'") def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] if "header-ids" in self.extras: self._count_from_header_id = {} # no `defaultdict` in Python 2.4 if "metadata" in self.extras: self.metadata = {} # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel" # should only be used in <a> tags with an "href" attribute. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE) def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) # strip metadata from head and extract if "metadata" in self.extras: text = self._extract_metadata(text) text = self.preprocess(text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self.postprocess(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) if "nofollow" in self.extras: text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text) text += "\n" rv = UnicodeWithAttrs(text) if "toc" in self.extras: rv._toc = self._toc if "metadata" in self.extras: rv.metadata = self.metadata return rv def postprocess(self, text): """A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans. """ return text def preprocess(self, text): """A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing. """ return text # Is metadata if the content starts with '---'-fenced `key: value` # pairs. E.g. (indented for presentation): # --- # foo: bar # another-var: blah blah # --- _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""") def _extract_metadata(self, text): # fast test if not text.startswith("---"): return text match = self._metadata_pat.match(text) if not match: return text tail = text[len(match.group(0)):] metadata_str = match.group(1).strip() for line in metadata_str.split('\n'): key, value = line.split(':', 1) self.metadata[key.strip()] = value.strip() return tail _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in list(emacs_vars.items()): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] # I broke out the html5 tags here and add them to _block_tags_a and # _block_tags_b. This way html5 tags are easy to keep track of. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption' _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _block_tags_a += _html5tags _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _block_tags_b += _html5tags _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) _html_markdown_attr_re = re.compile( r'''\s+markdown=("1"|'1')''') def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) elif 'markdown-in-html' in self.extras and 'markdown=' in html: first_line = html.split('\n', 1)[0] m = self._html_markdown_attr_re.search(first_line) if m: lines = html.split('\n') middle = '\n'.join(lines[1:-1]) last_line = lines[-1] first_line = first_line[:m.start()] + first_line[m.end():] f_key = _hash_text(first_line) self.html_blocks[f_key] = first_line l_key = _hash_text(last_line) self.html_blocks[l_key] = last_line return ''.join(["\n\n", f_key, "\n\n", middle, "\n\n", l_key, "\n\n"]) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_data = [ ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)), ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)), ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. if "fenced-code-blocks" in self.extras: text = self._do_fenced_code_blocks(text) text = self._do_headers(text) # Do Horizontal Rules: # On the number of spaces in horizontal rules: The spec is fuzzy: "If # you wish, you may use spaces between the hyphens or asterisks." # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the # hr chars to one or two. We'll reproduce that limit here. hr = "\n<hr"+self.empty_element_suffix+"\n" for ch, regex in self._hr_data: if ch in text: for m in reversed(list(regex.finditer(text))): tail = m.group(1).rstrip() if not tail.strip(ch + ' ') and tail.count(" ") == 0: start, end = m.span() text = text[:start] + hr + text[end:] text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) if "wiki-tables" in self.extras: text = self._do_wiki_tables(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _wiki_table_sub(self, match): ttext = match.group(0).strip() #print 'wiki table: %r' % match.group(0) rows = [] for line in ttext.splitlines(0): line = line.strip()[2:-2].strip() row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)] rows.append(row) #pprint(rows) hlines = ['<table>', '<tbody>'] for row in rows: hrow = ['<tr>'] for cell in row: hrow.append('<td>') hrow.append(self._run_span_gamut(cell)) hrow.append('</td>') hrow.append('</tr>') hlines.append(''.join(hrow)) hlines += ['</tbody>', '</table>'] return '\n'.join(hlines) + '\n' def _do_wiki_tables(self, text): # Optimization. if "||" not in text: return text less_than_tab = self.tab_width - 1 wiki_table_re = re.compile(r''' (?:(?<=\n\n)|\A\n?) # leading blank line ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line (^\1\|\|.+?\|\|\n)* # any number of subsequent lines ''' % less_than_tab, re.M | re.X) return wiki_table_re.sub(self._wiki_table_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) if "smarty-pants" in self.extras: text = self._do_smart_punctuation(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in list(self.html_spans.items()): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) if title: title_str = ' title="%s"' % ( _xml_escape_attr(title) .replace('*', self._escape_table['*']) .replace('_', self._escape_table['_'])) else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), _xml_escape_attr(link_text), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title = self.titles.get(link_id) if title: before = title title = _xml_escape_attr(title) \ .replace('*', self._escape_table['*']) \ .replace('_', self._escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) if "smarty-pants" in self.extras: result = result.replace('"', self._escape_table['"']) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text def header_id_from_text(self, text, prefix, n): """Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "header-ids" extra key, if any. Otherwise, None. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag. @returns {str} The value for the header tag's "id" attribute. Return None to not have an id attribute and to exclude this header from the TOC (if the "toc" extra is specified). """ header_id = _slugify(text) if prefix and isinstance(prefix, base_string_type): header_id = prefix + '-' + header_id if header_id in self._count_from_header_id: self._count_from_header_id[header_id] += 1 header_id += '-%s' % self._count_from_header_id[header_id] else: self._count_from_header_id[header_id] = 1 return header_id _toc = None def _toc_add_entry(self, level, id, name): if self._toc is None: self._toc = [] self._toc.append((level, id, self._unescape_special_chars(name))) _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(1), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(1)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]+ (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) header_id_attr = "" if "header-ids" in self.extras: header_id = self.header_id_from_text(match.group(2), self.extras["header-ids"], n) if header_id: header_id_attr = ' id="%s"' % header_id html = self._run_span_gamut(match.group(2)) if "toc" in self.extras and header_id: self._toc_add_entry(n, header_id, html) return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. # Iterate over each *non-overlapping* list match. pos = 0 while True: # Find the *first* hit for either list style (ul or ol). We # match ul and ol separately to avoid adjacent lists of different # types running into each other (see issue #16). hits = [] for marker_pat in (self._marker_ul, self._marker_ol): less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case. ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) if self.list_level: # sub-list list_re = re.compile("^"+whole_list, re.X | re.M | re.S) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) match = list_re.search(text, pos) if match: hits.append((match.start(), match)) if not hits: break hits.sort() match = hits[0][1] start, end = match.span() text = text[:start] + self._list_sub(match) + text[end:] pos = end return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (?P<marker>%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter_opts.setdefault("cssclass", "codehilite") formatter = HtmlCodeFormatter(**formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match, is_fenced_code_block=False): lexer_name = None if is_fenced_code_block: lexer_name = match.group(1) if lexer_name: formatter_opts = self.extras['fenced-code-blocks'] or {} codeblock = match.group(2) codeblock = codeblock[:-1] # drop one trailing newline else: codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace # Note: "code-color" extra is DEPRECATED. if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() codeblock = rest.lstrip("\n") # Remove lexer declaration line. formatter_opts = self.extras['code-color'] or {} if lexer_name: lexer = self._get_pygments_lexer(lexer_name) if lexer: colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) pre_class_str = self._html_class_str_from_tag("pre") code_class_str = self._html_class_str_from_tag("code") return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % ( pre_class_str, code_class_str, codeblock) def _html_class_str_from_tag(self, tag): """Get the appropriate ' class="..."' string (note the leading space), if any, for the given tag. """ if "html-classes" not in self.extras: return "" try: html_classes_from_tag = self.extras["html-classes"] except TypeError: return "" else: if tag in html_classes_from_tag: return ' class="%s"' % html_classes_from_tag[tag] return "" def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) _fenced_code_block_re = re.compile(r''' (?:\n\n|\A\n?) ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang (.*?) # $2 = code block content ^```[ \t]*\n # closing fence ''', re.M | re.X | re.S) def _fenced_code_block_sub(self, match): return self._code_block_sub(match, is_fenced_code_block=True); def _do_fenced_code_blocks(self, text): """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).""" return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S) _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text # "smarty-pants" extra: Very liberal in interpreting a single prime as an # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and # "twixt" can be written without an initial apostrophe. This is fine because # using scare quotes (single quotation marks) is rare. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))") _contractions = ["tis", "twas", "twer", "neath", "o", "n", "round", "bout", "twixt", "nuff", "fraid", "sup"] def _do_smart_contractions(self, text): text = self._apostrophe_year_re.sub(r"&#8217;\1", text) for c in self._contractions: text = text.replace("'%s" % c, "&#8217;%s" % c) text = text.replace("'%s" % c.capitalize(), "&#8217;%s" % c.capitalize()) return text # Substitute double-quotes before single-quotes. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)") _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)') _closing_single_quote_re = re.compile(r"(?<=\S)'") _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))') def _do_smart_punctuation(self, text): """Fancifies 'single quotes', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a discussion of some diversion from the original SmartyPants. """ if "'" in text: # guard for perf text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub("&#8216;", text) text = self._closing_single_quote_re.sub("&#8217;", text) if '"' in text: # guard for perf text = self._opening_double_quote_re.sub("&#8220;", text) text = self._closing_double_quote_re.sub("&#8221;", text) text = text.replace("---", "&#8212;") text = text.replace("--", "&#8211;") text = text.replace("...", "&#8230;") text = text.replace(" . . . ", "&#8230;") text = text.replace(". . .", "&#8230;") return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = [] for i, graf in enumerate(re.split(r"\n{2,}", text)): if graf in self.html_blocks: # Unhashify HTML blocks grafs.append(self.html_blocks[graf]) else: cuddled_list = None if "cuddled-lists" in self.extras: # Need to put back trailing '\n' for `_list_item_re` # match at the end of the paragraph. li = self._list_item_re.search(graf + '\n') # Two of the same list marker in this paragraph: a likely # candidate for a list cuddled to preceding paragraph # text (issue 33). Note the `[-1]` is a quick way to # consider numeric bullets (e.g. "1." and "2.") to be # equal. if (li and len(li.group(2)) <= 3 and li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1]): start = li.start() cuddled_list = self._do_lists(graf[start:]).rstrip("\n") assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>") graf = graf[:start] # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs.append("<p>" + graf.lstrip(" \t") + "</p>") if cuddled_list: grafs.append(cuddled_list) return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in list(self._escape_table.items()): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in list(self._escape_table.items()): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text)
chibisov/drf-extensions
docs/backdoc.py
UnicodeWithAttrs.toc_html
python
def toc_html(self): if self._toc is None: return None def indent(): return ' ' * (len(h_stack) - 1) lines = [] h_stack = [0] # stack of header-level numbers for level, id, name in self._toc: if level > h_stack[-1]: lines.append("%s<ul>" % indent()) h_stack.append(level) elif level == h_stack[-1]: lines[-1] += "</li>" else: while level < h_stack[-1]: h_stack.pop() if not lines[-1].endswith("</li>"): lines[-1] += "</li>" lines.append("%s</ul></li>" % indent()) lines.append('%s<li><a href="#%s">%s</a>' % ( indent(), id, name)) while len(h_stack) > 1: h_stack.pop() if not lines[-1].endswith("</li>"): lines[-1] += "</li>" lines.append("%s</ul>" % indent()) return '\n'.join(lines) + '\n'
Return the HTML for the current TOC. This expects the `_toc` attribute to have been set on this instance.
train
https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L1912-L1943
[ "def indent():\n return ' ' * (len(h_stack) - 1)\n" ]
class UnicodeWithAttrs(unicode): """A subclass of unicode used for the return value of conversion to possibly attach some attributes. E.g. the "toc_html" attribute when the "toc" extra is used. """ metadata = None _toc = None toc_html = property(toc_html)
google/neuroglancer
python/neuroglancer/server.py
stop
python
def stop(): global global_server if global_server is not None: ioloop = global_server.ioloop def stop_ioloop(): ioloop.stop() ioloop.close() global_server.ioloop.add_callback(stop_ioloop) global_server = None
Stop the server, invalidating any viewer URLs. This allows any previously-referenced data arrays to be garbage collected if there are no other references to them.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/server.py#L245-L258
null
# @license # Copyright 2017 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, print_function import concurrent.futures import json import multiprocessing import re import socket import threading import weakref import tornado.httpserver import tornado.ioloop import tornado.netutil import tornado.web import sockjs.tornado from . import local_volume, static from .json_utils import json_encoder_default from .random_token import make_random_token from .sockjs_handler import SOCKET_PATH_REGEX, SOCKET_PATH_REGEX_WITHOUT_GROUP, SockJSHandler INFO_PATH_REGEX = r'^/neuroglancer/info/(?P<token>[^/]+)$' DATA_PATH_REGEX = r'^/neuroglancer/(?P<data_format>[^/]+)/(?P<token>[^/]+)/(?P<scale_key>[^/]+)/(?P<start_x>[0-9]+),(?P<end_x>[0-9]+)/(?P<start_y>[0-9]+),(?P<end_y>[0-9]+)/(?P<start_z>[0-9]+),(?P<end_z>[0-9]+)$' SKELETON_PATH_REGEX = r'^/neuroglancer/skeleton/(?P<key>[^/]+)/(?P<object_id>[0-9]+)$' MESH_PATH_REGEX = r'^/neuroglancer/mesh/(?P<key>[^/]+)/(?P<object_id>[0-9]+)$' STATIC_PATH_REGEX = r'^/v/(?P<viewer_token>[^/]+)/(?P<path>(?:[a-zA-Z0-9_\-][a-zA-Z0-9_\-.]*)?)$' global_static_content_source = None global_server_args = dict(bind_address='127.0.0.1', bind_port=0) debug = False class Server(object): def __init__(self, ioloop, bind_address='127.0.0.1', bind_port=0): self.viewers = weakref.WeakValueDictionary() self.token = make_random_token() self.executor = concurrent.futures.ThreadPoolExecutor( max_workers=multiprocessing.cpu_count()) self.ioloop = ioloop sockjs_router = sockjs.tornado.SockJSRouter( SockJSHandler, SOCKET_PATH_REGEX_WITHOUT_GROUP, io_loop=ioloop) sockjs_router.neuroglancer_server = self def log_function(handler): if debug: print("%d %s %.2fs" % (handler.get_status(), handler.request.uri, handler.request.request_time())) app = self.app = tornado.web.Application( [ (STATIC_PATH_REGEX, StaticPathHandler, dict(server=self)), (INFO_PATH_REGEX, VolumeInfoHandler, dict(server=self)), (DATA_PATH_REGEX, SubvolumeHandler, dict(server=self)), (SKELETON_PATH_REGEX, SkeletonHandler, dict(server=self)), (MESH_PATH_REGEX, MeshHandler, dict(server=self)), ] + sockjs_router.urls, log_function=log_function, # Set a large maximum message size to accommodate large screenshot # messages. websocket_max_message_size=100 * 1024 * 1024) http_server = tornado.httpserver.HTTPServer(app) sockets = tornado.netutil.bind_sockets(port=bind_port, address=bind_address) http_server.add_sockets(sockets) actual_port = sockets[0].getsockname()[1] global global_static_content_source if global_static_content_source is None: global_static_content_source = static.get_default_static_content_source() if bind_address == '0.0.0.0': hostname = socket.getfqdn() else: hostname = bind_address self.server_url = 'http://%s:%s' % (hostname, actual_port) def get_volume(self, key): dot_index = key.find('.') if dot_index == -1: return None viewer_token = key[:dot_index] volume_token = key[dot_index+1:] viewer = self.viewers.get(viewer_token) if viewer is None: return None return viewer.volume_manager.volumes.get(volume_token) class BaseRequestHandler(tornado.web.RequestHandler): def initialize(self, server): self.server = server class StaticPathHandler(BaseRequestHandler): def get(self, viewer_token, path): if viewer_token != self.server.token and viewer_token not in self.server.viewers: self.send_error(404) return try: data, content_type = global_static_content_source.get(path) except ValueError as e: self.send_error(404, message=e.args[0]) return self.set_header('Content-type', content_type) self.finish(data) class VolumeInfoHandler(BaseRequestHandler): def get(self, token): vol = self.server.get_volume(token) if vol is None: self.send_error(404) return self.finish(json.dumps(vol.info(), default=json_encoder_default).encode()) class SubvolumeHandler(BaseRequestHandler): @tornado.web.asynchronous def get(self, data_format, token, scale_key, start_x, end_x, start_y, end_y, start_z, end_z): start = (int(start_x), int(start_y), int(start_z)) end = (int(end_x), int(end_y), int(end_z)) vol = self.server.get_volume(token) if vol is None: self.send_error(404) return def handle_subvolume_result(f): try: data, content_type = f.result() except ValueError as e: self.send_error(400, message=e.args[0]) return self.set_header('Content-type', content_type) self.finish(data) self.server.executor.submit( vol.get_encoded_subvolume, data_format, start, end, scale_key=scale_key).add_done_callback( lambda f: self.server.ioloop.add_callback(lambda: handle_subvolume_result(f))) class MeshHandler(BaseRequestHandler): @tornado.web.asynchronous def get(self, key, object_id): object_id = int(object_id) vol = self.server.get_volume(key) if vol is None: self.send_error(404) return def handle_mesh_result(f): try: encoded_mesh = f.result() except local_volume.MeshImplementationNotAvailable: self.send_error(501, message='Mesh implementation not available') return except local_volume.MeshesNotSupportedForVolume: self.send_error(405, message='Meshes not supported for volume') return except local_volume.InvalidObjectIdForMesh: self.send_error(404, message='Mesh not available for specified object id') return except ValueError as e: self.send_error(400, message=e.args[0]) return self.set_header('Content-type', 'application/octet-stream') self.finish(encoded_mesh) self.server.executor.submit(vol.get_object_mesh, object_id).add_done_callback( lambda f: self.server.ioloop.add_callback(lambda: handle_mesh_result(f))) class SkeletonHandler(BaseRequestHandler): @tornado.web.asynchronous def get(self, key, object_id): object_id = int(object_id) vol = self.server.get_volume(key) if vol is None: self.send_error(404) if vol.skeletons is None: self.send_error(405, message='Skeletons not supported for volume') return def handle_result(f): try: encoded_skeleton = f.result() except: self.send_error(500, message=e.args[0]) return if encoded_skeleton is None: self.send_error(404, message='Skeleton not available for specified object id') return self.set_header('Content-type', 'application/octet-stream') self.finish(encoded_skeleton) def get_encoded_skeleton(skeletons, object_id): skeleton = skeletons.get_skeleton(object_id) if skeleton is None: return None return skeleton.encode(skeletons) self.server.executor.submit( get_encoded_skeleton, vol.skeletons, object_id).add_done_callback( lambda f: self.server.ioloop.add_callback(lambda: handle_result(f))) global_server = None def set_static_content_source(*args, **kwargs): global global_static_content_source global_static_content_source = static.get_static_content_source(*args, **kwargs) def set_server_bind_address(bind_address='127.0.0.1', bind_port=0): global global_server_args global_server_args = dict(bind_address=bind_address, bind_port=bind_port) def is_server_running(): return global_server is not None def get_server_url(): return global_server.server_url def start(): global global_server if global_server is None: ioloop = tornado.ioloop.IOLoop() ioloop.make_current() global_server = Server(ioloop=ioloop, **global_server_args) thread = threading.Thread(target=ioloop.start) thread.daemon = True thread.start() def register_viewer(viewer): start() global_server.viewers[viewer.token] = viewer def defer_callback(callback, *args, **kwargs): """Register `callback` to run in the server event loop thread.""" start() global_server.ioloop.add_callback(lambda: callback(*args, **kwargs))
google/neuroglancer
python/neuroglancer/server.py
defer_callback
python
def defer_callback(callback, *args, **kwargs): start() global_server.ioloop.add_callback(lambda: callback(*args, **kwargs))
Register `callback` to run in the server event loop thread.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/server.py#L280-L283
[ "def start():\n global global_server\n if global_server is None:\n ioloop = tornado.ioloop.IOLoop()\n ioloop.make_current()\n global_server = Server(ioloop=ioloop, **global_server_args)\n thread = threading.Thread(target=ioloop.start)\n thread.daemon = True\n thread.start()\n" ]
# @license # Copyright 2017 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, print_function import concurrent.futures import json import multiprocessing import re import socket import threading import weakref import tornado.httpserver import tornado.ioloop import tornado.netutil import tornado.web import sockjs.tornado from . import local_volume, static from .json_utils import json_encoder_default from .random_token import make_random_token from .sockjs_handler import SOCKET_PATH_REGEX, SOCKET_PATH_REGEX_WITHOUT_GROUP, SockJSHandler INFO_PATH_REGEX = r'^/neuroglancer/info/(?P<token>[^/]+)$' DATA_PATH_REGEX = r'^/neuroglancer/(?P<data_format>[^/]+)/(?P<token>[^/]+)/(?P<scale_key>[^/]+)/(?P<start_x>[0-9]+),(?P<end_x>[0-9]+)/(?P<start_y>[0-9]+),(?P<end_y>[0-9]+)/(?P<start_z>[0-9]+),(?P<end_z>[0-9]+)$' SKELETON_PATH_REGEX = r'^/neuroglancer/skeleton/(?P<key>[^/]+)/(?P<object_id>[0-9]+)$' MESH_PATH_REGEX = r'^/neuroglancer/mesh/(?P<key>[^/]+)/(?P<object_id>[0-9]+)$' STATIC_PATH_REGEX = r'^/v/(?P<viewer_token>[^/]+)/(?P<path>(?:[a-zA-Z0-9_\-][a-zA-Z0-9_\-.]*)?)$' global_static_content_source = None global_server_args = dict(bind_address='127.0.0.1', bind_port=0) debug = False class Server(object): def __init__(self, ioloop, bind_address='127.0.0.1', bind_port=0): self.viewers = weakref.WeakValueDictionary() self.token = make_random_token() self.executor = concurrent.futures.ThreadPoolExecutor( max_workers=multiprocessing.cpu_count()) self.ioloop = ioloop sockjs_router = sockjs.tornado.SockJSRouter( SockJSHandler, SOCKET_PATH_REGEX_WITHOUT_GROUP, io_loop=ioloop) sockjs_router.neuroglancer_server = self def log_function(handler): if debug: print("%d %s %.2fs" % (handler.get_status(), handler.request.uri, handler.request.request_time())) app = self.app = tornado.web.Application( [ (STATIC_PATH_REGEX, StaticPathHandler, dict(server=self)), (INFO_PATH_REGEX, VolumeInfoHandler, dict(server=self)), (DATA_PATH_REGEX, SubvolumeHandler, dict(server=self)), (SKELETON_PATH_REGEX, SkeletonHandler, dict(server=self)), (MESH_PATH_REGEX, MeshHandler, dict(server=self)), ] + sockjs_router.urls, log_function=log_function, # Set a large maximum message size to accommodate large screenshot # messages. websocket_max_message_size=100 * 1024 * 1024) http_server = tornado.httpserver.HTTPServer(app) sockets = tornado.netutil.bind_sockets(port=bind_port, address=bind_address) http_server.add_sockets(sockets) actual_port = sockets[0].getsockname()[1] global global_static_content_source if global_static_content_source is None: global_static_content_source = static.get_default_static_content_source() if bind_address == '0.0.0.0': hostname = socket.getfqdn() else: hostname = bind_address self.server_url = 'http://%s:%s' % (hostname, actual_port) def get_volume(self, key): dot_index = key.find('.') if dot_index == -1: return None viewer_token = key[:dot_index] volume_token = key[dot_index+1:] viewer = self.viewers.get(viewer_token) if viewer is None: return None return viewer.volume_manager.volumes.get(volume_token) class BaseRequestHandler(tornado.web.RequestHandler): def initialize(self, server): self.server = server class StaticPathHandler(BaseRequestHandler): def get(self, viewer_token, path): if viewer_token != self.server.token and viewer_token not in self.server.viewers: self.send_error(404) return try: data, content_type = global_static_content_source.get(path) except ValueError as e: self.send_error(404, message=e.args[0]) return self.set_header('Content-type', content_type) self.finish(data) class VolumeInfoHandler(BaseRequestHandler): def get(self, token): vol = self.server.get_volume(token) if vol is None: self.send_error(404) return self.finish(json.dumps(vol.info(), default=json_encoder_default).encode()) class SubvolumeHandler(BaseRequestHandler): @tornado.web.asynchronous def get(self, data_format, token, scale_key, start_x, end_x, start_y, end_y, start_z, end_z): start = (int(start_x), int(start_y), int(start_z)) end = (int(end_x), int(end_y), int(end_z)) vol = self.server.get_volume(token) if vol is None: self.send_error(404) return def handle_subvolume_result(f): try: data, content_type = f.result() except ValueError as e: self.send_error(400, message=e.args[0]) return self.set_header('Content-type', content_type) self.finish(data) self.server.executor.submit( vol.get_encoded_subvolume, data_format, start, end, scale_key=scale_key).add_done_callback( lambda f: self.server.ioloop.add_callback(lambda: handle_subvolume_result(f))) class MeshHandler(BaseRequestHandler): @tornado.web.asynchronous def get(self, key, object_id): object_id = int(object_id) vol = self.server.get_volume(key) if vol is None: self.send_error(404) return def handle_mesh_result(f): try: encoded_mesh = f.result() except local_volume.MeshImplementationNotAvailable: self.send_error(501, message='Mesh implementation not available') return except local_volume.MeshesNotSupportedForVolume: self.send_error(405, message='Meshes not supported for volume') return except local_volume.InvalidObjectIdForMesh: self.send_error(404, message='Mesh not available for specified object id') return except ValueError as e: self.send_error(400, message=e.args[0]) return self.set_header('Content-type', 'application/octet-stream') self.finish(encoded_mesh) self.server.executor.submit(vol.get_object_mesh, object_id).add_done_callback( lambda f: self.server.ioloop.add_callback(lambda: handle_mesh_result(f))) class SkeletonHandler(BaseRequestHandler): @tornado.web.asynchronous def get(self, key, object_id): object_id = int(object_id) vol = self.server.get_volume(key) if vol is None: self.send_error(404) if vol.skeletons is None: self.send_error(405, message='Skeletons not supported for volume') return def handle_result(f): try: encoded_skeleton = f.result() except: self.send_error(500, message=e.args[0]) return if encoded_skeleton is None: self.send_error(404, message='Skeleton not available for specified object id') return self.set_header('Content-type', 'application/octet-stream') self.finish(encoded_skeleton) def get_encoded_skeleton(skeletons, object_id): skeleton = skeletons.get_skeleton(object_id) if skeleton is None: return None return skeleton.encode(skeletons) self.server.executor.submit( get_encoded_skeleton, vol.skeletons, object_id).add_done_callback( lambda f: self.server.ioloop.add_callback(lambda: handle_result(f))) global_server = None def set_static_content_source(*args, **kwargs): global global_static_content_source global_static_content_source = static.get_static_content_source(*args, **kwargs) def set_server_bind_address(bind_address='127.0.0.1', bind_port=0): global global_server_args global_server_args = dict(bind_address=bind_address, bind_port=bind_port) def is_server_running(): return global_server is not None def stop(): """Stop the server, invalidating any viewer URLs. This allows any previously-referenced data arrays to be garbage collected if there are no other references to them. """ global global_server if global_server is not None: ioloop = global_server.ioloop def stop_ioloop(): ioloop.stop() ioloop.close() global_server.ioloop.add_callback(stop_ioloop) global_server = None def get_server_url(): return global_server.server_url def start(): global global_server if global_server is None: ioloop = tornado.ioloop.IOLoop() ioloop.make_current() global_server = Server(ioloop=ioloop, **global_server_args) thread = threading.Thread(target=ioloop.start) thread.daemon = True thread.start() def register_viewer(viewer): start() global_server.viewers[viewer.token] = viewer
google/neuroglancer
python/neuroglancer/downsample_scales.py
compute_near_isotropic_downsampling_scales
python
def compute_near_isotropic_downsampling_scales(size, voxel_size, dimensions_to_downsample, max_scales=DEFAULT_MAX_DOWNSAMPLING_SCALES, max_downsampling=DEFAULT_MAX_DOWNSAMPLING, max_downsampled_size=DEFAULT_MAX_DOWNSAMPLED_SIZE): num_dims = len(voxel_size) cur_scale = np.ones((num_dims, ), dtype=int) scales = [tuple(cur_scale)] while (len(scales) < max_scales and (np.prod(cur_scale) < max_downsampling) and (size / cur_scale).max() > max_downsampled_size): # Find dimension with smallest voxelsize. cur_voxel_size = cur_scale * voxel_size smallest_cur_voxel_size_dim = dimensions_to_downsample[np.argmin(cur_voxel_size[ dimensions_to_downsample])] cur_scale[smallest_cur_voxel_size_dim] *= 2 target_voxel_size = cur_voxel_size[smallest_cur_voxel_size_dim] * 2 for d in dimensions_to_downsample: if d == smallest_cur_voxel_size_dim: continue d_voxel_size = cur_voxel_size[d] if abs(d_voxel_size - target_voxel_size) > abs(d_voxel_size * 2 - target_voxel_size): cur_scale[d] *= 2 scales.append(tuple(cur_scale)) return scales
Compute a list of successive downsampling factors.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/downsample_scales.py#L24-L50
null
# @license # Copyright 2016 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import division import numpy as np DEFAULT_MAX_DOWNSAMPLING = 64 DEFAULT_MAX_DOWNSAMPLED_SIZE = 128 DEFAULT_MAX_DOWNSAMPLING_SCALES = float('inf') def compute_two_dimensional_near_isotropic_downsampling_scales( size, voxel_size, max_scales=float('inf'), max_downsampling=DEFAULT_MAX_DOWNSAMPLING, max_downsampled_size=DEFAULT_MAX_DOWNSAMPLED_SIZE): """Compute a list of successive downsampling factors for 2-d tiles.""" max_scales = min(max_scales, 10) # First compute a set of 2-d downsamplings for XY, XZ, and YZ with a high # number of max_scales, and ignoring other criteria. scales_transpose = [ compute_near_isotropic_downsampling_scales( size=size, voxel_size=voxel_size, dimensions_to_downsample=dimensions_to_downsample, max_scales=max_scales, max_downsampling=float('inf'), max_downsampled_size=0, ) for dimensions_to_downsample in [[0, 1], [0, 2], [1, 2]] ] # Truncate all list of scales to the same length, once the stopping criteria # is reached for all values of dimensions_to_downsample. scales = [((1, ) * 3, ) * 3] size = np.array(size) def scale_satisfies_criteria(scale): return np.prod(scale) < max_downsampling and (size / scale).max() > max_downsampled_size for i in range(1, max_scales): cur_scales = tuple(scales_transpose[d][i] for d in range(3)) if all(not scale_satisfies_criteria(scale) for scale in cur_scales): break scales.append(cur_scales) return scales
google/neuroglancer
python/neuroglancer/downsample_scales.py
compute_two_dimensional_near_isotropic_downsampling_scales
python
def compute_two_dimensional_near_isotropic_downsampling_scales( size, voxel_size, max_scales=float('inf'), max_downsampling=DEFAULT_MAX_DOWNSAMPLING, max_downsampled_size=DEFAULT_MAX_DOWNSAMPLED_SIZE): max_scales = min(max_scales, 10) # First compute a set of 2-d downsamplings for XY, XZ, and YZ with a high # number of max_scales, and ignoring other criteria. scales_transpose = [ compute_near_isotropic_downsampling_scales( size=size, voxel_size=voxel_size, dimensions_to_downsample=dimensions_to_downsample, max_scales=max_scales, max_downsampling=float('inf'), max_downsampled_size=0, ) for dimensions_to_downsample in [[0, 1], [0, 2], [1, 2]] ] # Truncate all list of scales to the same length, once the stopping criteria # is reached for all values of dimensions_to_downsample. scales = [((1, ) * 3, ) * 3] size = np.array(size) def scale_satisfies_criteria(scale): return np.prod(scale) < max_downsampling and (size / scale).max() > max_downsampled_size for i in range(1, max_scales): cur_scales = tuple(scales_transpose[d][i] for d in range(3)) if all(not scale_satisfies_criteria(scale) for scale in cur_scales): break scales.append(cur_scales) return scales
Compute a list of successive downsampling factors for 2-d tiles.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/downsample_scales.py#L53-L88
null
# @license # Copyright 2016 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import division import numpy as np DEFAULT_MAX_DOWNSAMPLING = 64 DEFAULT_MAX_DOWNSAMPLED_SIZE = 128 DEFAULT_MAX_DOWNSAMPLING_SCALES = float('inf') def compute_near_isotropic_downsampling_scales(size, voxel_size, dimensions_to_downsample, max_scales=DEFAULT_MAX_DOWNSAMPLING_SCALES, max_downsampling=DEFAULT_MAX_DOWNSAMPLING, max_downsampled_size=DEFAULT_MAX_DOWNSAMPLED_SIZE): """Compute a list of successive downsampling factors.""" num_dims = len(voxel_size) cur_scale = np.ones((num_dims, ), dtype=int) scales = [tuple(cur_scale)] while (len(scales) < max_scales and (np.prod(cur_scale) < max_downsampling) and (size / cur_scale).max() > max_downsampled_size): # Find dimension with smallest voxelsize. cur_voxel_size = cur_scale * voxel_size smallest_cur_voxel_size_dim = dimensions_to_downsample[np.argmin(cur_voxel_size[ dimensions_to_downsample])] cur_scale[smallest_cur_voxel_size_dim] *= 2 target_voxel_size = cur_voxel_size[smallest_cur_voxel_size_dim] * 2 for d in dimensions_to_downsample: if d == smallest_cur_voxel_size_dim: continue d_voxel_size = cur_voxel_size[d] if abs(d_voxel_size - target_voxel_size) > abs(d_voxel_size * 2 - target_voxel_size): cur_scale[d] *= 2 scales.append(tuple(cur_scale)) return scales
google/neuroglancer
python/neuroglancer/json_utils.py
json_encoder_default
python
def json_encoder_default(obj): if isinstance(obj, numbers.Integral) and (obj < min_safe_integer or obj > max_safe_integer): return str(obj) if isinstance(obj, np.integer): return str(obj) elif isinstance(obj, np.floating): return float(obj) elif isinstance(obj, np.ndarray): return list(obj) elif isinstance(obj, (set, frozenset)): return list(obj) raise TypeError
JSON encoder function that handles some numpy types.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/json_utils.py#L28-L40
null
# @license # Copyright 2017 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import import collections import json import numbers import numpy as np from . import local_volume min_safe_integer = -9007199254740991 max_safe_integer = 9007199254740991 def json_encoder_default_for_repr(obj): if isinstance(obj, local_volume.LocalVolume): return '<LocalVolume>' return json_encoder_default(obj) def decode_json(x): return json.loads(x, object_pairs_hook=collections.OrderedDict) def encode_json(obj): return json.dumps(obj, default=json_encoder_default) def encode_json_for_repr(obj): return json.dumps(obj, default=json_encoder_default_for_repr)
google/neuroglancer
python/neuroglancer/sockjs_handler.py
StateHandler._on_state_changed
python
def _on_state_changed(self): raw_state, generation = self.state.raw_state_and_generation if generation != self._last_generation: self._last_generation = generation self._send_update(raw_state, generation)
Invoked when the viewer state changes.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/sockjs_handler.py#L83-L88
null
class StateHandler(object): def __init__(self, state, io_loop, send_update, receive_updates=True): self.state = state self._send_update = send_update self._receive_updates = receive_updates self.io_loop = io_loop self._last_generation = None if send_update is not None: self._on_state_changed_callback = ( lambda: self.io_loop.add_callback(self._on_state_changed)) self.state.add_changed_callback(self._on_state_changed_callback) def request_send_state(self, generation): if self._send_update is not None: self._last_generation = generation self._on_state_changed() def receive_update(self, raw_state, generation): if self._receive_updates: self._last_generation = generation self.state.set_state(raw_state, generation) def close(self): if self._send_update is not None: self.state.remove_changed_callback(self._on_state_changed_callback) del self._on_state_changed_callback
google/neuroglancer
python/neuroglancer/futures.py
future_then_immediate
python
def future_then_immediate(future, func): result = concurrent.futures.Future() def on_done(f): try: result.set_result(func(f.result())) except Exception as e: result.set_exception(e) future.add_done_callback(on_done) return result
Returns a future that maps the result of `future` by `func`. If `future` succeeds, sets the result of the returned future to `func(future.result())`. If `future` fails or `func` raises an exception, the exception is stored in the returned future. If `future` has not yet finished, `func` is invoked by the same thread that finishes it. Otherwise, it is invoked immediately in the same thread that calls `future_then_immediate`.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/futures.py#L23-L41
null
# @license # Copyright 2017 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Various extensions to the concurrent.futures module.""" from __future__ import absolute_import import concurrent.futures import threading def run_on_new_thread(func, daemon=True): """Calls `func()` from a new thread. :param daemon: Specifies whether the thread should be in daemon mode. :returns: A concurrent.futures.Future object representing the result. """ f = concurrent.futures.Future() def wrapper(): if not f.set_running_or_notify_cancel(): return try: f.set_result(func()) except Exception as e: f.set_exception(e) t = threading.Thread(target=wrapper) t.daemon = daemon t.start() return f
google/neuroglancer
python/neuroglancer/futures.py
run_on_new_thread
python
def run_on_new_thread(func, daemon=True): f = concurrent.futures.Future() def wrapper(): if not f.set_running_or_notify_cancel(): return try: f.set_result(func()) except Exception as e: f.set_exception(e) t = threading.Thread(target=wrapper) t.daemon = daemon t.start() return f
Calls `func()` from a new thread. :param daemon: Specifies whether the thread should be in daemon mode. :returns: A concurrent.futures.Future object representing the result.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/futures.py#L44-L62
null
# @license # Copyright 2017 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Various extensions to the concurrent.futures module.""" from __future__ import absolute_import import concurrent.futures import threading def future_then_immediate(future, func): """Returns a future that maps the result of `future` by `func`. If `future` succeeds, sets the result of the returned future to `func(future.result())`. If `future` fails or `func` raises an exception, the exception is stored in the returned future. If `future` has not yet finished, `func` is invoked by the same thread that finishes it. Otherwise, it is invoked immediately in the same thread that calls `future_then_immediate`. """ result = concurrent.futures.Future() def on_done(f): try: result.set_result(func(f.result())) except Exception as e: result.set_exception(e) future.add_done_callback(on_done) return result
google/neuroglancer
python/neuroglancer/downsample.py
downsample_with_averaging
python
def downsample_with_averaging(array, factor): factor = tuple(factor) output_shape = tuple(int(math.ceil(s / f)) for s, f in zip(array.shape, factor)) temp = np.zeros(output_shape, dtype=np.float32) counts = np.zeros(output_shape, np.int) for offset in np.ndindex(factor): part = array[tuple(np.s_[o::f] for o, f in zip(offset, factor))] indexing_expr = tuple(np.s_[:s] for s in part.shape) temp[indexing_expr] += part counts[indexing_expr] += 1 return np.cast[array.dtype](temp / counts)
Downsample x by factor using averaging. @return: The downsampled array, of the same type as x.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/downsample.py#L22-L36
null
# @license # Copyright 2016 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import division import math import numpy as np def downsample_with_striding(array, factor): """Downsample x by factor using striding. @return: The downsampled array, of the same type as x. """ return array[tuple(np.s_[::f] for f in factor)]
google/neuroglancer
python/neuroglancer/downsample.py
downsample_with_striding
python
def downsample_with_striding(array, factor): return array[tuple(np.s_[::f] for f in factor)]
Downsample x by factor using striding. @return: The downsampled array, of the same type as x.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/downsample.py#L39-L44
null
# @license # Copyright 2016 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import division import math import numpy as np def downsample_with_averaging(array, factor): """Downsample x by factor using averaging. @return: The downsampled array, of the same type as x. """ factor = tuple(factor) output_shape = tuple(int(math.ceil(s / f)) for s, f in zip(array.shape, factor)) temp = np.zeros(output_shape, dtype=np.float32) counts = np.zeros(output_shape, np.int) for offset in np.ndindex(factor): part = array[tuple(np.s_[o::f] for o, f in zip(offset, factor))] indexing_expr = tuple(np.s_[:s] for s in part.shape) temp[indexing_expr] += part counts[indexing_expr] += 1 return np.cast[array.dtype](temp / counts)
google/neuroglancer
python/neuroglancer/equivalence_map.py
EquivalenceMap._get_representative
python
def _get_representative(self, obj): if obj not in self._parents: self._parents[obj] = obj self._weights[obj] = 1 self._prev_next[obj] = [obj, obj] self._min_values[obj] = obj return obj path = [obj] root = self._parents[obj] while root != path[-1]: path.append(root) root = self._parents[root] # compress the path and return for ancestor in path: self._parents[ancestor] = root return root
Finds and returns the root of the set containing `obj`.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/equivalence_map.py#L47-L66
null
class EquivalenceMap(object): """Union-find data structure""" supports_readonly = True def __init__(self, existing=None, _readonly=False): """Create a new empty union-find structure.""" if isinstance(existing, EquivalenceMap): self._weights = existing._weights.copy() self._parents = existing._parents.copy() self._prev_next = existing._prev_next.copy() self._min_values = existing._min_values.copy() else: self._weights = {} self._parents = {} self._prev_next = {} self._min_values = {} self._readonly = False if existing is not None: if isinstance(existing, dict): existing = six.viewitems(existing) for group in existing: self.union(*group) self._readonly = _readonly def __getitem__(self, obj): """Returns the minimum element in the set containing `obj`.""" if obj not in self._parents: return obj return self._min_values[self._get_representative(obj)] def __iter__(self): """Iterates over all elements known to this equivalence map.""" return iter(self._parents) def items(self): return six.viewitems(self._parents) def keys(self): return six.viewkeys(self._parents) def clear(self): self._weights.clear() self._parents.clear() self._prev_next.clear() self._min_values.clear() def union(self, *args): """Unions the equivalence classes containing the elements in `*args`.""" if self._readonly: raise AttributeError if len(args) == 0: return None if len(args) == 1: return self[args[0]] for a, b in zip(args[:-1], args[1:]): result = self._union_pair(a, b) return result def _union_pair(self, a, b): a = self._get_representative(a) b = self._get_representative(b) if a == b: return self._min_values[a] if self._weights[a] < self._weights[b]: a, b = (b, a) self._min_values[a] = min(self._min_values[a], self._min_values[b]) a_links_new = self._prev_next[a] a_links_old = tuple(a_links_new) b_links_new = self._prev_next[b] b_links_old = tuple(b_links_new) # We want to splice b's list at the end of a's list # Splice beginning of b's list into end of a's list b_links_new[0] = a_links_old[0] self._prev_next[a_links_old[0]][1] = b # Splice end of b's list into end of a's list # last element of a's list is set to last element of b's list a_links_new[0] = b_links_old[0] # fix next pointer for last element of b's list self._prev_next[b_links_old[0]][1] = a self._weights[a] += self._weights[b] self._parents[b] = a return self._min_values[a] def members(self, x): """Yields the members of the equivalence class containing `x`.""" if x not in self._parents: yield x return cur_x = x while True: yield cur_x cur_x = self._prev_next[cur_x][1] if cur_x == x: break def sets(self): """Returns the equivalence classes as a set of sets.""" sets = {} for x in self._parents: sets.setdefault(self[x], set()).add(x) return frozenset(frozenset(v) for v in six.viewvalues(sets)) def to_json(self): """Returns the equivalence classes a sorted list of sorted lists.""" sets = self.sets() return sorted(sorted(x) for x in sets) def __copy__(self): """Does not preserve _readonly attribute.""" return EquivalenceMap(self) def __deepcopy__(self, memo): """Does not preserve _readonly attribute.""" result = EquivalenceMap() result._parents = copy.deepcopy(self._parents, memo) result._weights = copy.deepcopy(self._weights, memo) result._prev_next = copy.deepcopy(self._prev_next, memo) result._min_values = copy.deepcopy(self._min_values, memo) return result def copy(self): """Returns a copy of the equivalence map.""" return EquivalenceMap(self) def delete_set(self, x): """Removes the equivalence class containing `x`.""" if x not in self._parents: return members = list(self.members(x)) for v in members: del self._parents[v] del self._weights[v] del self._prev_next[v] del self._min_values[v] def isolate_element(self, x): """Isolates `x` from its equivalence class.""" members = list(self.members(x)) self.delete_set(x) self.union(*(v for v in members if v != x))
google/neuroglancer
python/neuroglancer/equivalence_map.py
EquivalenceMap.union
python
def union(self, *args): if self._readonly: raise AttributeError if len(args) == 0: return None if len(args) == 1: return self[args[0]] for a, b in zip(args[:-1], args[1:]): result = self._union_pair(a, b) return result
Unions the equivalence classes containing the elements in `*args`.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/equivalence_map.py#L90-L101
[ "def _union_pair(self, a, b):\n a = self._get_representative(a)\n b = self._get_representative(b)\n if a == b:\n return self._min_values[a]\n if self._weights[a] < self._weights[b]:\n a, b = (b, a)\n\n self._min_values[a] = min(self._min_values[a], self._min_values[b])\n\n a_links_new = self._prev_next[a]\n a_links_old = tuple(a_links_new)\n b_links_new = self._prev_next[b]\n b_links_old = tuple(b_links_new)\n\n # We want to splice b's list at the end of a's list\n\n # Splice beginning of b's list into end of a's list\n b_links_new[0] = a_links_old[0]\n self._prev_next[a_links_old[0]][1] = b\n\n # Splice end of b's list into end of a's list\n\n # last element of a's list is set to last element of b's list\n a_links_new[0] = b_links_old[0]\n # fix next pointer for last element of b's list\n self._prev_next[b_links_old[0]][1] = a\n self._weights[a] += self._weights[b]\n self._parents[b] = a\n return self._min_values[a]\n" ]
class EquivalenceMap(object): """Union-find data structure""" supports_readonly = True def __init__(self, existing=None, _readonly=False): """Create a new empty union-find structure.""" if isinstance(existing, EquivalenceMap): self._weights = existing._weights.copy() self._parents = existing._parents.copy() self._prev_next = existing._prev_next.copy() self._min_values = existing._min_values.copy() else: self._weights = {} self._parents = {} self._prev_next = {} self._min_values = {} self._readonly = False if existing is not None: if isinstance(existing, dict): existing = six.viewitems(existing) for group in existing: self.union(*group) self._readonly = _readonly def _get_representative(self, obj): """Finds and returns the root of the set containing `obj`.""" if obj not in self._parents: self._parents[obj] = obj self._weights[obj] = 1 self._prev_next[obj] = [obj, obj] self._min_values[obj] = obj return obj path = [obj] root = self._parents[obj] while root != path[-1]: path.append(root) root = self._parents[root] # compress the path and return for ancestor in path: self._parents[ancestor] = root return root def __getitem__(self, obj): """Returns the minimum element in the set containing `obj`.""" if obj not in self._parents: return obj return self._min_values[self._get_representative(obj)] def __iter__(self): """Iterates over all elements known to this equivalence map.""" return iter(self._parents) def items(self): return six.viewitems(self._parents) def keys(self): return six.viewkeys(self._parents) def clear(self): self._weights.clear() self._parents.clear() self._prev_next.clear() self._min_values.clear() def _union_pair(self, a, b): a = self._get_representative(a) b = self._get_representative(b) if a == b: return self._min_values[a] if self._weights[a] < self._weights[b]: a, b = (b, a) self._min_values[a] = min(self._min_values[a], self._min_values[b]) a_links_new = self._prev_next[a] a_links_old = tuple(a_links_new) b_links_new = self._prev_next[b] b_links_old = tuple(b_links_new) # We want to splice b's list at the end of a's list # Splice beginning of b's list into end of a's list b_links_new[0] = a_links_old[0] self._prev_next[a_links_old[0]][1] = b # Splice end of b's list into end of a's list # last element of a's list is set to last element of b's list a_links_new[0] = b_links_old[0] # fix next pointer for last element of b's list self._prev_next[b_links_old[0]][1] = a self._weights[a] += self._weights[b] self._parents[b] = a return self._min_values[a] def members(self, x): """Yields the members of the equivalence class containing `x`.""" if x not in self._parents: yield x return cur_x = x while True: yield cur_x cur_x = self._prev_next[cur_x][1] if cur_x == x: break def sets(self): """Returns the equivalence classes as a set of sets.""" sets = {} for x in self._parents: sets.setdefault(self[x], set()).add(x) return frozenset(frozenset(v) for v in six.viewvalues(sets)) def to_json(self): """Returns the equivalence classes a sorted list of sorted lists.""" sets = self.sets() return sorted(sorted(x) for x in sets) def __copy__(self): """Does not preserve _readonly attribute.""" return EquivalenceMap(self) def __deepcopy__(self, memo): """Does not preserve _readonly attribute.""" result = EquivalenceMap() result._parents = copy.deepcopy(self._parents, memo) result._weights = copy.deepcopy(self._weights, memo) result._prev_next = copy.deepcopy(self._prev_next, memo) result._min_values = copy.deepcopy(self._min_values, memo) return result def copy(self): """Returns a copy of the equivalence map.""" return EquivalenceMap(self) def delete_set(self, x): """Removes the equivalence class containing `x`.""" if x not in self._parents: return members = list(self.members(x)) for v in members: del self._parents[v] del self._weights[v] del self._prev_next[v] del self._min_values[v] def isolate_element(self, x): """Isolates `x` from its equivalence class.""" members = list(self.members(x)) self.delete_set(x) self.union(*(v for v in members if v != x))
google/neuroglancer
python/neuroglancer/equivalence_map.py
EquivalenceMap.members
python
def members(self, x): if x not in self._parents: yield x return cur_x = x while True: yield cur_x cur_x = self._prev_next[cur_x][1] if cur_x == x: break
Yields the members of the equivalence class containing `x`.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/equivalence_map.py#L134-L144
null
class EquivalenceMap(object): """Union-find data structure""" supports_readonly = True def __init__(self, existing=None, _readonly=False): """Create a new empty union-find structure.""" if isinstance(existing, EquivalenceMap): self._weights = existing._weights.copy() self._parents = existing._parents.copy() self._prev_next = existing._prev_next.copy() self._min_values = existing._min_values.copy() else: self._weights = {} self._parents = {} self._prev_next = {} self._min_values = {} self._readonly = False if existing is not None: if isinstance(existing, dict): existing = six.viewitems(existing) for group in existing: self.union(*group) self._readonly = _readonly def _get_representative(self, obj): """Finds and returns the root of the set containing `obj`.""" if obj not in self._parents: self._parents[obj] = obj self._weights[obj] = 1 self._prev_next[obj] = [obj, obj] self._min_values[obj] = obj return obj path = [obj] root = self._parents[obj] while root != path[-1]: path.append(root) root = self._parents[root] # compress the path and return for ancestor in path: self._parents[ancestor] = root return root def __getitem__(self, obj): """Returns the minimum element in the set containing `obj`.""" if obj not in self._parents: return obj return self._min_values[self._get_representative(obj)] def __iter__(self): """Iterates over all elements known to this equivalence map.""" return iter(self._parents) def items(self): return six.viewitems(self._parents) def keys(self): return six.viewkeys(self._parents) def clear(self): self._weights.clear() self._parents.clear() self._prev_next.clear() self._min_values.clear() def union(self, *args): """Unions the equivalence classes containing the elements in `*args`.""" if self._readonly: raise AttributeError if len(args) == 0: return None if len(args) == 1: return self[args[0]] for a, b in zip(args[:-1], args[1:]): result = self._union_pair(a, b) return result def _union_pair(self, a, b): a = self._get_representative(a) b = self._get_representative(b) if a == b: return self._min_values[a] if self._weights[a] < self._weights[b]: a, b = (b, a) self._min_values[a] = min(self._min_values[a], self._min_values[b]) a_links_new = self._prev_next[a] a_links_old = tuple(a_links_new) b_links_new = self._prev_next[b] b_links_old = tuple(b_links_new) # We want to splice b's list at the end of a's list # Splice beginning of b's list into end of a's list b_links_new[0] = a_links_old[0] self._prev_next[a_links_old[0]][1] = b # Splice end of b's list into end of a's list # last element of a's list is set to last element of b's list a_links_new[0] = b_links_old[0] # fix next pointer for last element of b's list self._prev_next[b_links_old[0]][1] = a self._weights[a] += self._weights[b] self._parents[b] = a return self._min_values[a] def sets(self): """Returns the equivalence classes as a set of sets.""" sets = {} for x in self._parents: sets.setdefault(self[x], set()).add(x) return frozenset(frozenset(v) for v in six.viewvalues(sets)) def to_json(self): """Returns the equivalence classes a sorted list of sorted lists.""" sets = self.sets() return sorted(sorted(x) for x in sets) def __copy__(self): """Does not preserve _readonly attribute.""" return EquivalenceMap(self) def __deepcopy__(self, memo): """Does not preserve _readonly attribute.""" result = EquivalenceMap() result._parents = copy.deepcopy(self._parents, memo) result._weights = copy.deepcopy(self._weights, memo) result._prev_next = copy.deepcopy(self._prev_next, memo) result._min_values = copy.deepcopy(self._min_values, memo) return result def copy(self): """Returns a copy of the equivalence map.""" return EquivalenceMap(self) def delete_set(self, x): """Removes the equivalence class containing `x`.""" if x not in self._parents: return members = list(self.members(x)) for v in members: del self._parents[v] del self._weights[v] del self._prev_next[v] del self._min_values[v] def isolate_element(self, x): """Isolates `x` from its equivalence class.""" members = list(self.members(x)) self.delete_set(x) self.union(*(v for v in members if v != x))
google/neuroglancer
python/neuroglancer/equivalence_map.py
EquivalenceMap.sets
python
def sets(self): sets = {} for x in self._parents: sets.setdefault(self[x], set()).add(x) return frozenset(frozenset(v) for v in six.viewvalues(sets))
Returns the equivalence classes as a set of sets.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/equivalence_map.py#L146-L151
null
class EquivalenceMap(object): """Union-find data structure""" supports_readonly = True def __init__(self, existing=None, _readonly=False): """Create a new empty union-find structure.""" if isinstance(existing, EquivalenceMap): self._weights = existing._weights.copy() self._parents = existing._parents.copy() self._prev_next = existing._prev_next.copy() self._min_values = existing._min_values.copy() else: self._weights = {} self._parents = {} self._prev_next = {} self._min_values = {} self._readonly = False if existing is not None: if isinstance(existing, dict): existing = six.viewitems(existing) for group in existing: self.union(*group) self._readonly = _readonly def _get_representative(self, obj): """Finds and returns the root of the set containing `obj`.""" if obj not in self._parents: self._parents[obj] = obj self._weights[obj] = 1 self._prev_next[obj] = [obj, obj] self._min_values[obj] = obj return obj path = [obj] root = self._parents[obj] while root != path[-1]: path.append(root) root = self._parents[root] # compress the path and return for ancestor in path: self._parents[ancestor] = root return root def __getitem__(self, obj): """Returns the minimum element in the set containing `obj`.""" if obj not in self._parents: return obj return self._min_values[self._get_representative(obj)] def __iter__(self): """Iterates over all elements known to this equivalence map.""" return iter(self._parents) def items(self): return six.viewitems(self._parents) def keys(self): return six.viewkeys(self._parents) def clear(self): self._weights.clear() self._parents.clear() self._prev_next.clear() self._min_values.clear() def union(self, *args): """Unions the equivalence classes containing the elements in `*args`.""" if self._readonly: raise AttributeError if len(args) == 0: return None if len(args) == 1: return self[args[0]] for a, b in zip(args[:-1], args[1:]): result = self._union_pair(a, b) return result def _union_pair(self, a, b): a = self._get_representative(a) b = self._get_representative(b) if a == b: return self._min_values[a] if self._weights[a] < self._weights[b]: a, b = (b, a) self._min_values[a] = min(self._min_values[a], self._min_values[b]) a_links_new = self._prev_next[a] a_links_old = tuple(a_links_new) b_links_new = self._prev_next[b] b_links_old = tuple(b_links_new) # We want to splice b's list at the end of a's list # Splice beginning of b's list into end of a's list b_links_new[0] = a_links_old[0] self._prev_next[a_links_old[0]][1] = b # Splice end of b's list into end of a's list # last element of a's list is set to last element of b's list a_links_new[0] = b_links_old[0] # fix next pointer for last element of b's list self._prev_next[b_links_old[0]][1] = a self._weights[a] += self._weights[b] self._parents[b] = a return self._min_values[a] def members(self, x): """Yields the members of the equivalence class containing `x`.""" if x not in self._parents: yield x return cur_x = x while True: yield cur_x cur_x = self._prev_next[cur_x][1] if cur_x == x: break def to_json(self): """Returns the equivalence classes a sorted list of sorted lists.""" sets = self.sets() return sorted(sorted(x) for x in sets) def __copy__(self): """Does not preserve _readonly attribute.""" return EquivalenceMap(self) def __deepcopy__(self, memo): """Does not preserve _readonly attribute.""" result = EquivalenceMap() result._parents = copy.deepcopy(self._parents, memo) result._weights = copy.deepcopy(self._weights, memo) result._prev_next = copy.deepcopy(self._prev_next, memo) result._min_values = copy.deepcopy(self._min_values, memo) return result def copy(self): """Returns a copy of the equivalence map.""" return EquivalenceMap(self) def delete_set(self, x): """Removes the equivalence class containing `x`.""" if x not in self._parents: return members = list(self.members(x)) for v in members: del self._parents[v] del self._weights[v] del self._prev_next[v] del self._min_values[v] def isolate_element(self, x): """Isolates `x` from its equivalence class.""" members = list(self.members(x)) self.delete_set(x) self.union(*(v for v in members if v != x))
google/neuroglancer
python/neuroglancer/equivalence_map.py
EquivalenceMap.to_json
python
def to_json(self): sets = self.sets() return sorted(sorted(x) for x in sets)
Returns the equivalence classes a sorted list of sorted lists.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/equivalence_map.py#L153-L156
[ "def sets(self):\n \"\"\"Returns the equivalence classes as a set of sets.\"\"\"\n sets = {}\n for x in self._parents:\n sets.setdefault(self[x], set()).add(x)\n return frozenset(frozenset(v) for v in six.viewvalues(sets))\n" ]
class EquivalenceMap(object): """Union-find data structure""" supports_readonly = True def __init__(self, existing=None, _readonly=False): """Create a new empty union-find structure.""" if isinstance(existing, EquivalenceMap): self._weights = existing._weights.copy() self._parents = existing._parents.copy() self._prev_next = existing._prev_next.copy() self._min_values = existing._min_values.copy() else: self._weights = {} self._parents = {} self._prev_next = {} self._min_values = {} self._readonly = False if existing is not None: if isinstance(existing, dict): existing = six.viewitems(existing) for group in existing: self.union(*group) self._readonly = _readonly def _get_representative(self, obj): """Finds and returns the root of the set containing `obj`.""" if obj not in self._parents: self._parents[obj] = obj self._weights[obj] = 1 self._prev_next[obj] = [obj, obj] self._min_values[obj] = obj return obj path = [obj] root = self._parents[obj] while root != path[-1]: path.append(root) root = self._parents[root] # compress the path and return for ancestor in path: self._parents[ancestor] = root return root def __getitem__(self, obj): """Returns the minimum element in the set containing `obj`.""" if obj not in self._parents: return obj return self._min_values[self._get_representative(obj)] def __iter__(self): """Iterates over all elements known to this equivalence map.""" return iter(self._parents) def items(self): return six.viewitems(self._parents) def keys(self): return six.viewkeys(self._parents) def clear(self): self._weights.clear() self._parents.clear() self._prev_next.clear() self._min_values.clear() def union(self, *args): """Unions the equivalence classes containing the elements in `*args`.""" if self._readonly: raise AttributeError if len(args) == 0: return None if len(args) == 1: return self[args[0]] for a, b in zip(args[:-1], args[1:]): result = self._union_pair(a, b) return result def _union_pair(self, a, b): a = self._get_representative(a) b = self._get_representative(b) if a == b: return self._min_values[a] if self._weights[a] < self._weights[b]: a, b = (b, a) self._min_values[a] = min(self._min_values[a], self._min_values[b]) a_links_new = self._prev_next[a] a_links_old = tuple(a_links_new) b_links_new = self._prev_next[b] b_links_old = tuple(b_links_new) # We want to splice b's list at the end of a's list # Splice beginning of b's list into end of a's list b_links_new[0] = a_links_old[0] self._prev_next[a_links_old[0]][1] = b # Splice end of b's list into end of a's list # last element of a's list is set to last element of b's list a_links_new[0] = b_links_old[0] # fix next pointer for last element of b's list self._prev_next[b_links_old[0]][1] = a self._weights[a] += self._weights[b] self._parents[b] = a return self._min_values[a] def members(self, x): """Yields the members of the equivalence class containing `x`.""" if x not in self._parents: yield x return cur_x = x while True: yield cur_x cur_x = self._prev_next[cur_x][1] if cur_x == x: break def sets(self): """Returns the equivalence classes as a set of sets.""" sets = {} for x in self._parents: sets.setdefault(self[x], set()).add(x) return frozenset(frozenset(v) for v in six.viewvalues(sets)) def __copy__(self): """Does not preserve _readonly attribute.""" return EquivalenceMap(self) def __deepcopy__(self, memo): """Does not preserve _readonly attribute.""" result = EquivalenceMap() result._parents = copy.deepcopy(self._parents, memo) result._weights = copy.deepcopy(self._weights, memo) result._prev_next = copy.deepcopy(self._prev_next, memo) result._min_values = copy.deepcopy(self._min_values, memo) return result def copy(self): """Returns a copy of the equivalence map.""" return EquivalenceMap(self) def delete_set(self, x): """Removes the equivalence class containing `x`.""" if x not in self._parents: return members = list(self.members(x)) for v in members: del self._parents[v] del self._weights[v] del self._prev_next[v] del self._min_values[v] def isolate_element(self, x): """Isolates `x` from its equivalence class.""" members = list(self.members(x)) self.delete_set(x) self.union(*(v for v in members if v != x))
google/neuroglancer
python/neuroglancer/equivalence_map.py
EquivalenceMap.delete_set
python
def delete_set(self, x): if x not in self._parents: return members = list(self.members(x)) for v in members: del self._parents[v] del self._weights[v] del self._prev_next[v] del self._min_values[v]
Removes the equivalence class containing `x`.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/equivalence_map.py#L175-L184
[ "def members(self, x):\n \"\"\"Yields the members of the equivalence class containing `x`.\"\"\"\n if x not in self._parents:\n yield x\n return\n cur_x = x\n while True:\n yield cur_x\n cur_x = self._prev_next[cur_x][1]\n if cur_x == x:\n break\n" ]
class EquivalenceMap(object): """Union-find data structure""" supports_readonly = True def __init__(self, existing=None, _readonly=False): """Create a new empty union-find structure.""" if isinstance(existing, EquivalenceMap): self._weights = existing._weights.copy() self._parents = existing._parents.copy() self._prev_next = existing._prev_next.copy() self._min_values = existing._min_values.copy() else: self._weights = {} self._parents = {} self._prev_next = {} self._min_values = {} self._readonly = False if existing is not None: if isinstance(existing, dict): existing = six.viewitems(existing) for group in existing: self.union(*group) self._readonly = _readonly def _get_representative(self, obj): """Finds and returns the root of the set containing `obj`.""" if obj not in self._parents: self._parents[obj] = obj self._weights[obj] = 1 self._prev_next[obj] = [obj, obj] self._min_values[obj] = obj return obj path = [obj] root = self._parents[obj] while root != path[-1]: path.append(root) root = self._parents[root] # compress the path and return for ancestor in path: self._parents[ancestor] = root return root def __getitem__(self, obj): """Returns the minimum element in the set containing `obj`.""" if obj not in self._parents: return obj return self._min_values[self._get_representative(obj)] def __iter__(self): """Iterates over all elements known to this equivalence map.""" return iter(self._parents) def items(self): return six.viewitems(self._parents) def keys(self): return six.viewkeys(self._parents) def clear(self): self._weights.clear() self._parents.clear() self._prev_next.clear() self._min_values.clear() def union(self, *args): """Unions the equivalence classes containing the elements in `*args`.""" if self._readonly: raise AttributeError if len(args) == 0: return None if len(args) == 1: return self[args[0]] for a, b in zip(args[:-1], args[1:]): result = self._union_pair(a, b) return result def _union_pair(self, a, b): a = self._get_representative(a) b = self._get_representative(b) if a == b: return self._min_values[a] if self._weights[a] < self._weights[b]: a, b = (b, a) self._min_values[a] = min(self._min_values[a], self._min_values[b]) a_links_new = self._prev_next[a] a_links_old = tuple(a_links_new) b_links_new = self._prev_next[b] b_links_old = tuple(b_links_new) # We want to splice b's list at the end of a's list # Splice beginning of b's list into end of a's list b_links_new[0] = a_links_old[0] self._prev_next[a_links_old[0]][1] = b # Splice end of b's list into end of a's list # last element of a's list is set to last element of b's list a_links_new[0] = b_links_old[0] # fix next pointer for last element of b's list self._prev_next[b_links_old[0]][1] = a self._weights[a] += self._weights[b] self._parents[b] = a return self._min_values[a] def members(self, x): """Yields the members of the equivalence class containing `x`.""" if x not in self._parents: yield x return cur_x = x while True: yield cur_x cur_x = self._prev_next[cur_x][1] if cur_x == x: break def sets(self): """Returns the equivalence classes as a set of sets.""" sets = {} for x in self._parents: sets.setdefault(self[x], set()).add(x) return frozenset(frozenset(v) for v in six.viewvalues(sets)) def to_json(self): """Returns the equivalence classes a sorted list of sorted lists.""" sets = self.sets() return sorted(sorted(x) for x in sets) def __copy__(self): """Does not preserve _readonly attribute.""" return EquivalenceMap(self) def __deepcopy__(self, memo): """Does not preserve _readonly attribute.""" result = EquivalenceMap() result._parents = copy.deepcopy(self._parents, memo) result._weights = copy.deepcopy(self._weights, memo) result._prev_next = copy.deepcopy(self._prev_next, memo) result._min_values = copy.deepcopy(self._min_values, memo) return result def copy(self): """Returns a copy of the equivalence map.""" return EquivalenceMap(self) def isolate_element(self, x): """Isolates `x` from its equivalence class.""" members = list(self.members(x)) self.delete_set(x) self.union(*(v for v in members if v != x))
google/neuroglancer
python/neuroglancer/equivalence_map.py
EquivalenceMap.isolate_element
python
def isolate_element(self, x): members = list(self.members(x)) self.delete_set(x) self.union(*(v for v in members if v != x))
Isolates `x` from its equivalence class.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/equivalence_map.py#L186-L190
[ "def union(self, *args):\n \"\"\"Unions the equivalence classes containing the elements in `*args`.\"\"\"\n if self._readonly:\n raise AttributeError\n\n if len(args) == 0:\n return None\n if len(args) == 1:\n return self[args[0]]\n for a, b in zip(args[:-1], args[1:]):\n result = self._union_pair(a, b)\n return result\n", "def members(self, x):\n \"\"\"Yields the members of the equivalence class containing `x`.\"\"\"\n if x not in self._parents:\n yield x\n return\n cur_x = x\n while True:\n yield cur_x\n cur_x = self._prev_next[cur_x][1]\n if cur_x == x:\n break\n", "def delete_set(self, x):\n \"\"\"Removes the equivalence class containing `x`.\"\"\"\n if x not in self._parents:\n return\n members = list(self.members(x))\n for v in members:\n del self._parents[v]\n del self._weights[v]\n del self._prev_next[v]\n del self._min_values[v]\n" ]
class EquivalenceMap(object): """Union-find data structure""" supports_readonly = True def __init__(self, existing=None, _readonly=False): """Create a new empty union-find structure.""" if isinstance(existing, EquivalenceMap): self._weights = existing._weights.copy() self._parents = existing._parents.copy() self._prev_next = existing._prev_next.copy() self._min_values = existing._min_values.copy() else: self._weights = {} self._parents = {} self._prev_next = {} self._min_values = {} self._readonly = False if existing is not None: if isinstance(existing, dict): existing = six.viewitems(existing) for group in existing: self.union(*group) self._readonly = _readonly def _get_representative(self, obj): """Finds and returns the root of the set containing `obj`.""" if obj not in self._parents: self._parents[obj] = obj self._weights[obj] = 1 self._prev_next[obj] = [obj, obj] self._min_values[obj] = obj return obj path = [obj] root = self._parents[obj] while root != path[-1]: path.append(root) root = self._parents[root] # compress the path and return for ancestor in path: self._parents[ancestor] = root return root def __getitem__(self, obj): """Returns the minimum element in the set containing `obj`.""" if obj not in self._parents: return obj return self._min_values[self._get_representative(obj)] def __iter__(self): """Iterates over all elements known to this equivalence map.""" return iter(self._parents) def items(self): return six.viewitems(self._parents) def keys(self): return six.viewkeys(self._parents) def clear(self): self._weights.clear() self._parents.clear() self._prev_next.clear() self._min_values.clear() def union(self, *args): """Unions the equivalence classes containing the elements in `*args`.""" if self._readonly: raise AttributeError if len(args) == 0: return None if len(args) == 1: return self[args[0]] for a, b in zip(args[:-1], args[1:]): result = self._union_pair(a, b) return result def _union_pair(self, a, b): a = self._get_representative(a) b = self._get_representative(b) if a == b: return self._min_values[a] if self._weights[a] < self._weights[b]: a, b = (b, a) self._min_values[a] = min(self._min_values[a], self._min_values[b]) a_links_new = self._prev_next[a] a_links_old = tuple(a_links_new) b_links_new = self._prev_next[b] b_links_old = tuple(b_links_new) # We want to splice b's list at the end of a's list # Splice beginning of b's list into end of a's list b_links_new[0] = a_links_old[0] self._prev_next[a_links_old[0]][1] = b # Splice end of b's list into end of a's list # last element of a's list is set to last element of b's list a_links_new[0] = b_links_old[0] # fix next pointer for last element of b's list self._prev_next[b_links_old[0]][1] = a self._weights[a] += self._weights[b] self._parents[b] = a return self._min_values[a] def members(self, x): """Yields the members of the equivalence class containing `x`.""" if x not in self._parents: yield x return cur_x = x while True: yield cur_x cur_x = self._prev_next[cur_x][1] if cur_x == x: break def sets(self): """Returns the equivalence classes as a set of sets.""" sets = {} for x in self._parents: sets.setdefault(self[x], set()).add(x) return frozenset(frozenset(v) for v in six.viewvalues(sets)) def to_json(self): """Returns the equivalence classes a sorted list of sorted lists.""" sets = self.sets() return sorted(sorted(x) for x in sets) def __copy__(self): """Does not preserve _readonly attribute.""" return EquivalenceMap(self) def __deepcopy__(self, memo): """Does not preserve _readonly attribute.""" result = EquivalenceMap() result._parents = copy.deepcopy(self._parents, memo) result._weights = copy.deepcopy(self._weights, memo) result._prev_next = copy.deepcopy(self._prev_next, memo) result._min_values = copy.deepcopy(self._min_values, memo) return result def copy(self): """Returns a copy of the equivalence map.""" return EquivalenceMap(self) def delete_set(self, x): """Removes the equivalence class containing `x`.""" if x not in self._parents: return members = list(self.members(x)) for v in members: del self._parents[v] del self._weights[v] del self._prev_next[v] del self._min_values[v]
google/neuroglancer
python/neuroglancer/viewer_state.py
quaternion_slerp
python
def quaternion_slerp(a, b, t): if a is None: a = unit_quaternion() if b is None: b = unit_quaternion() # calc cosine cosom = np.dot(a, b) # adjust signs (if necessary) if cosom < 0.0: cosom = -cosom b = -b # calculate coefficients if (1.0 - cosom) > 0.000001: # standard case (slerp) omega = math.acos(cosom) sinom = math.sin(omega) scale0 = math.sin((1.0 - t) * omega) / sinom scale1 = math.sin(t * omega) / sinom else: # "from" and "to" quaternions are very close # ... so we can do a linear interpolation scale0 = 1.0 - t scale1 = t return scale0 * a + scale1 * b
Spherical linear interpolation for unit quaternions. This is based on the implementation in the gl-matrix package: https://github.com/toji/gl-matrix
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/viewer_state.py#L65-L94
[ "def unit_quaternion():\n return np.array([0, 0, 0, 1], np.float32)\n" ]
# @license # Copyright 2017 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Wrappers for representing the Neuroglancer viewer state.""" from __future__ import absolute_import import collections import copy import math import numpy as np import six from . import local_volume from .equivalence_map import EquivalenceMap from .json_utils import encode_json_for_repr from .json_wrappers import (JsonObjectWrapper, array_wrapper, optional, text_type, typed_list, typed_set, typed_string_map, wrapped_property) __all__ = [] def export(obj): __all__.append(obj.__name__) return obj def interpolate_linear(a, b, t): return a * (1 - t) + b * t @export class SpatialPosition(JsonObjectWrapper): __slots__ = () voxel_size = voxelSize = wrapped_property('voxelSize', optional(array_wrapper(np.float32, 3))) spatial_coordinates = spatialCoordinates = wrapped_property( 'spatialCoordinates', optional(array_wrapper(np.float32, 3))) voxel_coordinates = voxelCoordinates = wrapped_property('voxelCoordinates', optional(array_wrapper(np.float32, 3))) @staticmethod def interpolate(a, b, t): if a.voxel_size is None or a.voxel_coordinates is None or b.voxel_coordinates is None: return a c = copy.deepcopy(a) c.voxel_coordinates = interpolate_linear(a.voxel_coordinates, b.voxel_coordinates, t) return c def unit_quaternion(): return np.array([0, 0, 0, 1], np.float32) @export class Pose(JsonObjectWrapper): __slots__ = () position = wrapped_property('position', SpatialPosition) orientation = wrapped_property('orientation', optional(array_wrapper(np.float32, 4))) @staticmethod def interpolate(a, b, t): c = copy.deepcopy(a) c.position = SpatialPosition.interpolate(a.position, b.position, t) c.orientation = quaternion_slerp(a.orientation, b.orientation, t) return c def interpolate_zoom(a, b, t): if a is None or b is None: return a scale_change = math.log(b / a) return a * math.exp(scale_change * t) @export class NavigationState(JsonObjectWrapper): __slots__ = () pose = wrapped_property('pose', Pose) zoom_factor = zoomFactor = wrapped_property('zoomFactor', optional(float)) @property def position(self): return self.pose.position @position.setter def position(self, v): self.pose.position = v @property def voxel_size(self): return self.pose.position.voxel_size @voxel_size.setter def voxel_size(self, v): self.pose.position.voxel_size = v @staticmethod def interpolate(a, b, t): c = copy.deepcopy(a) c.pose = Pose.interpolate(a.pose, b.pose, t) c.zoom_factor = interpolate_zoom(a.zoom_factor, b.zoom_factor, t) return c @export class Layer(JsonObjectWrapper): __slots__ = () type = wrapped_property('type', optional(text_type)) @export class PointAnnotationLayer(Layer): __slots__ = () def __init__(self, *args, **kwargs): super(PointAnnotationLayer, self).__init__(*args, type='pointAnnotation', **kwargs) points = wrapped_property('points', typed_list(array_wrapper(np.float32, 3))) def volume_source(x): if isinstance(x, local_volume.LocalVolume): return x if not isinstance(x, six.string_types): raise TypeError return text_type(x) class _AnnotationLayerOptions(object): __slots__ = () annotation_color = annotationColor = wrapped_property('annotationColor', optional(text_type)) annotation_fill_opacity = annotationFillOpacity = wrapped_property('annotationFillOpacity', optional(float, 0)) @export class ImageLayer(Layer, _AnnotationLayerOptions): __slots__ = () def __init__(self, *args, **kwargs): super(ImageLayer, self).__init__(*args, type='image', **kwargs) source = wrapped_property('source', volume_source) shader = wrapped_property('shader', text_type) opacity = wrapped_property('opacity', optional(float, 0.5)) blend = wrapped_property('blend', optional(str)) cross_section_render_scale = crossSectionRenderScale = wrapped_property( 'crossSectionRenderScale', optional(float, 1)) @staticmethod def interpolate(a, b, t): c = copy.deepcopy(a) c.opacity = interpolate_linear(a.opacity, b.opacity, t) return c def uint64_equivalence_map(obj, _readonly=False): if isinstance(obj, EquivalenceMap): return obj if obj is not None: obj = [[int(v) for v in group] for group in obj] return EquivalenceMap(obj, _readonly=_readonly) @export class SegmentationLayer(Layer, _AnnotationLayerOptions): __slots__ = () def __init__(self, *args, **kwargs): super(SegmentationLayer, self).__init__(*args, type='segmentation', **kwargs) source = wrapped_property('source', optional(volume_source)) mesh = wrapped_property('mesh', optional(text_type)) skeletons = wrapped_property('skeletons', optional(text_type)) segments = wrapped_property('segments', typed_set(np.uint64)) equivalences = wrapped_property('equivalences', uint64_equivalence_map) hide_segment_zero = hideSegmentZero = wrapped_property('hideSegmentZero', optional(bool, True)) selected_alpha = selectedAlpha = wrapped_property('selectedAlpha', optional(float, 0.5)) not_selected_alpha = notSelectedAlpha = wrapped_property('notSelectedAlpha', optional(float, 0)) object_alpha = objectAlpha = wrapped_property('objectAlpha', optional(float, 1.0)) skeleton_shader = skeletonShader = wrapped_property('skeletonShader', text_type) color_seed = colorSeed = wrapped_property('colorSeed', optional(int, 0)) cross_section_render_scale = crossSectionRenderScale = wrapped_property( 'crossSectionRenderScale', optional(float, 1)) mesh_render_scale = meshRenderScale = wrapped_property('meshRenderScale', optional(float, 10)) @staticmethod def interpolate(a, b, t): c = copy.deepcopy(a) for k in ['selected_alpha', 'not_selected_alpha', 'object_alpha']: setattr(c, k, interpolate_linear(getattr(a, k), getattr(b, k), t)) return c @export class SingleMeshLayer(Layer): __slots__ = () def __init__(self, *args, **kwargs): super(SingleMeshLayer, self).__init__(*args, type='mesh', **kwargs) source = wrapped_property('source', text_type) vertex_attribute_sources = vertexAttributeSources = wrapped_property( 'vertexAttributeSources', optional(typed_list(text_type))) shader = wrapped_property('shader', text_type) vertex_attribute_names = vertexAttributeNames = wrapped_property('vertexAttributeNames', optional( typed_list( optional(text_type)))) class AnnotationBase(JsonObjectWrapper): __slots__ = () id = wrapped_property('id', optional(text_type)) # pylint: disable=invalid-name type = wrapped_property('type', text_type) description = wrapped_property('description', optional(text_type)) segments = wrapped_property('segments', optional(typed_list(np.uint64))) @export class PointAnnotation(AnnotationBase): __slots__ = () def __init__(self, *args, **kwargs): super(PointAnnotation, self).__init__(*args, type='point', **kwargs) point = wrapped_property('point', array_wrapper(np.float32, 3)) @export class LineAnnotation(AnnotationBase): __slots__ = () def __init__(self, *args, **kwargs): super(LineAnnotation, self).__init__(*args, type='line', **kwargs) point_a = pointA = wrapped_property('pointA', array_wrapper(np.float32, 3)) point_b = pointB = wrapped_property('pointB', array_wrapper(np.float32, 3)) @export class AxisAlignedBoundingBoxAnnotation(AnnotationBase): __slots__ = () def __init__(self, *args, **kwargs): super(AxisAlignedBoundingBoxAnnotation, self).__init__( *args, type='axis_aligned_bounding_box', **kwargs) point_a = pointA = wrapped_property('pointA', array_wrapper(np.float32, 3)) point_b = pointB = wrapped_property('pointB', array_wrapper(np.float32, 3)) @export class EllipsoidAnnotation(AnnotationBase): __slots__ = () def __init__(self, *args, **kwargs): super(EllipsoidAnnotation, self).__init__(*args, type='ellipsoid', **kwargs) center = wrapped_property('center', array_wrapper(np.float32, 3)) radii = wrapped_property('radii', array_wrapper(np.float32, 3)) annotation_types = { 'point': PointAnnotation, 'line': LineAnnotation, 'axis_aligned_bounding_box': AxisAlignedBoundingBoxAnnotation, 'ellipsoid': EllipsoidAnnotation, } def annotation(obj, _readonly=False): if isinstance(obj, AnnotationBase): obj = obj.to_json() elif not isinstance(obj, dict): raise TypeError t = obj.get('type') return annotation_types[t](obj, _readonly=_readonly) annotation.supports_readonly = True @export class AnnotationLayer(Layer, _AnnotationLayerOptions): __slots__ = () def __init__(self, *args, **kwargs): super(AnnotationLayer, self).__init__(*args, type='annotation', **kwargs) source = wrapped_property('source', optional(volume_source)) voxel_size = voxelSize = wrapped_property('voxelSize', optional(array_wrapper(np.float32, 3))) annotations = wrapped_property('annotations', typed_list(annotation)) linked_segmentation_layer = linkedSegmentationLayer = wrapped_property('linkedSegmentationLayer', optional(text_type)) filter_by_segmentation = filterBySegmentation = wrapped_property('filterBySegmentation', optional(bool, False)) @staticmethod def interpolate(a, b, t): del b del t return a layer_types = { 'image': ImageLayer, 'segmentation': SegmentationLayer, 'pointAnnotation': PointAnnotationLayer, 'annotation': AnnotationLayer, 'mesh': SingleMeshLayer, } def make_layer(json_data, _readonly=False): if isinstance(json_data, Layer): return json_data if isinstance(json_data, local_volume.LocalVolume): json_data = dict(type=json_data.volume_type, source=json_data) if not isinstance(json_data, dict): raise TypeError type_name = json_data.get('type') layer_type = layer_types.get(type_name) if layer_type is not None: return layer_type(json_data, _readonly=_readonly) else: raise ValueError @export class ManagedLayer(JsonObjectWrapper): __slots__ = ('name', 'layer') def __init__(self, name, layer=None, _readonly=False, **kwargs): if isinstance(name, ManagedLayer): if layer is not None or kwargs: raise ValueError layer = name.to_json() name = name.name object.__setattr__(self, 'name', name) if isinstance(layer, Layer): json_data = collections.OrderedDict() elif isinstance(layer, local_volume.LocalVolume): json_data = collections.OrderedDict() layer = make_layer(layer, _readonly=_readonly) else: if layer is None: json_data = collections.OrderedDict() else: json_data = layer layer = make_layer(json_data, _readonly=_readonly) object.__setattr__(self, 'layer', layer) super(ManagedLayer, self).__init__(json_data, _readonly=_readonly, **kwargs) visible = wrapped_property('visible', optional(bool)) def __getattr__(self, key): return getattr(self.layer, key) def __setattr__(self, key, value): if self._readonly: raise AttributeError if key in ['name', 'visible', 'layer']: object.__setattr__(self, key, value) else: return setattr(self.layer, key, value) def __repr__(self): return u'ManagedLayer(%s,%s)' % (encode_json_for_repr(self.name), encode_json_for_repr(self.to_json())) def to_json(self): r = self.layer.to_json() r['name'] = self.name visible = self.visible if visible is not None: r['visible'] = visible return r def __deepcopy__(self, memo): return ManagedLayer(self.name, copy.deepcopy(self.to_json(), memo)) @export class Layers(object): __slots__ = ('_layers', '_readonly') supports_readonly = True def __init__(self, json_data, _readonly=False): if json_data is None: json_data = collections.OrderedDict() self._layers = [] self._readonly = _readonly if isinstance(json_data, collections.Mapping): for k, v in six.iteritems(json_data): self._layers.append(ManagedLayer(k, v, _readonly=_readonly)) else: # layers property can also be an array in JSON now. each layer has a name property for layer in json_data: if isinstance(layer, ManagedLayer): self._layers.append(ManagedLayer(layer.name, layer, _readonly=_readonly)) elif isinstance(layer, dict): self._layers.append(ManagedLayer(text_type(layer['name']), layer, _readonly=_readonly)) else: raise TypeError def index(self, k): for i, u in enumerate(self._layers): if u.name == k: return i return -1 def __getitem__(self, k): """Indexes into the list of layers by index, slice, or layer name.""" if isinstance(k, six.string_types): return self._layers[self.index(k)] return self._layers[k] def __setitem__(self, k, v): if self._readonly: raise AttributeError if isinstance(k, six.string_types): i = self.index(k) if isinstance(v, Layer): v = ManagedLayer(k, v) elif not isinstance(v, ManagedLayer): raise TypeError if i == -1: self._layers.append(v) else: self._layers[i] = v else: if isinstance(k, slice): values = [] for x in v: if not isinstance(v, ManagedLayer): raise TypeError values.append(x) self._layers[k] = values else: if not isinstance(v, ManagedLayer): raise TypeError self._layers[k] = v def clear(self): """Clears the list of layers.""" del self[:] def __delitem__(self, k): """Deletes a layer by index, slice, or name.""" if self._readonly: raise AttributeError if isinstance(k, six.string_types): k = self.index(k) del self._layers[k] def append(self, *args, **kwargs): """Appends a ManagedLayer to the list of layers.""" if self._readonly: raise AttributeError if len(args) == 1 and not kwargs and isinstance(args[0], ManagedLayer): layer = args[0] else: layer = ManagedLayer(*args, **kwargs) self._layers.append(layer) def extend(self, elements): for element in elements: self.append(element) def __len__(self): """Returns the number of layers in the list.""" return len(self._layers) def __iter__(self): return iter(self._layers) def to_json(self): r = [] for x in self._layers: r.append(x.to_json()) return r def __repr__(self): return repr(self._layers) @staticmethod def interpolate(a, b, t): c = copy.deepcopy(a) for layer in c: index = b.index(layer.name) if index == -1: continue other_layer = b[index] if type(other_layer.layer) is not type(layer.layer): # pylint: disable=unidiomatic-typecheck continue layer.layer = type(layer.layer).interpolate(layer.layer, other_layer.layer, t) return c def navigation_link_type(x): x = six.text_type(x) x = x.lower() if x not in [u'linked', u'unlinked', u'relative']: raise ValueError('Invalid navigation link type: %r' % x) return x def make_linked_navigation_type(value_type, interpolate_function=None): if interpolate_function is None: interpolate_function = value_type.interpolate class LinkedType(JsonObjectWrapper): __slots__ = () link = wrapped_property('link', optional(navigation_link_type, u'linked')) value = wrapped_property('value', optional(value_type)) @staticmethod def interpolate(a, b, t): c = copy.deepcopy(a) c.link = a.link if a.link == b.link and a.link != 'linked': c.value = interpolate_function(a, b, t) return c return c return LinkedType @export class LinkedSpatialPosition(make_linked_navigation_type(SpatialPosition)): __slots__ = () @export class LinkedZoomFactor(make_linked_navigation_type(float, interpolate_zoom)): __slots__ = () @export class LinkedOrientationState(make_linked_navigation_type(array_wrapper(np.float32, 4), quaternion_slerp)): __slots__ = () @export class CrossSection(JsonObjectWrapper): __slots__ = () supports_validation = True width = wrapped_property('width', optional(int, 1000)) height = wrapped_property('height', optional(int, 1000)) position = wrapped_property('position', LinkedSpatialPosition) orientation = wrapped_property('orientation', LinkedOrientationState) zoom = wrapped_property('zoom', LinkedZoomFactor) @staticmethod def interpolate(a, b, t): c = copy.deepcopy(a) c.width = interpolate_linear(a.width, b.width, t) c.height = interpolate_linear(a.height, b.height, t) c.position = LinkedSpatialPosition.interpolate(a.position, b.position, t) c.orientation = LinkedOrientationState.interpolate(a.orientation, b.orientation, t) c.zoom = LinkedZoomFactor.interpolate(a.zoom, b.zoom, t) return c @export class CrossSectionMap(typed_string_map(CrossSection)): @staticmethod def interpolate(a, b, t): c = copy.deepcopy(a) for k in a: if k in b: c[k] = CrossSection.interpolate(a[k], b[k], t) return c @export class DataPanelLayout(JsonObjectWrapper): __slots__ = () type = wrapped_property('type', text_type) cross_sections = crossSections = wrapped_property('crossSections', CrossSectionMap) orthographic_projection = orthographicProjection = wrapped_property( 'orthographicProjection', optional(bool, False)) def __init__(self, json_data=None, _readonly=False, **kwargs): if isinstance(json_data, six.string_types): json_data = {'type': six.text_type(json_data)} super(DataPanelLayout, self).__init__(json_data, _readonly=_readonly, **kwargs) def to_json(self): if len(self.cross_sections) == 0 and not self.orthographic_projection: return self.type return super(DataPanelLayout, self).to_json() @staticmethod def interpolate(a, b, t): if a.type != b.type or len(a.cross_sections) == 0: return a c = copy.deepcopy(a) c.cross_sections = CrossSectionMap.interpolate(a.cross_sections, b.cross_sections, t) return c def data_panel_layout_wrapper(default_value='xy'): def wrapper(x, _readonly=False): if x is None: x = default_value if isinstance(x, six.string_types): x = {'type': six.text_type(x)} return DataPanelLayout(x, _readonly=_readonly) wrapper.supports_readonly = True return wrapper data_panel_layout_types = frozenset(['xy', 'yz', 'yz', 'xy-3d', 'yz-3d', 'yz-3d', '4panel', '3d']) def layout_specification(x, _readonly=False): if x is None: x = '4panel' if isinstance(x, six.string_types): x = {'type': six.text_type(x)} if isinstance(x, (StackLayout, LayerGroupViewer, DataPanelLayout)): return type(x)(x.to_json(), _readonly=_readonly) if not isinstance(x, dict): raise ValueError layout_type = layout_types.get(x.get('type')) if layout_type is None: raise ValueError return layout_type(x, _readonly=_readonly) layout_specification.supports_readonly = True @export class StackLayout(JsonObjectWrapper): __slots__ = () type = wrapped_property('type', text_type) children = wrapped_property('children', typed_list(layout_specification)) def __getitem__(self, key): return self.children[key] def __len__(self): return len(self.children) def __setitem__(self, key, value): self.children[key] = value def __delitem__(self, key): del self.children[key] def __iter__(self): return iter(self.children) @staticmethod def interpolate(a, b, t): if a.type != b.type or len(a.children) != len(b.children): return a c = copy.deepcopy(a) c.children = [ interpolate_layout(a_child, b_child, t) for a_child, b_child in zip(a.children, b.children) ] return c @export def row_layout(children): return StackLayout(type='row', children=children) @export def column_layout(children): return StackLayout(type='column', children=children) def interpolate_layout(a, b, t): if type(a) is not type(b): return a return type(a).interpolate(a, b, t) @export class LayerGroupViewer(JsonObjectWrapper): __slots__ = () type = wrapped_property('type', text_type) layers = wrapped_property('layers', typed_list(text_type)) layout = wrapped_property('layout', data_panel_layout_wrapper('xy')) position = wrapped_property('position', LinkedSpatialPosition) cross_section_orientation = crossSectionOrientation = wrapped_property( 'crossSectionOrientation', LinkedOrientationState) cross_section_zoom = crossSectionZoom = wrapped_property('crossSectionZoom', LinkedZoomFactor) perspective_orientation = perspectiveOrientation = wrapped_property( 'perspectiveOrientation', LinkedOrientationState) perspective_zoom = perspectiveZoom = wrapped_property('perspectiveZoom', LinkedZoomFactor) def __init__(self, *args, **kwargs): super(LayerGroupViewer, self).__init__(*args, **kwargs) self.type = 'viewer' def __repr__(self): j = self.to_json() j.pop('type', None) return u'%s(%s)' % (type(self).__name__, encode_json_for_repr(j)) @staticmethod def interpolate(a, b, t): c = copy.deepcopy(a) for k in ('layout', 'position', 'cross_section_orientation', 'cross_section_zoom', 'perspective_orientation', 'perspective_zoom'): a_attr = getattr(a, k) b_attr = getattr(b, k) setattr(c, k, type(a_attr).interpolate(a_attr, b_attr, t)) return c layout_types = { 'row': StackLayout, 'column': StackLayout, 'viewer': LayerGroupViewer, } def add_data_panel_layout_types(): for k in data_panel_layout_types: layout_types[k] = DataPanelLayout add_data_panel_layout_types() @export class SelectedLayerState(JsonObjectWrapper): visible = wrapped_property('visible', optional(bool, False)) size = wrapped_property('size', optional(int)) layer = wrapped_property('layer', optional(text_type)) @export class StatisticsDisplayState(JsonObjectWrapper): visible = wrapped_property('visible', optional(bool, False)) size = wrapped_property('size', optional(int)) @export class ViewerState(JsonObjectWrapper): __slots__ = () navigation = wrapped_property('navigation', NavigationState) perspective_zoom = perspectiveZoom = wrapped_property('perspectiveZoom', optional(float)) perspective_orientation = perspectiveOrientation = wrapped_property( 'perspectiveOrientation', optional(array_wrapper(np.float32, 4))) show_slices = showSlices = wrapped_property('showSlices', optional(bool, True)) show_axis_lines = showAxisLines = wrapped_property('showAxisLines', optional(bool, True)) show_scale_bar = showScaleBar = wrapped_property('showScaleBar', optional(bool, True)) show_default_annotations = showDefaultAnnotations = wrapped_property('showDefaultAnnotations', optional(bool, True)) gpu_memory_limit = gpuMemoryLimit = wrapped_property('gpuMemoryLimit', optional(int)) system_memory_limit = systemMemoryLimit = wrapped_property('systemMemoryLimit', optional(int)) concurrent_downloads = concurrentDownloads = wrapped_property('concurrentDownloads', optional(int)) layers = wrapped_property('layers', Layers) layout = wrapped_property('layout', layout_specification) cross_section_background_color = crossSectionBackgroundColor = wrapped_property( 'crossSectionBackgroundColor', optional(text_type)) perspective_view_background_color = perspectiveViewBackgroundColor = wrapped_property( 'perspectiveViewBackgroundColor', optional(text_type)) selected_layer = selectedLayer = wrapped_property('selectedLayer', SelectedLayerState) statistics = wrapped_property('statistics', StatisticsDisplayState) @property def position(self): return self.navigation.position @position.setter def position(self, v): self.navigation.position = v @property def voxel_coordinates(self): return self.position.voxel_coordinates @voxel_coordinates.setter def voxel_coordinates(self, v): self.position.voxel_coordinates = v @property def voxel_size(self): return self.navigation.voxel_size @voxel_size.setter def voxel_size(self, v): self.navigation.voxel_size = v @staticmethod def interpolate(a, b, t): c = copy.deepcopy(a) c.navigation = NavigationState.interpolate(a.navigation, b.navigation, t) c.perspective_zoom = interpolate_zoom(a.perspective_zoom, b.perspective_zoom, t) c.perspective_orientation = quaternion_slerp(a.perspective_orientation, b.perspective_orientation, t) c.layers = Layers.interpolate(a.layers, b.layers, t) c.layout = interpolate_layout(a.layout, b.layout, t) return c
google/neuroglancer
python/neuroglancer/tool/agglomeration_split_tool.py
GreedyMulticut.remove_edge_from_heap
python
def remove_edge_from_heap(self, segment_ids): self._initialize_heap() key = normalize_edge(segment_ids) if key in self.edge_map: self.edge_map[key][0] = None self.num_valid_edges -= 1
Remove an edge from the heap.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/tool/agglomeration_split_tool.py#L73-L79
[ "def normalize_edge((id_a, id_b)):\n if id_a > id_b:\n id_a, id_b = id_b, id_a\n return id_a, id_b\n", "def _initialize_heap(self):\n if self._initialized:\n return\n for key in self.edge_map:\n entry = self.edge_map[key]\n self._add_to_heap(entry)\n self._initialized = True\n" ]
class GreedyMulticut(object): def __init__(self, combine_edges, edge_priority): # Contains (score, edge_map_value) tuple values in heap order. The # edge_map_value is the actual corresponding value in edge_map, not a copy. self.edge_heap = [] # Maps segment_id -> set of segment_id neighbors. self.regions = dict() # Maps (id_a, id_b) -> edge_map_value=[score, key, edge_object] self.edge_map = dict() self.combine_edges = combine_edges self.edge_priority = edge_priority self.num_valid_edges = 0 self._initialized = False def add_edge(self, (id_a, id_b), edge): id_a, id_b = normalize_edge((id_a, id_b)) self.regions.setdefault(id_a, set()).add(id_b) self.regions.setdefault(id_b, set()).add(id_a) key = (id_a, id_b) entry = self.edge_map.get(key, None) if entry is not None: edge_data = entry[2] = self.combine_edges(entry[0], edge) entry[0] = self.edge_priority(edge_data) else: entry = self.edge_map[key] = [self.edge_priority(edge), key, edge] self.num_valid_edges += 1 if self._initialized: self._add_to_heap(entry) def _initialize_heap(self): if self._initialized: return for key in self.edge_map: entry = self.edge_map[key] self._add_to_heap(entry) self._initialized = True def _add_to_heap(self, entry): heapq.heappush(self.edge_heap, (entry[0], entry)) def check_consistency(self): self._initialize_heap() expected_regions = dict() for key, entry in six.viewitems(self.edge_map): assert entry[1] == key expected_regions.setdefault(key[0], set()).add(key[1]) expected_regions.setdefault(key[1], set()).add(key[0]) assert expected_regions == self.regions num_valid_edges = 0 for e in self.edge_heap: if self._is_valid_heap_entry(e): num_valid_edges += 1 assert num_valid_edges == self.num_valid_edges def merge(self, (id_a, id_b)): self._initialize_heap() id_a, id_b = normalize_edge((id_a, id_b)) if (id_a, id_b) not in self.edge_map: raise KeyError for neighbor in self.regions[id_b]: if neighbor == id_a: continue expired_ids = normalize_edge((neighbor, id_b)) new_ids = normalize_edge((neighbor, id_a)) new_edge = self.edge_map.get(new_ids) expired_edge = self.edge_map[expired_ids] if new_edge is not None: edge_data = new_edge[2] = self.combine_edges(new_edge[2], expired_edge[2]) if new_edge[0] is not None: self.num_valid_edges -= 1 if expired_edge[0] is not None: self.num_valid_edges -= 1 self.num_valid_edges += 1 new_edge[0] = self.edge_priority(edge_data) self._add_to_heap(new_edge) else: self.regions[neighbor].add(id_a) self.regions[id_a].add(neighbor) self.edge_map[new_ids] = expired_edge expired_edge[1] = new_ids # No need to add to heap, since score hasn't changed. del self.edge_map[expired_ids] self.regions[neighbor].remove(id_b) del self.regions[id_b] self.regions[id_a].remove(id_b) del self.edge_map[(id_a, id_b)] self.num_valid_edges -= 1 def _is_valid_heap_entry(self, heap_entry): score, entry = heap_entry expected_entry = self.edge_map.get(entry[1]) if entry is not expected_entry or entry[0] is not score: return None else: return entry def get_next_edge(self): self._initialize_heap() while True: if self.num_valid_edges == 0: return None heap_entry = self.edge_heap[0] entry = self._is_valid_heap_entry(heap_entry) if entry is None: heapq.heappop(self.edge_heap) else: return entry
google/neuroglancer
python/neuroglancer/trackable_state.py
TrackableState.txn
python
def txn(self, overwrite=False, lock=True): if lock: self._lock.acquire() try: new_state, existing_generation = self.state_and_generation new_state = copy.deepcopy(new_state) yield new_state if overwrite: existing_generation = None self.set_state(new_state, existing_generation=existing_generation) finally: if lock: self._lock.release()
Context manager for a state modification transaction.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/trackable_state.py#L108-L121
[ "def set_state(self, new_state, generation=None, existing_generation=None):\n with self._lock:\n if existing_generation is not None and self._generation != existing_generation:\n raise ConcurrentModificationError\n new_state = self._transform_state(new_state)\n if new_state != self._raw_state or (generation is not None and generation != self._generation):\n if generation is None:\n generation = make_random_token()\n self._raw_state = new_state\n self._wrapped_state = None\n self._generation = generation\n self._dispatch_changed_callbacks()\n return self._generation\n" ]
class TrackableState(ChangeNotifier): def __init__(self, wrapper_type, transform_state=None): super(TrackableState, self).__init__() self._raw_state = {} self._lock = threading.RLock() self._generation = make_random_token() self._wrapped_state = None self._wrapper_type = wrapper_type if transform_state is None: def transform_state_function(new_state): if isinstance(new_state, wrapper_type): return new_state.to_json() return new_state transform_state = transform_state_function self._transform_state = transform_state def set_state(self, new_state, generation=None, existing_generation=None): with self._lock: if existing_generation is not None and self._generation != existing_generation: raise ConcurrentModificationError new_state = self._transform_state(new_state) if new_state != self._raw_state or (generation is not None and generation != self._generation): if generation is None: generation = make_random_token() self._raw_state = new_state self._wrapped_state = None self._generation = generation self._dispatch_changed_callbacks() return self._generation @property def state_and_generation(self): with self._lock: return (self.state, self.state_generation) @property def raw_state_and_generation(self): with self._lock: return (self.raw_state, self.state_generation) @property def state_generation(self): return self._generation @property def raw_state(self): return self._raw_state @property def state(self): with self._lock: wrapped_state = self._wrapped_state if wrapped_state is None: wrapped_state = self._wrapped_state = self._wrapper_type(self._raw_state, _readonly=True) return wrapped_state @contextlib.contextmanager def retry_txn(self, func, retries=10): for retry in range(retries): try: with self.txn(lock=False) as s: return func(s) except ConcurrentModificationError: if retry + 1 < retries: pass raise def __repr__(self): return u'%s(%r)' % (type(self).__name__, self.state)
google/neuroglancer
python/neuroglancer/local_volume.py
LocalVolume.invalidate
python
def invalidate(self): with self._mesh_generator_lock: self._mesh_generator_pending = None self._mesh_generator = None self._dispatch_changed_callbacks()
Mark the data invalidated. Clients will refetch the volume.
train
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/local_volume.py#L289-L294
[ "def _dispatch_changed_callbacks(self):\n with self.__lock:\n self.change_count += 1\n for callback in self.__changed_callbacks:\n callback()\n" ]
class LocalVolume(trackable_state.ChangeNotifier): def __init__(self, data, offset=None, voxel_offset=None, skeletons=None, voxel_size=(1, 1, 1), encoding='npz', max_voxels_per_chunk_log2=None, volume_type=None, mesh_options=None, downsampling='3d', max_downsampling=downsample_scales.DEFAULT_MAX_DOWNSAMPLING, max_downsampled_size=downsample_scales.DEFAULT_MAX_DOWNSAMPLED_SIZE, max_downsampling_scales=downsample_scales.DEFAULT_MAX_DOWNSAMPLING_SCALES): """Initializes a LocalVolume. @param data: 3-d [z, y, x] array or 4-d [channel, z, y, x] array. @param downsampling: '3d' to use isotropic downsampling, '2d' to downsample separately in XY, XZ, and YZ, None to use no downsampling. @param max_downsampling: Maximum amount by which on-the-fly downsampling may reduce the volume of a chunk. For example, 4x4x4 downsampling reduces the volume by 64. @param volume_type: either 'image' or 'segmentation'. If not specified, guessed from the data type. @param voxel_size: Sequence [x, y, z] of floats. Specifies the voxel size. @param mesh_options: A dict with the following keys specifying options for mesh simplification for 'segmentation' volumes: - max_quadrics_error: float. Edge collapses with a larger associated quadrics error than this amount are prohibited. Set this to a negative number to disable mesh simplification, and just use the original mesh produced by the marching cubes algorithm. Defaults to 1e6. The effect of this value depends on the voxel_size. - max_normal_angle_deviation: float. Edge collapses that change a triangle normal by more than this angle are prohibited. The angle is specified in degrees. Defaults to 90. - lock_boundary_vertices: bool. Retain all vertices along mesh surface boundaries, which can only occur at the boundary of the volume. Defaults to true. """ super(LocalVolume, self).__init__() if hasattr(data, 'attrs'): if 'resolution' in data.attrs: if voxel_size is None: voxel_size = tuple(data.attrs['resolution'])[::-1] if 'offset' in data.attrs: if offset is None and voxel_offset is None: offset = tuple(data.attrs['offset'])[::-1] voxel_size = np.array(voxel_size) self.token = make_random_token() self.max_voxels_per_chunk_log2 = max_voxels_per_chunk_log2 self.data = data self.skeletons = skeletons if voxel_offset is not None: if offset is not None: raise ValueError('Must specify at most one of \'offset\' and \'voxel_offset\'.') voxel_offset = np.array(voxel_offset) offset = tuple(voxel_offset * voxel_size) if offset is None: offset = (0, 0, 0) self.offset = tuple(offset) self.data_type = np.dtype(data.dtype).name if self.data_type == 'float64': self.data_type = 'float32' self.encoding = encoding if len(data.shape) == 3: self.num_channels = 1 original_shape = data.shape[::-1] else: if len(data.shape) != 4: raise ValueError('data array must be 3- or 4-dimensional.') self.num_channels = data.shape[0] original_shape = data.shape[1:][::-1] original_shape = np.array(original_shape) if volume_type is None: if self.num_channels == 1 and (self.data_type == 'uint16' or self.data_type == 'uint32' or self.data_type == 'uint64'): volume_type = 'segmentation' else: volume_type = 'image' self.volume_type = volume_type self._mesh_generator = None self._mesh_generator_pending = None self._mesh_generator_lock = threading.Condition() self._mesh_options = mesh_options.copy() if mesh_options is not None else dict() voxel_size = np.array(voxel_size) self.voxel_size = voxel_size self.two_dimensional_scales = None self.three_dimensional_scales = None if downsampling is None: downsampling_scales = self.three_dimensional_scales = [(1, 1, 1)] elif downsampling == '3d': self.three_dimensional_scales = downsample_scales.compute_near_isotropic_downsampling_scales( size=original_shape, voxel_size=voxel_size, dimensions_to_downsample=[0, 1, 2], max_downsampling=max_downsampling, max_downsampled_size=max_downsampled_size, max_scales=max_downsampling_scales) downsampling_scales = self.three_dimensional_scales elif downsampling == '2d': self.two_dimensional_scales = downsample_scales.compute_two_dimensional_near_isotropic_downsampling_scales( size=original_shape, voxel_size=voxel_size, max_downsampling=max_downsampling, max_downsampled_size=max_downsampled_size, max_scales=max_downsampling_scales) downsampling_scales = [s for level in self.two_dimensional_scales for s in level] downsampling_scale_info = self.downsampling_scale_info = {} for scale in downsampling_scales: info = DownsamplingScaleInfo(key=get_scale_key(scale), voxel_size=tuple(voxel_size * scale), downsample_factor=scale, shape=tuple(np.cast[int](np.ceil(original_shape / scale)))) downsampling_scale_info[info.key] = info def info(self): info = dict(volumeType=self.volume_type, dataType=self.data_type, encoding=self.encoding, numChannels=self.num_channels, generation=self.change_count, ) if self.max_voxels_per_chunk_log2 is not None: info['maxVoxelsPerChunkLog2'] = self.max_voxels_per_chunk_log2 def get_scale_info(s): info = self.downsampling_scale_info[get_scale_key(s)] return dict(key=info.key, offset=self.offset, sizeInVoxels=info.shape, voxelSize=info.voxel_size) if self.two_dimensional_scales is not None: info['twoDimensionalScales'] = [[get_scale_info(s) for s in level] for level in self.two_dimensional_scales] if self.three_dimensional_scales is not None: info['threeDimensionalScales'] = [get_scale_info(s) for s in self.three_dimensional_scales] if self.skeletons is not None: info['skeletonVertexAttributes'] = self.skeletons.get_vertex_attributes_spec() return info def get_encoded_subvolume(self, data_format, start, end, scale_key='1,1,1'): scale_info = self.downsampling_scale_info.get(scale_key) if scale_info is None: raise ValueError('Invalid scale.') shape = scale_info.shape downsample_factor = scale_info.downsample_factor for i in range(3): if end[i] < start[i] or start[i] < 0 or end[i] > shape[i]: raise ValueError('Out of bounds data request.') indexing_expr = tuple(np.s_[start[i] * downsample_factor[i]:end[i] * downsample_factor[i]] for i in (2, 1, 0)) if len(self.data.shape) == 3: full_downsample_factor = downsample_factor[::-1] subvol = self.data[indexing_expr] else: full_downsample_factor = (1, ) + downsample_factor[::-1] subvol = self.data[(np.s_[:], ) + indexing_expr] if subvol.dtype == 'float64': subvol = np.cast[np.float32](subvol) if downsample_factor != (1, 1, 1): if self.volume_type == 'image': subvol = downsample.downsample_with_averaging(subvol, full_downsample_factor) else: subvol = downsample.downsample_with_striding(subvol, full_downsample_factor) content_type = 'application/octet-stream' if data_format == 'jpeg': data = encode_jpeg(subvol) content_type = 'image/jpeg' elif data_format == 'npz': data = encode_npz(subvol) elif data_format == 'raw': data = encode_raw(subvol) else: raise ValueError('Invalid data format requested.') return data, content_type def get_object_mesh(self, object_id): mesh_generator = self._get_mesh_generator() data = mesh_generator.get_mesh(object_id) if data is None: raise InvalidObjectIdForMesh() return data def _get_mesh_generator(self): if self._mesh_generator is not None: return self._mesh_generator while True: with self._mesh_generator_lock: if self._mesh_generator is not None: return self._mesh_generator if self._mesh_generator_pending is not None: while self._mesh_generator is None: self._mesh_generator_lock.wait() if self._mesh_generator is not None: return self._mesh_generator try: from . import _neuroglancer except ImportError: raise MeshImplementationNotAvailable() if not (self.num_channels == 1 and (self.data_type == 'uint8' or self.data_type == 'uint16' or self.data_type == 'uint32' or self.data_type == 'uint64')): raise MeshesNotSupportedForVolume() pending_obj = object() self._mesh_generator_pending = pending_obj if len(self.data.shape) == 4: data = self.data[0, :, :, :] else: data = self.data new_mesh_generator = _neuroglancer.OnDemandObjectMeshGenerator( data, self.voxel_size, self.offset / self.voxel_size, **self._mesh_options) with self._mesh_generator_lock: if self._mesh_generator_pending is not pending_obj: continue self._mesh_generator = new_mesh_generator self._mesh_generator_pending = False self._mesh_generator_lock.notify_all() return new_mesh_generator def __deepcopy__(self, memo): """Since this type is immutable, we don't need to deepcopy it. Actually deep copying would intefere with the use of deepcopy by JsonObjectWrapper. """ return self
KvasirSecurity/kvasirapi-python
KvasirAPI/config.py
Configuration.load
python
def load(self, configuration): try: self.config = yaml.load(open(configuration, "rb")) except IOError: try: self.config = yaml.load(configuration) except ParserError, e: raise ParserError('Error parsing config: %s' % e) # put customer data into self.customer if isinstance(self.config, dict): self.customer = self.config.get('customer', {}) self.instances_dict = self.config.get('instances', {}) self.web2py_dir = self.config.get('web2py', None) self.api_type = self.config.get('api_type', 'jsonrpc') self.valid = True else: self.customer = {} self.instances_dict = {} self.web2py_dir = None self.valid = False
Load a YAML configuration file. :param configuration: Configuration filename or YAML string
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/config.py#L51-L76
null
class Configuration(): """Loads configuration values from configuration files""" def __init__(self, configuration=None): self.config = {} self.web2py_dir = None self.customer = {} self.instances_dict = {} self.log = logging.getLogger(str(self.__class__)) self.version = __version__ self.api_type = None self.valid = False if configuration: self.load(configuration) def __getitem__(self, item): try: return self.instances_dict[item] except ValueError: return {} def keys(self): return self.instances_dict.keys() def instances(self, test_type=".*"): """ Returns a dict of all instances defined using a regex :param test_type: Regular expression to match for self.instance['test_type'] value names """ import re data = {} for k, v in self.instances_dict.iteritems(): if re.match(test_type, v.get('test_type'), re.IGNORECASE): if 'filter_type' in v: hostfilter = { 'filtertype': v['filter_type'], 'content': v['filter_value'] } else: hostfilter = {} data[k] = { 'name': v.get('name'), 'start': v.get('start'), 'end': v.get('end'), 'url': v.get('url'), 'hostfilter': hostfilter, 'test_type': v.get('test_type') } return data def instance_uri(self, instance="internal"): """ Returns the URI for a Kvasir instance :param instance: An instance name (exact) :return: The URL as parsed through make_good_url """ return make_good_url(self.instances_dict.get(instance, '{}').get('url'), ) def customer_info(self): """ Returns the customer information """ return self.customer
KvasirSecurity/kvasirapi-python
KvasirAPI/config.py
Configuration.instances
python
def instances(self, test_type=".*"): import re data = {} for k, v in self.instances_dict.iteritems(): if re.match(test_type, v.get('test_type'), re.IGNORECASE): if 'filter_type' in v: hostfilter = { 'filtertype': v['filter_type'], 'content': v['filter_value'] } else: hostfilter = {} data[k] = { 'name': v.get('name'), 'start': v.get('start'), 'end': v.get('end'), 'url': v.get('url'), 'hostfilter': hostfilter, 'test_type': v.get('test_type') } return data
Returns a dict of all instances defined using a regex :param test_type: Regular expression to match for self.instance['test_type'] value names
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/config.py#L78-L103
null
class Configuration(): """Loads configuration values from configuration files""" def __init__(self, configuration=None): self.config = {} self.web2py_dir = None self.customer = {} self.instances_dict = {} self.log = logging.getLogger(str(self.__class__)) self.version = __version__ self.api_type = None self.valid = False if configuration: self.load(configuration) def __getitem__(self, item): try: return self.instances_dict[item] except ValueError: return {} def keys(self): return self.instances_dict.keys() def load(self, configuration): """ Load a YAML configuration file. :param configuration: Configuration filename or YAML string """ try: self.config = yaml.load(open(configuration, "rb")) except IOError: try: self.config = yaml.load(configuration) except ParserError, e: raise ParserError('Error parsing config: %s' % e) # put customer data into self.customer if isinstance(self.config, dict): self.customer = self.config.get('customer', {}) self.instances_dict = self.config.get('instances', {}) self.web2py_dir = self.config.get('web2py', None) self.api_type = self.config.get('api_type', 'jsonrpc') self.valid = True else: self.customer = {} self.instances_dict = {} self.web2py_dir = None self.valid = False def instance_uri(self, instance="internal"): """ Returns the URI for a Kvasir instance :param instance: An instance name (exact) :return: The URL as parsed through make_good_url """ return make_good_url(self.instances_dict.get(instance, '{}').get('url'), ) def customer_info(self): """ Returns the customer information """ return self.customer
KvasirSecurity/kvasirapi-python
KvasirAPI/utils.py
none_to_blank
python
def none_to_blank(s, exchange=''): if isinstance(s, list): return [none_to_blank(z) for y, z in enumerate(s)] return exchange if s is None else unicode(s)
Replaces NoneType with '' >>> none_to_blank(None, '') '' >>> none_to_blank(None) '' >>> none_to_blank('something', '') u'something' >>> none_to_blank(['1', None]) [u'1', ''] :param s: String to replace :para exchange: Character to return for None, default is blank ('') :return: If s is None, returns exchange
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/utils.py#L24-L42
null
#!/usr/bin/env python # -*- coding: utf-8 -*- ##--------------------------------------# ## API for Kvasir ## ## (c) 2010-2014 Cisco Systems, Inc. ## ## Utility functions ## ## Author: Kurt Grutzmacher <kgrutzma@cisco.com> ##--------------------------------------# __author__ = "Kurt Grutzmacher <kgrutzma@cisco.com>" __date__ = "3 August 2014" __version__ = "1.0.0" KVASIR_JSONRPC_PATH = '/api/call/jsonrpc' __all__ = ['none_to_blank', 'make_good_url', 'build_kvasir_url'] ##------------------------------------------------------------------------- ##------------------------------------------------------------------------- def make_good_url(url=None, addition="/"): """Appends addition to url, ensuring the right number of slashes exist and the path doesn't get clobbered. >>> make_good_url('http://www.server.com/anywhere', 'else') 'http://www.server.com/anywhere/else' >>> make_good_url('http://test.com/', '/somewhere/over/the/rainbow/') 'http://test.com/somewhere/over/the/rainbow/' >>> make_good_url('None') 'None/' >>> make_good_url() >>> make_good_url({}) >>> make_good_url(addition='{}') :param url: URL :param addition: Something to add to the URL :return: New URL with addition""" if url is None: return None if isinstance(url, str) and isinstance(addition, str): return "%s/%s" % (url.rstrip('/'), addition.lstrip('/')) else: return None ##------------------------------------------------------------------------- def build_kvasir_url( proto="https", server="localhost", port="8443", base="Kvasir", user="test", password="test", path=KVASIR_JSONRPC_PATH): """ Creates a full URL to reach Kvasir given specific data >>> build_kvasir_url('https', 'localhost', '8443', 'Kvasir', 'test', 'test') 'https://test@test/localhost:8443/Kvasir/api/call/jsonrpc' >>> build_kvasir_url() 'https://test@test/localhost:8443/Kvasir/api/call/jsonrpc' >>> build_kvasir_url(server='localhost', port='443', password='password', path='bad/path') 'https://test@password/localhost:443/Kvasir/bad/path' :param proto: Protocol type - http or https :param server: Hostname or IP address of Web2py server :param port: Port to reach server :param base: Base application name :param user: Username for basic auth :param password: Password for basic auth :param path: Full path to JSONRPC (/api/call/jsonrpc) :return: A full URL that can reach Kvasir's JSONRPC interface """ uri = proto + '://' + user + '@' + password + '/' + server + ':' + port + '/' + base return make_good_url(uri, path)
KvasirSecurity/kvasirapi-python
KvasirAPI/utils.py
make_good_url
python
def make_good_url(url=None, addition="/"): if url is None: return None if isinstance(url, str) and isinstance(addition, str): return "%s/%s" % (url.rstrip('/'), addition.lstrip('/')) else: return None
Appends addition to url, ensuring the right number of slashes exist and the path doesn't get clobbered. >>> make_good_url('http://www.server.com/anywhere', 'else') 'http://www.server.com/anywhere/else' >>> make_good_url('http://test.com/', '/somewhere/over/the/rainbow/') 'http://test.com/somewhere/over/the/rainbow/' >>> make_good_url('None') 'None/' >>> make_good_url() >>> make_good_url({}) >>> make_good_url(addition='{}') :param url: URL :param addition: Something to add to the URL :return: New URL with addition
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/utils.py#L47-L71
null
#!/usr/bin/env python # -*- coding: utf-8 -*- ##--------------------------------------# ## API for Kvasir ## ## (c) 2010-2014 Cisco Systems, Inc. ## ## Utility functions ## ## Author: Kurt Grutzmacher <kgrutzma@cisco.com> ##--------------------------------------# __author__ = "Kurt Grutzmacher <kgrutzma@cisco.com>" __date__ = "3 August 2014" __version__ = "1.0.0" KVASIR_JSONRPC_PATH = '/api/call/jsonrpc' __all__ = ['none_to_blank', 'make_good_url', 'build_kvasir_url'] ##------------------------------------------------------------------------- def none_to_blank(s, exchange=''): """Replaces NoneType with '' >>> none_to_blank(None, '') '' >>> none_to_blank(None) '' >>> none_to_blank('something', '') u'something' >>> none_to_blank(['1', None]) [u'1', ''] :param s: String to replace :para exchange: Character to return for None, default is blank ('') :return: If s is None, returns exchange """ if isinstance(s, list): return [none_to_blank(z) for y, z in enumerate(s)] return exchange if s is None else unicode(s) ##------------------------------------------------------------------------- ##------------------------------------------------------------------------- def build_kvasir_url( proto="https", server="localhost", port="8443", base="Kvasir", user="test", password="test", path=KVASIR_JSONRPC_PATH): """ Creates a full URL to reach Kvasir given specific data >>> build_kvasir_url('https', 'localhost', '8443', 'Kvasir', 'test', 'test') 'https://test@test/localhost:8443/Kvasir/api/call/jsonrpc' >>> build_kvasir_url() 'https://test@test/localhost:8443/Kvasir/api/call/jsonrpc' >>> build_kvasir_url(server='localhost', port='443', password='password', path='bad/path') 'https://test@password/localhost:443/Kvasir/bad/path' :param proto: Protocol type - http or https :param server: Hostname or IP address of Web2py server :param port: Port to reach server :param base: Base application name :param user: Username for basic auth :param password: Password for basic auth :param path: Full path to JSONRPC (/api/call/jsonrpc) :return: A full URL that can reach Kvasir's JSONRPC interface """ uri = proto + '://' + user + '@' + password + '/' + server + ':' + port + '/' + base return make_good_url(uri, path)
KvasirSecurity/kvasirapi-python
KvasirAPI/utils.py
build_kvasir_url
python
def build_kvasir_url( proto="https", server="localhost", port="8443", base="Kvasir", user="test", password="test", path=KVASIR_JSONRPC_PATH): uri = proto + '://' + user + '@' + password + '/' + server + ':' + port + '/' + base return make_good_url(uri, path)
Creates a full URL to reach Kvasir given specific data >>> build_kvasir_url('https', 'localhost', '8443', 'Kvasir', 'test', 'test') 'https://test@test/localhost:8443/Kvasir/api/call/jsonrpc' >>> build_kvasir_url() 'https://test@test/localhost:8443/Kvasir/api/call/jsonrpc' >>> build_kvasir_url(server='localhost', port='443', password='password', path='bad/path') 'https://test@password/localhost:443/Kvasir/bad/path' :param proto: Protocol type - http or https :param server: Hostname or IP address of Web2py server :param port: Port to reach server :param base: Base application name :param user: Username for basic auth :param password: Password for basic auth :param path: Full path to JSONRPC (/api/call/jsonrpc) :return: A full URL that can reach Kvasir's JSONRPC interface
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/utils.py#L76-L100
[ "def make_good_url(url=None, addition=\"/\"):\n \"\"\"Appends addition to url, ensuring the right number of slashes\n exist and the path doesn't get clobbered.\n\n >>> make_good_url('http://www.server.com/anywhere', 'else')\n 'http://www.server.com/anywhere/else'\n >>> make_good_url('http://test.com/', '/somewhere/over/the/rainbow/')\n 'http://test.com/somewhere/over/the/rainbow/'\n >>> make_good_url('None')\n 'None/'\n >>> make_good_url()\n >>> make_good_url({})\n >>> make_good_url(addition='{}')\n\n :param url: URL\n :param addition: Something to add to the URL\n :return: New URL with addition\"\"\"\n\n if url is None:\n return None\n\n if isinstance(url, str) and isinstance(addition, str):\n return \"%s/%s\" % (url.rstrip('/'), addition.lstrip('/'))\n else:\n return None\n" ]
#!/usr/bin/env python # -*- coding: utf-8 -*- ##--------------------------------------# ## API for Kvasir ## ## (c) 2010-2014 Cisco Systems, Inc. ## ## Utility functions ## ## Author: Kurt Grutzmacher <kgrutzma@cisco.com> ##--------------------------------------# __author__ = "Kurt Grutzmacher <kgrutzma@cisco.com>" __date__ = "3 August 2014" __version__ = "1.0.0" KVASIR_JSONRPC_PATH = '/api/call/jsonrpc' __all__ = ['none_to_blank', 'make_good_url', 'build_kvasir_url'] ##------------------------------------------------------------------------- def none_to_blank(s, exchange=''): """Replaces NoneType with '' >>> none_to_blank(None, '') '' >>> none_to_blank(None) '' >>> none_to_blank('something', '') u'something' >>> none_to_blank(['1', None]) [u'1', ''] :param s: String to replace :para exchange: Character to return for None, default is blank ('') :return: If s is None, returns exchange """ if isinstance(s, list): return [none_to_blank(z) for y, z in enumerate(s)] return exchange if s is None else unicode(s) ##------------------------------------------------------------------------- def make_good_url(url=None, addition="/"): """Appends addition to url, ensuring the right number of slashes exist and the path doesn't get clobbered. >>> make_good_url('http://www.server.com/anywhere', 'else') 'http://www.server.com/anywhere/else' >>> make_good_url('http://test.com/', '/somewhere/over/the/rainbow/') 'http://test.com/somewhere/over/the/rainbow/' >>> make_good_url('None') 'None/' >>> make_good_url() >>> make_good_url({}) >>> make_good_url(addition='{}') :param url: URL :param addition: Something to add to the URL :return: New URL with addition""" if url is None: return None if isinstance(url, str) and isinstance(addition, str): return "%s/%s" % (url.rstrip('/'), addition.lstrip('/')) else: return None ##-------------------------------------------------------------------------
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/hosts.py
Hosts.add
python
def add(self, f_ipaddr, f_macaddr, f_hostname, f_netbios_name, f_engineer, f_asset_group, f_confirmed): return self.send.host_add(f_ipaddr, f_macaddr, f_hostname, f_netbios_name, f_engineer, f_asset_group, f_confirmed)
Add a t_hosts record :param f_ipaddr: IP address :param f_macaddr: MAC Address :param f_hostname: Hostname :param f_netbios_name: NetBIOS Name :param f_engineer: Engineer username :param f_asset_group: Asset group :param f_confirmed: Confirmed boolean :return: (True/False, t_hosts.id or response message)
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/hosts.py#L28-L42
null
class Hosts(ConnectorJSONRPC): def list(self, hostfilter=None): """ List of t_hosts :param hostfilter: Valid hostfilter or None :return: [(host.id, host.f_ipaddr, host.f_macaddr, host.f_hostname, host.f_netbios_name, db.auth_user[host.f_engineer].username, host.f_asset_group, host.f_confirmed) ...] """ return self.send.host_list(hostfilter) def info(self, host=None): """ Info about a t_hosts record :param host: t_hosts.id or IP Address :return: t_hosts fields """ return self.send.host_info(host) def detail(self, host=None): """ Detailed information about a host, not just t_hosts record :param host: t_hosts.id or IP Address :return: Dictionary of t_hosts record, additional points, services, accounts, vulns and snmp """ return self.send.host_details(host) def delete(self, host=None, ipaddr_list=None): """ Delete a t_hosts record or list of records :param host: t_hosts.id or list of ids :param ipaddr_list: IP Address or list of IP Addresses :return: [host_recs deleted, ip_recs deleted] """ return self.send.host_del(host, ipaddr_list)
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/services.py
Services.list
python
def list(self, service_rec=None, host_rec=None, hostfilter=None): return self.send.service_list(service_rec, host_rec, hostfilter)
List a specific service or all services :param service_rec: t_services.id :param host_rec: t_hosts.id :param hostfilter: Valid hostfilter or None :return: [(svc.t_services.id, svc.t_services.f_hosts_id, svc.t_hosts.f_ipaddr, svc.t_hosts.f_hostname, svc.t_services.f_proto, svc.t_services.f_number, svc.t_services.f_status, svc.t_services.f_name, svc.t_services.f_banner), ...]
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/services.py#L20-L32
null
class Services(ConnectorJSONRPC): """Services""" def list_only(self, host_rec=None, hostfilter=None): """ Returns a list of ports based on a t_hosts.id, hostfilter or all :param host_rec: t_hosts.id :param hostfilter: Valid hostfilter or None :return: [ service_id, host_id, ip, hostname, proto, number, status, name, banner, [ vuln list ...] ] """ return self.send.service_list_only(host_rec, hostfilter) def info(self, svc_rec=None, ipaddr=None, proto=None, port=None): """ Information about a service. :param svc_rec: t_services.id :param ipaddr: IP Address :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :return: [ service_id, host_id, ipv4, ipv6, hostname, proto, number, status, name, banner ] """ return self.send.service_info(svc_rec, ipaddr, proto, port) def add(self, ipaddr=None, proto=None, port=None, fields=None): """ Add a service record :param ipaddr: IP Address :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :param fields: Extra fields :return: (True/False, t_services.id or response message) """ return self.send.service_add(ipaddr, proto, port, fields) def delete(self, svc_rec=None, ipaddr=None, proto=None, port=None): """ Delete a t_services record :param svc_rec: t_services.id :param ipaddr: IP Address or t_hosts.id :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :return: [True, Response Message] """ return self.send.service_del(svc_rec, ipaddr, proto, port) def index_stats(self, hostfilter=None): """ Returns a services index of statistics :param hostfilter: Valid hostfilter or None :return: { 'service': [t_service.f_name, host count, unique vuln count, total vuln count], ... } """ return self.send.service_rpt_index_stats(hostfilter) def report_list(self, service_id=None, service_port=None, hostfilter=None): """ Returns a list of ports with IPs, banners and vulnerabilities (warning, slow!) :param service_id: t_services.id :param service_port: Port (tcp/#, udp/#, info/#) :param hostfilter: Valid hostfilter or None :return: { 'port': [t_hosts.f_ipaddr, t_services.f_banner, (t_vulndata.f_vulnid, t_vulndata.f_title, t_vulndata.f_severity, t_vulndata.f_cvss_score), ...} """ return self.send.service_report_list(service_id, service_port, hostfilter) def vulns_list(self, service_id=None, service_port=None, hostfilter=None): """ List of vulnerabilities for a service :param service_id: t_services.id :param service_port: tcp/#, udp/# or info/# :param hostfilter: Valid hostfilter or None :return: t_services.rows.as_list() """ return self.send.service_vulns_list(service_id, service_port, hostfilter) def vuln_iptable(self, hostfilter=None): """ Returns a dict of services containing IPs with (vuln, severity) :param hostfilter: Valid hostfilter or None :return: '0/info': { 'host_id1': [ (ip, hostname), ( (vuln1, 5), (vuln2, 10) ... ) ] }, { 'host_id2': [ (ip, hostname), ( (vuln1, 5) ) ] } """ return self.send.service_vuln_iptable(hostfilter)
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/services.py
Services.info
python
def info(self, svc_rec=None, ipaddr=None, proto=None, port=None): return self.send.service_info(svc_rec, ipaddr, proto, port)
Information about a service. :param svc_rec: t_services.id :param ipaddr: IP Address :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :return: [ service_id, host_id, ipv4, ipv6, hostname, proto, number, status, name, banner ]
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/services.py#L44-L54
null
class Services(ConnectorJSONRPC): """Services""" def list(self, service_rec=None, host_rec=None, hostfilter=None): """ List a specific service or all services :param service_rec: t_services.id :param host_rec: t_hosts.id :param hostfilter: Valid hostfilter or None :return: [(svc.t_services.id, svc.t_services.f_hosts_id, svc.t_hosts.f_ipaddr, svc.t_hosts.f_hostname, svc.t_services.f_proto, svc.t_services.f_number, svc.t_services.f_status, svc.t_services.f_name, svc.t_services.f_banner), ...] """ return self.send.service_list(service_rec, host_rec, hostfilter) def list_only(self, host_rec=None, hostfilter=None): """ Returns a list of ports based on a t_hosts.id, hostfilter or all :param host_rec: t_hosts.id :param hostfilter: Valid hostfilter or None :return: [ service_id, host_id, ip, hostname, proto, number, status, name, banner, [ vuln list ...] ] """ return self.send.service_list_only(host_rec, hostfilter) def add(self, ipaddr=None, proto=None, port=None, fields=None): """ Add a service record :param ipaddr: IP Address :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :param fields: Extra fields :return: (True/False, t_services.id or response message) """ return self.send.service_add(ipaddr, proto, port, fields) def delete(self, svc_rec=None, ipaddr=None, proto=None, port=None): """ Delete a t_services record :param svc_rec: t_services.id :param ipaddr: IP Address or t_hosts.id :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :return: [True, Response Message] """ return self.send.service_del(svc_rec, ipaddr, proto, port) def index_stats(self, hostfilter=None): """ Returns a services index of statistics :param hostfilter: Valid hostfilter or None :return: { 'service': [t_service.f_name, host count, unique vuln count, total vuln count], ... } """ return self.send.service_rpt_index_stats(hostfilter) def report_list(self, service_id=None, service_port=None, hostfilter=None): """ Returns a list of ports with IPs, banners and vulnerabilities (warning, slow!) :param service_id: t_services.id :param service_port: Port (tcp/#, udp/#, info/#) :param hostfilter: Valid hostfilter or None :return: { 'port': [t_hosts.f_ipaddr, t_services.f_banner, (t_vulndata.f_vulnid, t_vulndata.f_title, t_vulndata.f_severity, t_vulndata.f_cvss_score), ...} """ return self.send.service_report_list(service_id, service_port, hostfilter) def vulns_list(self, service_id=None, service_port=None, hostfilter=None): """ List of vulnerabilities for a service :param service_id: t_services.id :param service_port: tcp/#, udp/# or info/# :param hostfilter: Valid hostfilter or None :return: t_services.rows.as_list() """ return self.send.service_vulns_list(service_id, service_port, hostfilter) def vuln_iptable(self, hostfilter=None): """ Returns a dict of services containing IPs with (vuln, severity) :param hostfilter: Valid hostfilter or None :return: '0/info': { 'host_id1': [ (ip, hostname), ( (vuln1, 5), (vuln2, 10) ... ) ] }, { 'host_id2': [ (ip, hostname), ( (vuln1, 5) ) ] } """ return self.send.service_vuln_iptable(hostfilter)
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/services.py
Services.add
python
def add(self, ipaddr=None, proto=None, port=None, fields=None): return self.send.service_add(ipaddr, proto, port, fields)
Add a service record :param ipaddr: IP Address :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :param fields: Extra fields :return: (True/False, t_services.id or response message)
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/services.py#L56-L66
null
class Services(ConnectorJSONRPC): """Services""" def list(self, service_rec=None, host_rec=None, hostfilter=None): """ List a specific service or all services :param service_rec: t_services.id :param host_rec: t_hosts.id :param hostfilter: Valid hostfilter or None :return: [(svc.t_services.id, svc.t_services.f_hosts_id, svc.t_hosts.f_ipaddr, svc.t_hosts.f_hostname, svc.t_services.f_proto, svc.t_services.f_number, svc.t_services.f_status, svc.t_services.f_name, svc.t_services.f_banner), ...] """ return self.send.service_list(service_rec, host_rec, hostfilter) def list_only(self, host_rec=None, hostfilter=None): """ Returns a list of ports based on a t_hosts.id, hostfilter or all :param host_rec: t_hosts.id :param hostfilter: Valid hostfilter or None :return: [ service_id, host_id, ip, hostname, proto, number, status, name, banner, [ vuln list ...] ] """ return self.send.service_list_only(host_rec, hostfilter) def info(self, svc_rec=None, ipaddr=None, proto=None, port=None): """ Information about a service. :param svc_rec: t_services.id :param ipaddr: IP Address :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :return: [ service_id, host_id, ipv4, ipv6, hostname, proto, number, status, name, banner ] """ return self.send.service_info(svc_rec, ipaddr, proto, port) def delete(self, svc_rec=None, ipaddr=None, proto=None, port=None): """ Delete a t_services record :param svc_rec: t_services.id :param ipaddr: IP Address or t_hosts.id :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :return: [True, Response Message] """ return self.send.service_del(svc_rec, ipaddr, proto, port) def index_stats(self, hostfilter=None): """ Returns a services index of statistics :param hostfilter: Valid hostfilter or None :return: { 'service': [t_service.f_name, host count, unique vuln count, total vuln count], ... } """ return self.send.service_rpt_index_stats(hostfilter) def report_list(self, service_id=None, service_port=None, hostfilter=None): """ Returns a list of ports with IPs, banners and vulnerabilities (warning, slow!) :param service_id: t_services.id :param service_port: Port (tcp/#, udp/#, info/#) :param hostfilter: Valid hostfilter or None :return: { 'port': [t_hosts.f_ipaddr, t_services.f_banner, (t_vulndata.f_vulnid, t_vulndata.f_title, t_vulndata.f_severity, t_vulndata.f_cvss_score), ...} """ return self.send.service_report_list(service_id, service_port, hostfilter) def vulns_list(self, service_id=None, service_port=None, hostfilter=None): """ List of vulnerabilities for a service :param service_id: t_services.id :param service_port: tcp/#, udp/# or info/# :param hostfilter: Valid hostfilter or None :return: t_services.rows.as_list() """ return self.send.service_vulns_list(service_id, service_port, hostfilter) def vuln_iptable(self, hostfilter=None): """ Returns a dict of services containing IPs with (vuln, severity) :param hostfilter: Valid hostfilter or None :return: '0/info': { 'host_id1': [ (ip, hostname), ( (vuln1, 5), (vuln2, 10) ... ) ] }, { 'host_id2': [ (ip, hostname), ( (vuln1, 5) ) ] } """ return self.send.service_vuln_iptable(hostfilter)
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/services.py
Services.delete
python
def delete(self, svc_rec=None, ipaddr=None, proto=None, port=None): return self.send.service_del(svc_rec, ipaddr, proto, port)
Delete a t_services record :param svc_rec: t_services.id :param ipaddr: IP Address or t_hosts.id :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :return: [True, Response Message]
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/services.py#L68-L78
null
class Services(ConnectorJSONRPC): """Services""" def list(self, service_rec=None, host_rec=None, hostfilter=None): """ List a specific service or all services :param service_rec: t_services.id :param host_rec: t_hosts.id :param hostfilter: Valid hostfilter or None :return: [(svc.t_services.id, svc.t_services.f_hosts_id, svc.t_hosts.f_ipaddr, svc.t_hosts.f_hostname, svc.t_services.f_proto, svc.t_services.f_number, svc.t_services.f_status, svc.t_services.f_name, svc.t_services.f_banner), ...] """ return self.send.service_list(service_rec, host_rec, hostfilter) def list_only(self, host_rec=None, hostfilter=None): """ Returns a list of ports based on a t_hosts.id, hostfilter or all :param host_rec: t_hosts.id :param hostfilter: Valid hostfilter or None :return: [ service_id, host_id, ip, hostname, proto, number, status, name, banner, [ vuln list ...] ] """ return self.send.service_list_only(host_rec, hostfilter) def info(self, svc_rec=None, ipaddr=None, proto=None, port=None): """ Information about a service. :param svc_rec: t_services.id :param ipaddr: IP Address :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :return: [ service_id, host_id, ipv4, ipv6, hostname, proto, number, status, name, banner ] """ return self.send.service_info(svc_rec, ipaddr, proto, port) def add(self, ipaddr=None, proto=None, port=None, fields=None): """ Add a service record :param ipaddr: IP Address :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :param fields: Extra fields :return: (True/False, t_services.id or response message) """ return self.send.service_add(ipaddr, proto, port, fields) def index_stats(self, hostfilter=None): """ Returns a services index of statistics :param hostfilter: Valid hostfilter or None :return: { 'service': [t_service.f_name, host count, unique vuln count, total vuln count], ... } """ return self.send.service_rpt_index_stats(hostfilter) def report_list(self, service_id=None, service_port=None, hostfilter=None): """ Returns a list of ports with IPs, banners and vulnerabilities (warning, slow!) :param service_id: t_services.id :param service_port: Port (tcp/#, udp/#, info/#) :param hostfilter: Valid hostfilter or None :return: { 'port': [t_hosts.f_ipaddr, t_services.f_banner, (t_vulndata.f_vulnid, t_vulndata.f_title, t_vulndata.f_severity, t_vulndata.f_cvss_score), ...} """ return self.send.service_report_list(service_id, service_port, hostfilter) def vulns_list(self, service_id=None, service_port=None, hostfilter=None): """ List of vulnerabilities for a service :param service_id: t_services.id :param service_port: tcp/#, udp/# or info/# :param hostfilter: Valid hostfilter or None :return: t_services.rows.as_list() """ return self.send.service_vulns_list(service_id, service_port, hostfilter) def vuln_iptable(self, hostfilter=None): """ Returns a dict of services containing IPs with (vuln, severity) :param hostfilter: Valid hostfilter or None :return: '0/info': { 'host_id1': [ (ip, hostname), ( (vuln1, 5), (vuln2, 10) ... ) ] }, { 'host_id2': [ (ip, hostname), ( (vuln1, 5) ) ] } """ return self.send.service_vuln_iptable(hostfilter)
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/services.py
Services.report_list
python
def report_list(self, service_id=None, service_port=None, hostfilter=None): return self.send.service_report_list(service_id, service_port, hostfilter)
Returns a list of ports with IPs, banners and vulnerabilities (warning, slow!) :param service_id: t_services.id :param service_port: Port (tcp/#, udp/#, info/#) :param hostfilter: Valid hostfilter or None :return: { 'port': [t_hosts.f_ipaddr, t_services.f_banner, (t_vulndata.f_vulnid, t_vulndata.f_title, t_vulndata.f_severity, t_vulndata.f_cvss_score), ...}
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/services.py#L89-L99
null
class Services(ConnectorJSONRPC): """Services""" def list(self, service_rec=None, host_rec=None, hostfilter=None): """ List a specific service or all services :param service_rec: t_services.id :param host_rec: t_hosts.id :param hostfilter: Valid hostfilter or None :return: [(svc.t_services.id, svc.t_services.f_hosts_id, svc.t_hosts.f_ipaddr, svc.t_hosts.f_hostname, svc.t_services.f_proto, svc.t_services.f_number, svc.t_services.f_status, svc.t_services.f_name, svc.t_services.f_banner), ...] """ return self.send.service_list(service_rec, host_rec, hostfilter) def list_only(self, host_rec=None, hostfilter=None): """ Returns a list of ports based on a t_hosts.id, hostfilter or all :param host_rec: t_hosts.id :param hostfilter: Valid hostfilter or None :return: [ service_id, host_id, ip, hostname, proto, number, status, name, banner, [ vuln list ...] ] """ return self.send.service_list_only(host_rec, hostfilter) def info(self, svc_rec=None, ipaddr=None, proto=None, port=None): """ Information about a service. :param svc_rec: t_services.id :param ipaddr: IP Address :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :return: [ service_id, host_id, ipv4, ipv6, hostname, proto, number, status, name, banner ] """ return self.send.service_info(svc_rec, ipaddr, proto, port) def add(self, ipaddr=None, proto=None, port=None, fields=None): """ Add a service record :param ipaddr: IP Address :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :param fields: Extra fields :return: (True/False, t_services.id or response message) """ return self.send.service_add(ipaddr, proto, port, fields) def delete(self, svc_rec=None, ipaddr=None, proto=None, port=None): """ Delete a t_services record :param svc_rec: t_services.id :param ipaddr: IP Address or t_hosts.id :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :return: [True, Response Message] """ return self.send.service_del(svc_rec, ipaddr, proto, port) def index_stats(self, hostfilter=None): """ Returns a services index of statistics :param hostfilter: Valid hostfilter or None :return: { 'service': [t_service.f_name, host count, unique vuln count, total vuln count], ... } """ return self.send.service_rpt_index_stats(hostfilter) def vulns_list(self, service_id=None, service_port=None, hostfilter=None): """ List of vulnerabilities for a service :param service_id: t_services.id :param service_port: tcp/#, udp/# or info/# :param hostfilter: Valid hostfilter or None :return: t_services.rows.as_list() """ return self.send.service_vulns_list(service_id, service_port, hostfilter) def vuln_iptable(self, hostfilter=None): """ Returns a dict of services containing IPs with (vuln, severity) :param hostfilter: Valid hostfilter or None :return: '0/info': { 'host_id1': [ (ip, hostname), ( (vuln1, 5), (vuln2, 10) ... ) ] }, { 'host_id2': [ (ip, hostname), ( (vuln1, 5) ) ] } """ return self.send.service_vuln_iptable(hostfilter)
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/services.py
Services.vulns_list
python
def vulns_list(self, service_id=None, service_port=None, hostfilter=None): return self.send.service_vulns_list(service_id, service_port, hostfilter)
List of vulnerabilities for a service :param service_id: t_services.id :param service_port: tcp/#, udp/# or info/# :param hostfilter: Valid hostfilter or None :return: t_services.rows.as_list()
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/services.py#L101-L110
null
class Services(ConnectorJSONRPC): """Services""" def list(self, service_rec=None, host_rec=None, hostfilter=None): """ List a specific service or all services :param service_rec: t_services.id :param host_rec: t_hosts.id :param hostfilter: Valid hostfilter or None :return: [(svc.t_services.id, svc.t_services.f_hosts_id, svc.t_hosts.f_ipaddr, svc.t_hosts.f_hostname, svc.t_services.f_proto, svc.t_services.f_number, svc.t_services.f_status, svc.t_services.f_name, svc.t_services.f_banner), ...] """ return self.send.service_list(service_rec, host_rec, hostfilter) def list_only(self, host_rec=None, hostfilter=None): """ Returns a list of ports based on a t_hosts.id, hostfilter or all :param host_rec: t_hosts.id :param hostfilter: Valid hostfilter or None :return: [ service_id, host_id, ip, hostname, proto, number, status, name, banner, [ vuln list ...] ] """ return self.send.service_list_only(host_rec, hostfilter) def info(self, svc_rec=None, ipaddr=None, proto=None, port=None): """ Information about a service. :param svc_rec: t_services.id :param ipaddr: IP Address :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :return: [ service_id, host_id, ipv4, ipv6, hostname, proto, number, status, name, banner ] """ return self.send.service_info(svc_rec, ipaddr, proto, port) def add(self, ipaddr=None, proto=None, port=None, fields=None): """ Add a service record :param ipaddr: IP Address :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :param fields: Extra fields :return: (True/False, t_services.id or response message) """ return self.send.service_add(ipaddr, proto, port, fields) def delete(self, svc_rec=None, ipaddr=None, proto=None, port=None): """ Delete a t_services record :param svc_rec: t_services.id :param ipaddr: IP Address or t_hosts.id :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :return: [True, Response Message] """ return self.send.service_del(svc_rec, ipaddr, proto, port) def index_stats(self, hostfilter=None): """ Returns a services index of statistics :param hostfilter: Valid hostfilter or None :return: { 'service': [t_service.f_name, host count, unique vuln count, total vuln count], ... } """ return self.send.service_rpt_index_stats(hostfilter) def report_list(self, service_id=None, service_port=None, hostfilter=None): """ Returns a list of ports with IPs, banners and vulnerabilities (warning, slow!) :param service_id: t_services.id :param service_port: Port (tcp/#, udp/#, info/#) :param hostfilter: Valid hostfilter or None :return: { 'port': [t_hosts.f_ipaddr, t_services.f_banner, (t_vulndata.f_vulnid, t_vulndata.f_title, t_vulndata.f_severity, t_vulndata.f_cvss_score), ...} """ return self.send.service_report_list(service_id, service_port, hostfilter) def vuln_iptable(self, hostfilter=None): """ Returns a dict of services containing IPs with (vuln, severity) :param hostfilter: Valid hostfilter or None :return: '0/info': { 'host_id1': [ (ip, hostname), ( (vuln1, 5), (vuln2, 10) ... ) ] }, { 'host_id2': [ (ip, hostname), ( (vuln1, 5) ) ] } """ return self.send.service_vuln_iptable(hostfilter)
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/evidence.py
Evidence.add
python
def add(self, host, filename, data, f_type, f_other_type=None, f_text=''): return self.send.evidence_add(host, filename, data, f_type, f_other_type, f_text)
Add evidence :param host: db.t_hosts.id :param filename: Filename :param data: Content of file :param f_type: Evidence type :param f_other_type: If f_type is 'Other' what type it is :param f_text: Text information about the evidence :return: (True/False, response message)
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/evidence.py#L43-L55
null
class Evidence(ConnectorJSONRPC): """Evidence""" def list(self, host=None): """ List db.t_evidence records :param query: A record id, ipv4, ipv6, hostname or None for all records :returns t_evidence.id: :returns t_evidence.f_type: :returns t_evidence.f_other_type: :returns t_evidence.f_text: :returns t_evidence.f_evidence: :returns t_evidence.f_filename: """ return self.send.evidence_list(host) def download(self, filename=None): """ Download a specific evidence file :param filename: Filename to download :return: File content """ return self.send.evidence_download(filename) def delete(self, evidence_records=None): """ Delete evidence record(s) :param evidence_records: [db.t_evidence.id, db.t_evidence.id, ... ] :return: List of (True/False, response message) for each evidence """ return self.send.evidence_del(evidence_records)
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/vulns.py
Vulns.list
python
def list(self, host_rec=None, service_rec=None, hostfilter=None): return self.send.vuln_list(host_rec, service_rec, hostfilter)
Returns a list of vulnerabilities based on t_hosts.id or t_services.id. If neither are set then statistical results are added :param host_rec: db.t_hosts.id :param service_rec: db.t_services.id :param hostfilter: Valid hostfilter or None :return: [(vulndata) ...] if host_rec or service_rec set :return: [(vulndata, vuln_cnt, [vuln_ip, ...], [services ...]) ...] if nothing sent
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/vulns.py#L20-L31
null
class Vulns(ConnectorJSONRPC): """Vulnerabilities""" def info(self, vuln_name=None, vuln_id=None): """ Returns information about a vulnerability :param vuln_name: t_vulndata.f_vulnid :param vuln_id: t_vulndata.id :return: vulnerability data """ return self.send.vuln_info(vuln_name, vuln_id) def ip_info(self, vuln_name=None, vuln_id=None, ip_list_only=True, hostfilter=None): """ List of all IP Addresses with a vulnerability :param vuln_name: t_vulndata.f_vulnid :param vuln_id: t_vulndata.id :param ip_list_only: IP List only (default) or rest of t_hosts fields :param hostfilter: Valid hostfilter or none :return: [(ip, hostname) ...] or [(ip, hostname, t_service_vulns.f_proof, t_service_vulns.f_status), ...] """ return self.send.vuln_ip_info(vuln_name, vuln_id, ip_list_only, hostfilter) def service_list(self, vuln_name=None, vuln_id=None, hostfilter=None): """ Returns a dictionary of vulns with services and IP Addresses :param vuln_name: t_vulndata.f_vulnid :param vuln_id: t_vulndata.id :param hostfilter: Valid hostfilter or none :return: {'vuln-id': {'port': [ ip, hostname ]} ...} ... """ return self.send.vuln_service_list(vuln_name, vuln_id, hostfilter)
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/vulns.py
Vulns.ip_info
python
def ip_info(self, vuln_name=None, vuln_id=None, ip_list_only=True, hostfilter=None): return self.send.vuln_ip_info(vuln_name, vuln_id, ip_list_only, hostfilter)
List of all IP Addresses with a vulnerability :param vuln_name: t_vulndata.f_vulnid :param vuln_id: t_vulndata.id :param ip_list_only: IP List only (default) or rest of t_hosts fields :param hostfilter: Valid hostfilter or none :return: [(ip, hostname) ...] or [(ip, hostname, t_service_vulns.f_proof, t_service_vulns.f_status), ...]
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/vulns.py#L43-L53
null
class Vulns(ConnectorJSONRPC): """Vulnerabilities""" def list(self, host_rec=None, service_rec=None, hostfilter=None): """ Returns a list of vulnerabilities based on t_hosts.id or t_services.id. If neither are set then statistical results are added :param host_rec: db.t_hosts.id :param service_rec: db.t_services.id :param hostfilter: Valid hostfilter or None :return: [(vulndata) ...] if host_rec or service_rec set :return: [(vulndata, vuln_cnt, [vuln_ip, ...], [services ...]) ...] if nothing sent """ return self.send.vuln_list(host_rec, service_rec, hostfilter) def info(self, vuln_name=None, vuln_id=None): """ Returns information about a vulnerability :param vuln_name: t_vulndata.f_vulnid :param vuln_id: t_vulndata.id :return: vulnerability data """ return self.send.vuln_info(vuln_name, vuln_id) def service_list(self, vuln_name=None, vuln_id=None, hostfilter=None): """ Returns a dictionary of vulns with services and IP Addresses :param vuln_name: t_vulndata.f_vulnid :param vuln_id: t_vulndata.id :param hostfilter: Valid hostfilter or none :return: {'vuln-id': {'port': [ ip, hostname ]} ...} ... """ return self.send.vuln_service_list(vuln_name, vuln_id, hostfilter)
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/vulns.py
Vulns.service_list
python
def service_list(self, vuln_name=None, vuln_id=None, hostfilter=None): return self.send.vuln_service_list(vuln_name, vuln_id, hostfilter)
Returns a dictionary of vulns with services and IP Addresses :param vuln_name: t_vulndata.f_vulnid :param vuln_id: t_vulndata.id :param hostfilter: Valid hostfilter or none :return: {'vuln-id': {'port': [ ip, hostname ]} ...} ...
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/vulns.py#L55-L64
null
class Vulns(ConnectorJSONRPC): """Vulnerabilities""" def list(self, host_rec=None, service_rec=None, hostfilter=None): """ Returns a list of vulnerabilities based on t_hosts.id or t_services.id. If neither are set then statistical results are added :param host_rec: db.t_hosts.id :param service_rec: db.t_services.id :param hostfilter: Valid hostfilter or None :return: [(vulndata) ...] if host_rec or service_rec set :return: [(vulndata, vuln_cnt, [vuln_ip, ...], [services ...]) ...] if nothing sent """ return self.send.vuln_list(host_rec, service_rec, hostfilter) def info(self, vuln_name=None, vuln_id=None): """ Returns information about a vulnerability :param vuln_name: t_vulndata.f_vulnid :param vuln_id: t_vulndata.id :return: vulnerability data """ return self.send.vuln_info(vuln_name, vuln_id) def ip_info(self, vuln_name=None, vuln_id=None, ip_list_only=True, hostfilter=None): """ List of all IP Addresses with a vulnerability :param vuln_name: t_vulndata.f_vulnid :param vuln_id: t_vulndata.id :param ip_list_only: IP List only (default) or rest of t_hosts fields :param hostfilter: Valid hostfilter or none :return: [(ip, hostname) ...] or [(ip, hostname, t_service_vulns.f_proof, t_service_vulns.f_status), ...] """ return self.send.vuln_ip_info(vuln_name, vuln_id, ip_list_only, hostfilter)
KvasirSecurity/kvasirapi-python
KvasirAPI/API.py
API.load_calls
python
def load_calls(self, call_type='jsonrpc'): valid = False if call_type == 'jsonrpc': #from jsonrpc import Hosts, Services, Accounts, Vulns, OS, NetBIOS, Evidence import jsonrpc as api_calls self.api_calls = api_calls valid = True #if call_type == 'rest' # TODO: Implement restful API functions #from restapi import hosts, services, accounts, vulns, os, netbios, evidence if valid: # if kvasir configuration is valid, go through the instances and build the self.call dict for instance, values in self.configuration.instances_dict.items(): self.call[instance] = Calls() self.call[instance].call_type = call_type self.call[instance].hosts = self.api_calls.Hosts(values, self.configuration.web2py_dir) self.call[instance].services = self.api_calls.Services(values, self.configuration.web2py_dir) self.call[instance].accounts = self.api_calls.Accounts(values, self.configuration.web2py_dir) self.call[instance].vulns = self.api_calls.Vulns(values, self.configuration.web2py_dir) self.call[instance].os = self.api_calls.OpSys(values, self.configuration.web2py_dir) self.call[instance].snmp = self.api_calls.SNMP(values, self.configuration.web2py_dir) self.call[instance].netbios = self.api_calls.NetBIOS(values, self.configuration.web2py_dir) self.call[instance].evidence = self.api_calls.Evidence(values, self.configuration.web2py_dir) self.call[instance].stats = self.api_calls.Stats(values, self.configuration.web2py_dir)
Loads the KvasirAPI calls into API.call based on the call_type variable. Utilizes the `Calls` class to establish an attribute-based access method. For instance a configuration with an instance called 'internal' will create an API.call that can be used like this: API.call.internal.hosts.list() # return all hosts from Kvasir instance 'internal' :param call_type: string of 'jsonrpc' or 'restapi' :return: self.call dictionary
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/API.py#L95-L128
null
class API(): """An API to communicate with Kvasir. Kvasir is a Penetration Testing Data Management system (https://github.com/KvasirSecurity/Kvasir). This API allows third-party tools to communicate with Kvasir through a JSONRPC library. To use: ``` import KvasirAPI kvasir = KvasirAPI.API('config.yaml') ``` Multiple Kvasir instances can be defined in the configuration file. A sample configuration: ``` customer: id: 11-ACME-01 full-name: ACME Widgets, Inc. short-name: ACME possessive: ACME Widget, Inc's short-capital: ACME possessive-capital: ACME's instances: internal: url: "http://username:password@localhost:8000/internal/" name: Internal Network test_type: internal start: May 2, 2011 end: May 6, 2011 filter_type: assetgroup filter_value: organization external: url: "http://username:password@localhost:8000/external/" test_type: external start: May 2, 2011 end: May 6, 2011 name: External Network web2py: build/web2py ``` """ def __init__(self, configuration=None): """ Kvasir API initialization :param configuration: YAML configuration in a string or filename :return: instance """ self.api_version = __version__ self._representation = "Kvasir v%s" % __version__ self.api_calls = None self.configuration = Configuration(configuration) self.call = Calls() if self.configuration.valid: self.load_calls(self.configuration.api_type) def __repr__(self): return self._representation @property def version(self): return self.api_version
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/snmp.py
SNMP.list
python
def list(self, community=None, hostfilter=None, host=None): return self.send.snmp_list(community, hostfilter, host)
Returns a list of SNMP information for a community, hostfilter or host :param snmpstring: A specific SNMP string to list :param hostfilter: Valid hostfilter or None :param host: t_hosts.id or t_hosts.f_ipaddr :return: [ [ record_id, ipaddr, hostname, community, access, version ] ... ]
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/snmp.py#L29-L37
null
class SNMP(ConnectorJSONRPC): """SNMP""" def list_communities(self, hostfilter=None): """ Returns a list of all known SNMP community strings :param hostfilter: Valid hostfilter or None :return: list of community strings """ return self.send.snmp_list_communities(hostfilter) def add(self, host=None, f_community=None, f_access=None, f_version=None): """ Add an SNMP community string to a host :param host: t_hosts.id or t_hosts.f_ipaddr :param f_community: Community string to add :param f_access: READ or WRITE :param f_version: v1, v2c or v3 :return: (True/False, t_snmp.id/Error string) """ return self.send.snmp_add(host, f_community, f_access, f_version) def delete(self, record=None): """ Delete a t_snmp record :param record: [db.t_snmp.id, db.t_snmp_id, ...] :return: [(True/False, Response string) ...] """ return self.send.snmp_del(record) def rpt_table(self, hostfilter=None): """ Builds a report-like table of community strings, counts and permissions :param hostfilter: Valid hostfilter or None :return: ([t_snmp.f_community, count, t_snmp.f_access] ...) """ return self.send.snmp_rpt_table(hostfilter)
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/snmp.py
SNMP.add
python
def add(self, host=None, f_community=None, f_access=None, f_version=None): return self.send.snmp_add(host, f_community, f_access, f_version)
Add an SNMP community string to a host :param host: t_hosts.id or t_hosts.f_ipaddr :param f_community: Community string to add :param f_access: READ or WRITE :param f_version: v1, v2c or v3 :return: (True/False, t_snmp.id/Error string)
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/snmp.py#L39-L49
null
class SNMP(ConnectorJSONRPC): """SNMP""" def list_communities(self, hostfilter=None): """ Returns a list of all known SNMP community strings :param hostfilter: Valid hostfilter or None :return: list of community strings """ return self.send.snmp_list_communities(hostfilter) def list(self, community=None, hostfilter=None, host=None): """ Returns a list of SNMP information for a community, hostfilter or host :param snmpstring: A specific SNMP string to list :param hostfilter: Valid hostfilter or None :param host: t_hosts.id or t_hosts.f_ipaddr :return: [ [ record_id, ipaddr, hostname, community, access, version ] ... ] """ return self.send.snmp_list(community, hostfilter, host) def delete(self, record=None): """ Delete a t_snmp record :param record: [db.t_snmp.id, db.t_snmp_id, ...] :return: [(True/False, Response string) ...] """ return self.send.snmp_del(record) def rpt_table(self, hostfilter=None): """ Builds a report-like table of community strings, counts and permissions :param hostfilter: Valid hostfilter or None :return: ([t_snmp.f_community, count, t_snmp.f_access] ...) """ return self.send.snmp_rpt_table(hostfilter)
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/accounts.py
Accounts.list
python
def list(self, svc_rec=None, hostfilter=None, compromised=False): return self.send.accounts_list(svc_rec, hostfilter, compromised)
List user accounts :param svc_rec: db.t_services.id :param hostfilter: :param compromised: Show only compromised accounts :return: [acct.t_accounts.f_services_id, acct.t_hosts.f_ipaddr, acct.t_hosts.f_hostname, acct.t_accounts.id, acct.t_accounts.f_username, acct.t_accounts.f_fullname, acct.t_accounts.f_password, acct.t_accounts.f_compromised, acct.t_accounts.f_hash1, acct.t_accounts.f_hash1_type, acct.t_accounts.f_hash2, acct.t_accounts.f_hash2_type, acct.t_accounts.f_source, acct.t_accounts.f_uid, acct.t_accounts.f_gid, acct.t_accounts.f_level, acct.t_accounts.f_domain, acct.t_accounts.f_message, acct.t_accounts.f_lockout, acct.t_accounts.f_duration, acct.t_accounts.f_active, acct.t_accounts.f_description, acct.t_services.f_proto, acct.t_services.f_number, ]
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/accounts.py#L20-L42
null
class Accounts(ConnectorJSONRPC): """User accounts""" def add(self, svc_rec=None, records=None): """ Add account data :param svc_rec: db.t_services.id :param records: db.t_accounts field content dictionary :return: (True/False, db.t_accounts.id) """ return self.send.accounts_add(svc_rec, records) def info(self, rec=None): """ Information about an account :param rec: db.t_accounts.id :return: [True/False, hostrec.f_ipaddr, hostrec.f_hostname, svc_rec.f_proto, svc_rec.f_number, acct.id, acct.f_username, acct.f_fullname, acct.f_password, acct.f_compromised, acct.f_hash1, acct.f_hash1_type, acct.f_hash2, acct.f_hash2_type, acct.f_source, acct.f_uid, acct.f_gid, acct.f_level, acct.f_domain, acct.f_message, acct.f_lockout, acct.f_duration, acct.f_active, acct.f_description] """ return self.send.accounts_info(rec) def update(self, rec=None, values=None): """ Update a db.t_accounts record :param rec: db.t_accounts.id :param values: db.t_accounts fields to update :return: (True/False, Message) """ return self.send.accounts_update(rec, values) def list_pw_types(self): """ List the known password types :return: """ return self.send.list_pw_types() def upload_file(self, service_rec=None, host_service=None, filename=None, pw_data=None, f_type=None, add_to_evidence=True): """ Upload a password file :param service_rec: db.t_services.id :param host_service: db.t_hosts.id :param filename: Filename :param pw_data: Content of file :param f_type: Type of file :param add_to_evidence: True/False to add to t_evidence :return: (True/False, Response Message) """ return self.send.accounts_upload_file(service_rec, host_service, filename, pw_data, f_type, add_to_evidence) def delete(self, rec=None): """ Delete a db.t_accounts record :param rec: [db.t_accounts.id, db.t_accounts.id, ... ] :return: (True/False, Message string) """ return self.send.accounts_del(rec) def index_data(self, hostfilter=None): """ List of IP Addresses and account statistics. :param hostfilter: Hostfilter dict :return: """ return self.send.accounts_index_data(hostfilter)
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/accounts.py
Accounts.upload_file
python
def upload_file(self, service_rec=None, host_service=None, filename=None, pw_data=None, f_type=None, add_to_evidence=True): return self.send.accounts_upload_file(service_rec, host_service, filename, pw_data, f_type, add_to_evidence)
Upload a password file :param service_rec: db.t_services.id :param host_service: db.t_hosts.id :param filename: Filename :param pw_data: Content of file :param f_type: Type of file :param add_to_evidence: True/False to add to t_evidence :return: (True/False, Response Message)
train
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/accounts.py#L86-L99
null
class Accounts(ConnectorJSONRPC): """User accounts""" def list(self, svc_rec=None, hostfilter=None, compromised=False): """ List user accounts :param svc_rec: db.t_services.id :param hostfilter: :param compromised: Show only compromised accounts :return: [acct.t_accounts.f_services_id, acct.t_hosts.f_ipaddr, acct.t_hosts.f_hostname, acct.t_accounts.id, acct.t_accounts.f_username, acct.t_accounts.f_fullname, acct.t_accounts.f_password, acct.t_accounts.f_compromised, acct.t_accounts.f_hash1, acct.t_accounts.f_hash1_type, acct.t_accounts.f_hash2, acct.t_accounts.f_hash2_type, acct.t_accounts.f_source, acct.t_accounts.f_uid, acct.t_accounts.f_gid, acct.t_accounts.f_level, acct.t_accounts.f_domain, acct.t_accounts.f_message, acct.t_accounts.f_lockout, acct.t_accounts.f_duration, acct.t_accounts.f_active, acct.t_accounts.f_description, acct.t_services.f_proto, acct.t_services.f_number, ] """ return self.send.accounts_list(svc_rec, hostfilter, compromised) def add(self, svc_rec=None, records=None): """ Add account data :param svc_rec: db.t_services.id :param records: db.t_accounts field content dictionary :return: (True/False, db.t_accounts.id) """ return self.send.accounts_add(svc_rec, records) def info(self, rec=None): """ Information about an account :param rec: db.t_accounts.id :return: [True/False, hostrec.f_ipaddr, hostrec.f_hostname, svc_rec.f_proto, svc_rec.f_number, acct.id, acct.f_username, acct.f_fullname, acct.f_password, acct.f_compromised, acct.f_hash1, acct.f_hash1_type, acct.f_hash2, acct.f_hash2_type, acct.f_source, acct.f_uid, acct.f_gid, acct.f_level, acct.f_domain, acct.f_message, acct.f_lockout, acct.f_duration, acct.f_active, acct.f_description] """ return self.send.accounts_info(rec) def update(self, rec=None, values=None): """ Update a db.t_accounts record :param rec: db.t_accounts.id :param values: db.t_accounts fields to update :return: (True/False, Message) """ return self.send.accounts_update(rec, values) def list_pw_types(self): """ List the known password types :return: """ return self.send.list_pw_types() def delete(self, rec=None): """ Delete a db.t_accounts record :param rec: [db.t_accounts.id, db.t_accounts.id, ... ] :return: (True/False, Message string) """ return self.send.accounts_del(rec) def index_data(self, hostfilter=None): """ List of IP Addresses and account statistics. :param hostfilter: Hostfilter dict :return: """ return self.send.accounts_index_data(hostfilter)
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
err_exit
python
def err_exit(msg, rc=1): print(msg, file=sys.stderr) sys.exit(rc)
Print msg to stderr and exit with rc.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L195-L199
null
from __future__ import absolute_import from __future__ import print_function import locale try: locale.setlocale(locale.LC_ALL, '') except locale.Error: pass import pkg_resources __version__ = pkg_resources.get_distribution('jarn.viewdoc').version import sys import os import getopt import shutil import webbrowser from os.path import abspath, expanduser, split, isdir, isfile, exists from functools import partial from subprocess import Popen, PIPE from docutils.core import publish_string from .configparser import ConfigParser VERSION = "jarn.viewdoc %s" % __version__ USAGE = "Try 'viewdoc --help' for more information" HELP = """\ Usage: viewdoc [options] [rst-file|egg-dir] Python documentation viewer Options: -s style, --style=style, or --style Select the custom style added to the HTML output. -b browser, --browser=browser Select the browser used for display. -c config-file, --config-file=config-file Use config-file instead of the default ~/.viewdoc. -l, --list-styles List available styles and exit. -h, --help Print this help message and exit. -v, --version Print the version string and exit. rst-file reST file to view. egg-dir Package whose long description to view. Defaults to the current working directory. """ PLAIN = """ <style type="text/css"> body { margin-left: 20%; margin-right: 20%; } </style> """ CLASSIC = """ <link rel="stylesheet" href="http://pypi.python.org/static/styles/styles.css" type="text/css" /> <style type="text/css"> body { margin-left: 20%; margin-right: 20%; font-size: 95%; } a:link { text-decoration: none; color: #0000aa; } a:visited { text-decoration: none; color: #551a8b; } a.reference { border-bottom: 1px dashed #cccccc; } </style> """ PYPI = """ <link rel="stylesheet" href="http://pypi.python.org/static/styles/styles.css" type="text/css" /> <link rel="stylesheet" media="screen" href="http://pypi.python.org/static/css/pygments.css" type="text/css" /> <link rel="stylesheet" href="http://pypi.python.org/static/css/pypi.css" type="text/css" /> <link rel="stylesheet" media="screen" href="http://pypi.python.org/static/css/pypi-screen.css" type="text/css" /> <style type="text/css"> body { margin-left: 20%; margin-right: 20%; font-size: 95%; } a:link { text-decoration: none; color: #0000aa; } a:visited { text-decoration: none; color: #551a8b; } a.reference { border-bottom: 1px dashed #cccccc; } pre.literal-block { background-color: #f0f0f0; } </style> """ SMALL = """ <link rel="stylesheet" href="http://pypi.python.org/static/styles/styles.css" type="text/css" /> <link rel="stylesheet" media="screen" href="http://pypi.python.org/static/css/pygments.css" type="text/css" /> <link rel="stylesheet" href="http://pypi.python.org/static/css/pypi.css" type="text/css" /> <link rel="stylesheet" media="screen" href="http://pypi.python.org/static/css/pypi-screen.css" type="text/css" /> <style type="text/css"> body { margin-left: 20%; margin-right: 20%; font-size: 90%; } a:link { text-decoration: none; color: #0000aa; } a:visited { text-decoration: none; color: #551a8b; } a.reference { border-bottom: 1px dashed #cccccc; } pre.literal-block { background-color: #f0f0f0; } </style> """ SANS = """ <style type="text/css"> body { font-family: Helvetica,Arial,sans-serif; line-height: 1.4; margin-left: 20%; margin-right: 20%; } pre.literal-block { background-color: #f9f9f9; border: 1px solid #d3d3d3; margin-left: 0; padding: 1em; } a { text-decoration: none; color: #0070d0; } a:hover, a:focus { text-decoration: underline; } </style> """ WAREHOUSE = """ <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400italic,600,600italic,700,700italic|Source+Code+Pro:500"> <style type="text/css"> body { font-family: Source Sans Pro,Helvetica,Arial,sans-serif; font-size: 17px; font-weight: 300; line-height: 1.4; color: #464646; background-color: #fdfdfd; } code, kbd, pre, samp, tt { font-family: Source Code Pro,monospace; font-size: 85%; color: #6c6c6c; background-color: #f9f9f9; border: 1px solid #d3d3d3; padding: 0 2px 1px; } a { color: #006dad; text-decoration: none; } a:hover { color: #004d7a; text-decoration: underline; } a:focus { text-decoration: underline; } body { margin-left: 20%; margin-right: 20%; } pre.literal-block { margin-left: 0; padding: 1em; } dl.docutils dt { margin-top: 1em; } dl.docutils dd { margin-bottom: 1em; } </style> """ CONFIG_VERSION = '2.2' DEFAULT_CONFIG = """\ [viewdoc] version = %(CONFIG_VERSION)s style = sans browser = default [styles] plain =%(PLAIN)s sans =%(SANS)s pypi =%(WAREHOUSE)s """ % locals() # Open files as UTF-8 if sys.version_info[0] >= 3: open = partial(open, encoding='utf-8') def msg_exit(msg, rc=0): """Print msg to stdout and exit with rc. """ print(msg) sys.exit(rc) def warn(msg): """Print warning msg to stderr. """ print('WARNING:', msg, file=sys.stderr) class changedir(object): """Change directory.""" def __init__(self, dir): self.old = os.getcwd() self.dir = dir or self.old def __enter__(self): os.chdir(self.dir) def __exit__(self, *ignored): os.chdir(self.old) class Python(object): def __init__(self): self.python = sys.executable self.version_info = sys.version_info def __str__(self): return self.python def is_valid_python(self): return (self.version_info[:2] >= (2, 6)) def check_valid_python(self): if not self.is_valid_python(): err_exit('Python >= 2.6 required') class Process(object): def __init__(self, env=None): self.env = env def popen(self, cmd): """Execute an external command and return (rc, output). """ process = Popen(cmd, shell=True, stdout=PIPE, env=self.env) stdoutdata, stderrdata = process.communicate() return process.returncode, stdoutdata class Setuptools(object): def __init__(self): self.process = Process(env=self.get_env()) self.python = Python() def get_env(self): # Make sure setuptools is found if mkrelease has # been installed with zc.buildout path = [] for name in ('setuptools',): try: dist = pkg_resources.get_distribution(name) except pkg_resources.DistributionNotFound: continue path.append(dist.location) env = os.environ.copy() env['PYTHONPATH'] = ':'.join(path) return env def is_valid_package(self): return isfile('setup.py') def check_valid_package(self): if not self.is_valid_package(): err_exit('No setup.py found in %s' % os.getcwd()) def get_long_description(self): rc, long_description = self.process.popen( '"%s" setup.py --long-description' % self.python) if rc != 0: err_exit('Bad setup.py') if sys.version_info[0] >= 3: try: return long_description.decode('utf-8') except UnicodeDecodeError as e: err_exit('Error reading long description: %s' % (e,)) return long_description class Docutils(object): def read_file(self, infile): """Read a reST file into a string. """ try: with open(infile, 'rt') as file: return file.read() except UnicodeDecodeError as e: err_exit('Error reading %s: %s' % (infile, e)) except (IOError, OSError) as e: err_exit('Error reading %s: %s' % (infile, e.strerror or e)) def write_file(self, html, outfile): """Write an HTML string to a file. """ try: with open(outfile, 'wt') as file: file.write(html) except (IOError, OSError) as e: err_exit('Error writing %s: %s' % (outfile, e.strerror or e)) def convert_string(self, rest): """Convert a reST string to an HTML string. """ try: html = publish_string(rest, writer_name='html') except SystemExit as e: err_exit('HTML conversion failed with error: %s' % e.code) else: if sys.version_info[0] >= 3: return html.decode('utf-8') return html def strip_xml_header(self, html): """Strip any <?xml version="1.0" encoding="utf-8" ?> header. """ if html.startswith('<?xml '): return html.split('\n', 1)[1] return html def apply_styles(self, html, styles): """Insert style information into the HTML string. """ index = html.find('</head>') if index >= 0: return ''.join((html[:index], styles, html[index:])) return html def publish_string(self, rest, outfile, styles=''): """Render a reST string as HTML. """ html = self.convert_string(rest) html = self.strip_xml_header(html) html = self.apply_styles(html, styles) self.write_file(html, outfile) return outfile def publish_file(self, infile, outfile, styles=''): """Render a reST file as HTML. """ rest = self.read_file(infile) return self.publish_string(rest, outfile, styles) class Defaults(object): def __init__(self, config_file): """Read the config file. """ self.filename = config_file parser = ConfigParser(warn) parser.read(self.filename) self.warnings = parser.warnings self.version = parser.getstring('viewdoc', 'version', '') or '1.8' self.browser = parser.getstring('viewdoc', 'browser', '') or 'default' self.known_styles = {} for key, value in parser.items('styles', []): self.known_styles[key] = value.strip() self.default_style = parser.getstring('viewdoc', 'style', '') self.styles = self.known_styles.get(self.default_style, '') if os.environ.get('JARN_RUN') == '1': if parser.warnings: err_exit('viewdoc: exiting') def write(self): """Create the config file. """ warn('Creating ' + self.filename) return self.write_default_config(self.filename) def upgrade(self): """Upgrade the config file. """ warn('Upgrading ' + self.filename) if self.backup_config(self.filename): return self.write_default_config(self.filename) return False def backup_config(self, filename): """Backup the current config file. """ backup_name = filename + '-' + self.version warn('Moving current configuration to ' + backup_name) try: shutil.copy2(filename, backup_name) return True except (IOError, OSError) as e: print('Error copying %s: %s' % (filename, e.strerror or e), file=sys.stderr) return False def write_default_config(self, filename): """Write the default config file. """ try: with open(filename, 'wt') as file: file.write(DEFAULT_CONFIG) return True except (IOError, OSError) as e: print('Error writing %s: %s' % (filename, e.strerror or e), file=sys.stderr) return False class DocumentationViewer(object): def __init__(self, args): """Initialize. """ self.args = args self.set_defaults(expanduser('~/.viewdoc')) def set_defaults(self, config_file): """Set defaults. """ self.defaults = Defaults(config_file) self.python = Python() self.setuptools = Setuptools() self.docutils = Docutils() self.styles = self.defaults.styles self.browser = self.defaults.browser self.list = False def reset_defaults(self, config_file): """Reset defaults. """ if not exists(config_file): err_exit('No such file: %(config_file)s' % locals()) if not isfile(config_file): err_exit('Not a file: %(config_file)s' % locals()) if not os.access(config_file, os.R_OK): err_exit('File cannot be read: %(config_file)s' % locals()) self.set_defaults(config_file) def write_defaults(self): """Create default config file and reload. """ self.defaults.write() self.reset_defaults(self.defaults.filename) def upgrade_defaults(self): """Upgrade config file and reload. """ self.defaults.upgrade() self.reset_defaults(self.defaults.filename) def parse_options(self, args, depth=0): """Parse command line options. """ style_names = tuple(self.defaults.known_styles) style_opts = tuple('--'+x for x in style_names) try: options, remaining_args = getopt.gnu_getopt(args, 'b:c:hls:v', ('help', 'style=', 'version', 'list-styles', 'browser=', 'config-file=') + style_names) except getopt.GetoptError as e: err_exit('viewdoc: %s\n%s' % (e.msg, USAGE)) for name, value in options: if name in ('-s', '--style'): self.styles = self.defaults.known_styles.get(value, '') elif name in style_opts: self.styles = self.defaults.known_styles.get(name[2:], '') elif name in ('-b', '--browser'): self.browser = value elif name in ('-l', '--list-styles'): self.list = True elif name in ('-h', '--help'): msg_exit(HELP) elif name in ('-v', '--version'): msg_exit(VERSION) elif name in ('-c', '--config-file') and depth == 0: self.reset_defaults(expanduser(value)) return self.parse_options(args, depth+1) if len(remaining_args) > 1: err_exit('viewdoc: too many arguments\n%s' % USAGE) if not isfile(self.defaults.filename) and depth == 0: self.write_defaults() return self.parse_options(args, depth+1) if self.defaults.version < CONFIG_VERSION and depth == 0: self.upgrade_defaults() return self.parse_options(args, depth+1) if self.list: self.list_styles() return remaining_args def list_styles(self): """Print available styles and exit. """ known = sorted(self.defaults.known_styles) if not known: err_exit('No styles', 0) for style in known: if style == self.defaults.default_style: print(style, '(default)') else: print(style) sys.exit(0) def render_file(self, filename): """Convert a reST file to HTML. """ dirname, basename = split(filename) with changedir(dirname): infile = abspath(basename) outfile = abspath('.%s.html' % basename) self.docutils.publish_file(infile, outfile, self.styles) return outfile def render_long_description(self, dirname): """Convert a package's long description to HTML. """ with changedir(dirname): self.setuptools.check_valid_package() long_description = self.setuptools.get_long_description() outfile = abspath('.long-description.html') self.docutils.publish_string(long_description, outfile, self.styles) return outfile def open_in_browser(self, outfile): """Open the given HTML file in a browser. """ if self.browser == 'default': webbrowser.open('file://%s' % outfile) else: browser = webbrowser.get(self.browser) browser.open('file://%s' % outfile) def run(self): """Render and display Python package documentation. """ os.environ['JARN_RUN'] = '1' self.python.check_valid_python() args = self.parse_options(self.args) if args: arg = args[0] else: arg = os.curdir if arg: arg = expanduser(arg) if isfile(arg): outfile = self.render_file(arg) elif isdir(arg): outfile = self.render_long_description(arg) else: err_exit('No such file or directory: %s' % arg) self.open_in_browser(outfile) def main(args=None): if args is None: args = sys.argv[1:] try: DocumentationViewer(args).run() except SystemExit as e: return e.code return 0 if __name__ == '__main__': sys.exit(main())
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Process.popen
python
def popen(self, cmd): process = Popen(cmd, shell=True, stdout=PIPE, env=self.env) stdoutdata, stderrdata = process.communicate() return process.returncode, stdoutdata
Execute an external command and return (rc, output).
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L244-L249
null
class Process(object): def __init__(self, env=None): self.env = env
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Docutils.read_file
python
def read_file(self, infile): try: with open(infile, 'rt') as file: return file.read() except UnicodeDecodeError as e: err_exit('Error reading %s: %s' % (infile, e)) except (IOError, OSError) as e: err_exit('Error reading %s: %s' % (infile, e.strerror or e))
Read a reST file into a string.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L294-L303
[ "def err_exit(msg, rc=1):\n \"\"\"Print msg to stderr and exit with rc.\n \"\"\"\n print(msg, file=sys.stderr)\n sys.exit(rc)\n" ]
class Docutils(object): def write_file(self, html, outfile): """Write an HTML string to a file. """ try: with open(outfile, 'wt') as file: file.write(html) except (IOError, OSError) as e: err_exit('Error writing %s: %s' % (outfile, e.strerror or e)) def convert_string(self, rest): """Convert a reST string to an HTML string. """ try: html = publish_string(rest, writer_name='html') except SystemExit as e: err_exit('HTML conversion failed with error: %s' % e.code) else: if sys.version_info[0] >= 3: return html.decode('utf-8') return html def strip_xml_header(self, html): """Strip any <?xml version="1.0" encoding="utf-8" ?> header. """ if html.startswith('<?xml '): return html.split('\n', 1)[1] return html def apply_styles(self, html, styles): """Insert style information into the HTML string. """ index = html.find('</head>') if index >= 0: return ''.join((html[:index], styles, html[index:])) return html def publish_string(self, rest, outfile, styles=''): """Render a reST string as HTML. """ html = self.convert_string(rest) html = self.strip_xml_header(html) html = self.apply_styles(html, styles) self.write_file(html, outfile) return outfile def publish_file(self, infile, outfile, styles=''): """Render a reST file as HTML. """ rest = self.read_file(infile) return self.publish_string(rest, outfile, styles)
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Docutils.write_file
python
def write_file(self, html, outfile): try: with open(outfile, 'wt') as file: file.write(html) except (IOError, OSError) as e: err_exit('Error writing %s: %s' % (outfile, e.strerror or e))
Write an HTML string to a file.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L305-L312
[ "def err_exit(msg, rc=1):\n \"\"\"Print msg to stderr and exit with rc.\n \"\"\"\n print(msg, file=sys.stderr)\n sys.exit(rc)\n" ]
class Docutils(object): def read_file(self, infile): """Read a reST file into a string. """ try: with open(infile, 'rt') as file: return file.read() except UnicodeDecodeError as e: err_exit('Error reading %s: %s' % (infile, e)) except (IOError, OSError) as e: err_exit('Error reading %s: %s' % (infile, e.strerror or e)) def convert_string(self, rest): """Convert a reST string to an HTML string. """ try: html = publish_string(rest, writer_name='html') except SystemExit as e: err_exit('HTML conversion failed with error: %s' % e.code) else: if sys.version_info[0] >= 3: return html.decode('utf-8') return html def strip_xml_header(self, html): """Strip any <?xml version="1.0" encoding="utf-8" ?> header. """ if html.startswith('<?xml '): return html.split('\n', 1)[1] return html def apply_styles(self, html, styles): """Insert style information into the HTML string. """ index = html.find('</head>') if index >= 0: return ''.join((html[:index], styles, html[index:])) return html def publish_string(self, rest, outfile, styles=''): """Render a reST string as HTML. """ html = self.convert_string(rest) html = self.strip_xml_header(html) html = self.apply_styles(html, styles) self.write_file(html, outfile) return outfile def publish_file(self, infile, outfile, styles=''): """Render a reST file as HTML. """ rest = self.read_file(infile) return self.publish_string(rest, outfile, styles)
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Docutils.convert_string
python
def convert_string(self, rest): try: html = publish_string(rest, writer_name='html') except SystemExit as e: err_exit('HTML conversion failed with error: %s' % e.code) else: if sys.version_info[0] >= 3: return html.decode('utf-8') return html
Convert a reST string to an HTML string.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L314-L324
[ "def err_exit(msg, rc=1):\n \"\"\"Print msg to stderr and exit with rc.\n \"\"\"\n print(msg, file=sys.stderr)\n sys.exit(rc)\n" ]
class Docutils(object): def read_file(self, infile): """Read a reST file into a string. """ try: with open(infile, 'rt') as file: return file.read() except UnicodeDecodeError as e: err_exit('Error reading %s: %s' % (infile, e)) except (IOError, OSError) as e: err_exit('Error reading %s: %s' % (infile, e.strerror or e)) def write_file(self, html, outfile): """Write an HTML string to a file. """ try: with open(outfile, 'wt') as file: file.write(html) except (IOError, OSError) as e: err_exit('Error writing %s: %s' % (outfile, e.strerror or e)) def strip_xml_header(self, html): """Strip any <?xml version="1.0" encoding="utf-8" ?> header. """ if html.startswith('<?xml '): return html.split('\n', 1)[1] return html def apply_styles(self, html, styles): """Insert style information into the HTML string. """ index = html.find('</head>') if index >= 0: return ''.join((html[:index], styles, html[index:])) return html def publish_string(self, rest, outfile, styles=''): """Render a reST string as HTML. """ html = self.convert_string(rest) html = self.strip_xml_header(html) html = self.apply_styles(html, styles) self.write_file(html, outfile) return outfile def publish_file(self, infile, outfile, styles=''): """Render a reST file as HTML. """ rest = self.read_file(infile) return self.publish_string(rest, outfile, styles)
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Docutils.apply_styles
python
def apply_styles(self, html, styles): index = html.find('</head>') if index >= 0: return ''.join((html[:index], styles, html[index:])) return html
Insert style information into the HTML string.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L333-L339
null
class Docutils(object): def read_file(self, infile): """Read a reST file into a string. """ try: with open(infile, 'rt') as file: return file.read() except UnicodeDecodeError as e: err_exit('Error reading %s: %s' % (infile, e)) except (IOError, OSError) as e: err_exit('Error reading %s: %s' % (infile, e.strerror or e)) def write_file(self, html, outfile): """Write an HTML string to a file. """ try: with open(outfile, 'wt') as file: file.write(html) except (IOError, OSError) as e: err_exit('Error writing %s: %s' % (outfile, e.strerror or e)) def convert_string(self, rest): """Convert a reST string to an HTML string. """ try: html = publish_string(rest, writer_name='html') except SystemExit as e: err_exit('HTML conversion failed with error: %s' % e.code) else: if sys.version_info[0] >= 3: return html.decode('utf-8') return html def strip_xml_header(self, html): """Strip any <?xml version="1.0" encoding="utf-8" ?> header. """ if html.startswith('<?xml '): return html.split('\n', 1)[1] return html def publish_string(self, rest, outfile, styles=''): """Render a reST string as HTML. """ html = self.convert_string(rest) html = self.strip_xml_header(html) html = self.apply_styles(html, styles) self.write_file(html, outfile) return outfile def publish_file(self, infile, outfile, styles=''): """Render a reST file as HTML. """ rest = self.read_file(infile) return self.publish_string(rest, outfile, styles)
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Docutils.publish_string
python
def publish_string(self, rest, outfile, styles=''): html = self.convert_string(rest) html = self.strip_xml_header(html) html = self.apply_styles(html, styles) self.write_file(html, outfile) return outfile
Render a reST string as HTML.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L341-L348
[ "def write_file(self, html, outfile):\n \"\"\"Write an HTML string to a file.\n \"\"\"\n try:\n with open(outfile, 'wt') as file:\n file.write(html)\n except (IOError, OSError) as e:\n err_exit('Error writing %s: %s' % (outfile, e.strerror or e))\n", "def convert_string(self, rest):\n \"\"\"Convert a reST string to an HTML string.\n \"\"\"\n try:\n html = publish_string(rest, writer_name='html')\n except SystemExit as e:\n err_exit('HTML conversion failed with error: %s' % e.code)\n else:\n if sys.version_info[0] >= 3:\n return html.decode('utf-8')\n return html\n", "def strip_xml_header(self, html):\n \"\"\"Strip any <?xml version=\"1.0\" encoding=\"utf-8\" ?> header.\n \"\"\"\n if html.startswith('<?xml '):\n return html.split('\\n', 1)[1]\n return html\n", "def apply_styles(self, html, styles):\n \"\"\"Insert style information into the HTML string.\n \"\"\"\n index = html.find('</head>')\n if index >= 0:\n return ''.join((html[:index], styles, html[index:]))\n return html\n" ]
class Docutils(object): def read_file(self, infile): """Read a reST file into a string. """ try: with open(infile, 'rt') as file: return file.read() except UnicodeDecodeError as e: err_exit('Error reading %s: %s' % (infile, e)) except (IOError, OSError) as e: err_exit('Error reading %s: %s' % (infile, e.strerror or e)) def write_file(self, html, outfile): """Write an HTML string to a file. """ try: with open(outfile, 'wt') as file: file.write(html) except (IOError, OSError) as e: err_exit('Error writing %s: %s' % (outfile, e.strerror or e)) def convert_string(self, rest): """Convert a reST string to an HTML string. """ try: html = publish_string(rest, writer_name='html') except SystemExit as e: err_exit('HTML conversion failed with error: %s' % e.code) else: if sys.version_info[0] >= 3: return html.decode('utf-8') return html def strip_xml_header(self, html): """Strip any <?xml version="1.0" encoding="utf-8" ?> header. """ if html.startswith('<?xml '): return html.split('\n', 1)[1] return html def apply_styles(self, html, styles): """Insert style information into the HTML string. """ index = html.find('</head>') if index >= 0: return ''.join((html[:index], styles, html[index:])) return html def publish_file(self, infile, outfile, styles=''): """Render a reST file as HTML. """ rest = self.read_file(infile) return self.publish_string(rest, outfile, styles)
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Docutils.publish_file
python
def publish_file(self, infile, outfile, styles=''): rest = self.read_file(infile) return self.publish_string(rest, outfile, styles)
Render a reST file as HTML.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L350-L354
[ "def read_file(self, infile):\n \"\"\"Read a reST file into a string.\n \"\"\"\n try:\n with open(infile, 'rt') as file:\n return file.read()\n except UnicodeDecodeError as e:\n err_exit('Error reading %s: %s' % (infile, e))\n except (IOError, OSError) as e:\n err_exit('Error reading %s: %s' % (infile, e.strerror or e))\n", "def publish_string(self, rest, outfile, styles=''):\n \"\"\"Render a reST string as HTML.\n \"\"\"\n html = self.convert_string(rest)\n html = self.strip_xml_header(html)\n html = self.apply_styles(html, styles)\n self.write_file(html, outfile)\n return outfile\n" ]
class Docutils(object): def read_file(self, infile): """Read a reST file into a string. """ try: with open(infile, 'rt') as file: return file.read() except UnicodeDecodeError as e: err_exit('Error reading %s: %s' % (infile, e)) except (IOError, OSError) as e: err_exit('Error reading %s: %s' % (infile, e.strerror or e)) def write_file(self, html, outfile): """Write an HTML string to a file. """ try: with open(outfile, 'wt') as file: file.write(html) except (IOError, OSError) as e: err_exit('Error writing %s: %s' % (outfile, e.strerror or e)) def convert_string(self, rest): """Convert a reST string to an HTML string. """ try: html = publish_string(rest, writer_name='html') except SystemExit as e: err_exit('HTML conversion failed with error: %s' % e.code) else: if sys.version_info[0] >= 3: return html.decode('utf-8') return html def strip_xml_header(self, html): """Strip any <?xml version="1.0" encoding="utf-8" ?> header. """ if html.startswith('<?xml '): return html.split('\n', 1)[1] return html def apply_styles(self, html, styles): """Insert style information into the HTML string. """ index = html.find('</head>') if index >= 0: return ''.join((html[:index], styles, html[index:])) return html def publish_string(self, rest, outfile, styles=''): """Render a reST string as HTML. """ html = self.convert_string(rest) html = self.strip_xml_header(html) html = self.apply_styles(html, styles) self.write_file(html, outfile) return outfile
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Defaults.upgrade
python
def upgrade(self): warn('Upgrading ' + self.filename) if self.backup_config(self.filename): return self.write_default_config(self.filename) return False
Upgrade the config file.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L389-L395
[ "def warn(msg):\n \"\"\"Print warning msg to stderr.\n \"\"\"\n print('WARNING:', msg, file=sys.stderr)\n", "def backup_config(self, filename):\n \"\"\"Backup the current config file.\n \"\"\"\n backup_name = filename + '-' + self.version\n warn('Moving current configuration to ' + backup_name)\n try:\n shutil.copy2(filename, backup_name)\n return True\n except (IOError, OSError) as e:\n print('Error copying %s: %s' % (filename, e.strerror or e), file=sys.stderr)\n return False\n" ]
class Defaults(object): def __init__(self, config_file): """Read the config file. """ self.filename = config_file parser = ConfigParser(warn) parser.read(self.filename) self.warnings = parser.warnings self.version = parser.getstring('viewdoc', 'version', '') or '1.8' self.browser = parser.getstring('viewdoc', 'browser', '') or 'default' self.known_styles = {} for key, value in parser.items('styles', []): self.known_styles[key] = value.strip() self.default_style = parser.getstring('viewdoc', 'style', '') self.styles = self.known_styles.get(self.default_style, '') if os.environ.get('JARN_RUN') == '1': if parser.warnings: err_exit('viewdoc: exiting') def write(self): """Create the config file. """ warn('Creating ' + self.filename) return self.write_default_config(self.filename) def backup_config(self, filename): """Backup the current config file. """ backup_name = filename + '-' + self.version warn('Moving current configuration to ' + backup_name) try: shutil.copy2(filename, backup_name) return True except (IOError, OSError) as e: print('Error copying %s: %s' % (filename, e.strerror or e), file=sys.stderr) return False def write_default_config(self, filename): """Write the default config file. """ try: with open(filename, 'wt') as file: file.write(DEFAULT_CONFIG) return True except (IOError, OSError) as e: print('Error writing %s: %s' % (filename, e.strerror or e), file=sys.stderr) return False
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Defaults.backup_config
python
def backup_config(self, filename): backup_name = filename + '-' + self.version warn('Moving current configuration to ' + backup_name) try: shutil.copy2(filename, backup_name) return True except (IOError, OSError) as e: print('Error copying %s: %s' % (filename, e.strerror or e), file=sys.stderr) return False
Backup the current config file.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L397-L407
[ "def warn(msg):\n \"\"\"Print warning msg to stderr.\n \"\"\"\n print('WARNING:', msg, file=sys.stderr)\n" ]
class Defaults(object): def __init__(self, config_file): """Read the config file. """ self.filename = config_file parser = ConfigParser(warn) parser.read(self.filename) self.warnings = parser.warnings self.version = parser.getstring('viewdoc', 'version', '') or '1.8' self.browser = parser.getstring('viewdoc', 'browser', '') or 'default' self.known_styles = {} for key, value in parser.items('styles', []): self.known_styles[key] = value.strip() self.default_style = parser.getstring('viewdoc', 'style', '') self.styles = self.known_styles.get(self.default_style, '') if os.environ.get('JARN_RUN') == '1': if parser.warnings: err_exit('viewdoc: exiting') def write(self): """Create the config file. """ warn('Creating ' + self.filename) return self.write_default_config(self.filename) def upgrade(self): """Upgrade the config file. """ warn('Upgrading ' + self.filename) if self.backup_config(self.filename): return self.write_default_config(self.filename) return False def write_default_config(self, filename): """Write the default config file. """ try: with open(filename, 'wt') as file: file.write(DEFAULT_CONFIG) return True except (IOError, OSError) as e: print('Error writing %s: %s' % (filename, e.strerror or e), file=sys.stderr) return False
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Defaults.write_default_config
python
def write_default_config(self, filename): try: with open(filename, 'wt') as file: file.write(DEFAULT_CONFIG) return True except (IOError, OSError) as e: print('Error writing %s: %s' % (filename, e.strerror or e), file=sys.stderr) return False
Write the default config file.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L409-L418
null
class Defaults(object): def __init__(self, config_file): """Read the config file. """ self.filename = config_file parser = ConfigParser(warn) parser.read(self.filename) self.warnings = parser.warnings self.version = parser.getstring('viewdoc', 'version', '') or '1.8' self.browser = parser.getstring('viewdoc', 'browser', '') or 'default' self.known_styles = {} for key, value in parser.items('styles', []): self.known_styles[key] = value.strip() self.default_style = parser.getstring('viewdoc', 'style', '') self.styles = self.known_styles.get(self.default_style, '') if os.environ.get('JARN_RUN') == '1': if parser.warnings: err_exit('viewdoc: exiting') def write(self): """Create the config file. """ warn('Creating ' + self.filename) return self.write_default_config(self.filename) def upgrade(self): """Upgrade the config file. """ warn('Upgrading ' + self.filename) if self.backup_config(self.filename): return self.write_default_config(self.filename) return False def backup_config(self, filename): """Backup the current config file. """ backup_name = filename + '-' + self.version warn('Moving current configuration to ' + backup_name) try: shutil.copy2(filename, backup_name) return True except (IOError, OSError) as e: print('Error copying %s: %s' % (filename, e.strerror or e), file=sys.stderr) return False
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.set_defaults
python
def set_defaults(self, config_file): self.defaults = Defaults(config_file) self.python = Python() self.setuptools = Setuptools() self.docutils = Docutils() self.styles = self.defaults.styles self.browser = self.defaults.browser self.list = False
Set defaults.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L429-L438
null
class DocumentationViewer(object): def __init__(self, args): """Initialize. """ self.args = args self.set_defaults(expanduser('~/.viewdoc')) def reset_defaults(self, config_file): """Reset defaults. """ if not exists(config_file): err_exit('No such file: %(config_file)s' % locals()) if not isfile(config_file): err_exit('Not a file: %(config_file)s' % locals()) if not os.access(config_file, os.R_OK): err_exit('File cannot be read: %(config_file)s' % locals()) self.set_defaults(config_file) def write_defaults(self): """Create default config file and reload. """ self.defaults.write() self.reset_defaults(self.defaults.filename) def upgrade_defaults(self): """Upgrade config file and reload. """ self.defaults.upgrade() self.reset_defaults(self.defaults.filename) def parse_options(self, args, depth=0): """Parse command line options. """ style_names = tuple(self.defaults.known_styles) style_opts = tuple('--'+x for x in style_names) try: options, remaining_args = getopt.gnu_getopt(args, 'b:c:hls:v', ('help', 'style=', 'version', 'list-styles', 'browser=', 'config-file=') + style_names) except getopt.GetoptError as e: err_exit('viewdoc: %s\n%s' % (e.msg, USAGE)) for name, value in options: if name in ('-s', '--style'): self.styles = self.defaults.known_styles.get(value, '') elif name in style_opts: self.styles = self.defaults.known_styles.get(name[2:], '') elif name in ('-b', '--browser'): self.browser = value elif name in ('-l', '--list-styles'): self.list = True elif name in ('-h', '--help'): msg_exit(HELP) elif name in ('-v', '--version'): msg_exit(VERSION) elif name in ('-c', '--config-file') and depth == 0: self.reset_defaults(expanduser(value)) return self.parse_options(args, depth+1) if len(remaining_args) > 1: err_exit('viewdoc: too many arguments\n%s' % USAGE) if not isfile(self.defaults.filename) and depth == 0: self.write_defaults() return self.parse_options(args, depth+1) if self.defaults.version < CONFIG_VERSION and depth == 0: self.upgrade_defaults() return self.parse_options(args, depth+1) if self.list: self.list_styles() return remaining_args def list_styles(self): """Print available styles and exit. """ known = sorted(self.defaults.known_styles) if not known: err_exit('No styles', 0) for style in known: if style == self.defaults.default_style: print(style, '(default)') else: print(style) sys.exit(0) def render_file(self, filename): """Convert a reST file to HTML. """ dirname, basename = split(filename) with changedir(dirname): infile = abspath(basename) outfile = abspath('.%s.html' % basename) self.docutils.publish_file(infile, outfile, self.styles) return outfile def render_long_description(self, dirname): """Convert a package's long description to HTML. """ with changedir(dirname): self.setuptools.check_valid_package() long_description = self.setuptools.get_long_description() outfile = abspath('.long-description.html') self.docutils.publish_string(long_description, outfile, self.styles) return outfile def open_in_browser(self, outfile): """Open the given HTML file in a browser. """ if self.browser == 'default': webbrowser.open('file://%s' % outfile) else: browser = webbrowser.get(self.browser) browser.open('file://%s' % outfile) def run(self): """Render and display Python package documentation. """ os.environ['JARN_RUN'] = '1' self.python.check_valid_python() args = self.parse_options(self.args) if args: arg = args[0] else: arg = os.curdir if arg: arg = expanduser(arg) if isfile(arg): outfile = self.render_file(arg) elif isdir(arg): outfile = self.render_long_description(arg) else: err_exit('No such file or directory: %s' % arg) self.open_in_browser(outfile)
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.reset_defaults
python
def reset_defaults(self, config_file): if not exists(config_file): err_exit('No such file: %(config_file)s' % locals()) if not isfile(config_file): err_exit('Not a file: %(config_file)s' % locals()) if not os.access(config_file, os.R_OK): err_exit('File cannot be read: %(config_file)s' % locals()) self.set_defaults(config_file)
Reset defaults.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L440-L449
[ "def err_exit(msg, rc=1):\n \"\"\"Print msg to stderr and exit with rc.\n \"\"\"\n print(msg, file=sys.stderr)\n sys.exit(rc)\n", "def set_defaults(self, config_file):\n \"\"\"Set defaults.\n \"\"\"\n self.defaults = Defaults(config_file)\n self.python = Python()\n self.setuptools = Setuptools()\n self.docutils = Docutils()\n self.styles = self.defaults.styles\n self.browser = self.defaults.browser\n self.list = False\n" ]
class DocumentationViewer(object): def __init__(self, args): """Initialize. """ self.args = args self.set_defaults(expanduser('~/.viewdoc')) def set_defaults(self, config_file): """Set defaults. """ self.defaults = Defaults(config_file) self.python = Python() self.setuptools = Setuptools() self.docutils = Docutils() self.styles = self.defaults.styles self.browser = self.defaults.browser self.list = False def write_defaults(self): """Create default config file and reload. """ self.defaults.write() self.reset_defaults(self.defaults.filename) def upgrade_defaults(self): """Upgrade config file and reload. """ self.defaults.upgrade() self.reset_defaults(self.defaults.filename) def parse_options(self, args, depth=0): """Parse command line options. """ style_names = tuple(self.defaults.known_styles) style_opts = tuple('--'+x for x in style_names) try: options, remaining_args = getopt.gnu_getopt(args, 'b:c:hls:v', ('help', 'style=', 'version', 'list-styles', 'browser=', 'config-file=') + style_names) except getopt.GetoptError as e: err_exit('viewdoc: %s\n%s' % (e.msg, USAGE)) for name, value in options: if name in ('-s', '--style'): self.styles = self.defaults.known_styles.get(value, '') elif name in style_opts: self.styles = self.defaults.known_styles.get(name[2:], '') elif name in ('-b', '--browser'): self.browser = value elif name in ('-l', '--list-styles'): self.list = True elif name in ('-h', '--help'): msg_exit(HELP) elif name in ('-v', '--version'): msg_exit(VERSION) elif name in ('-c', '--config-file') and depth == 0: self.reset_defaults(expanduser(value)) return self.parse_options(args, depth+1) if len(remaining_args) > 1: err_exit('viewdoc: too many arguments\n%s' % USAGE) if not isfile(self.defaults.filename) and depth == 0: self.write_defaults() return self.parse_options(args, depth+1) if self.defaults.version < CONFIG_VERSION and depth == 0: self.upgrade_defaults() return self.parse_options(args, depth+1) if self.list: self.list_styles() return remaining_args def list_styles(self): """Print available styles and exit. """ known = sorted(self.defaults.known_styles) if not known: err_exit('No styles', 0) for style in known: if style == self.defaults.default_style: print(style, '(default)') else: print(style) sys.exit(0) def render_file(self, filename): """Convert a reST file to HTML. """ dirname, basename = split(filename) with changedir(dirname): infile = abspath(basename) outfile = abspath('.%s.html' % basename) self.docutils.publish_file(infile, outfile, self.styles) return outfile def render_long_description(self, dirname): """Convert a package's long description to HTML. """ with changedir(dirname): self.setuptools.check_valid_package() long_description = self.setuptools.get_long_description() outfile = abspath('.long-description.html') self.docutils.publish_string(long_description, outfile, self.styles) return outfile def open_in_browser(self, outfile): """Open the given HTML file in a browser. """ if self.browser == 'default': webbrowser.open('file://%s' % outfile) else: browser = webbrowser.get(self.browser) browser.open('file://%s' % outfile) def run(self): """Render and display Python package documentation. """ os.environ['JARN_RUN'] = '1' self.python.check_valid_python() args = self.parse_options(self.args) if args: arg = args[0] else: arg = os.curdir if arg: arg = expanduser(arg) if isfile(arg): outfile = self.render_file(arg) elif isdir(arg): outfile = self.render_long_description(arg) else: err_exit('No such file or directory: %s' % arg) self.open_in_browser(outfile)
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.write_defaults
python
def write_defaults(self): self.defaults.write() self.reset_defaults(self.defaults.filename)
Create default config file and reload.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L451-L455
[ "def reset_defaults(self, config_file):\n \"\"\"Reset defaults.\n \"\"\"\n if not exists(config_file):\n err_exit('No such file: %(config_file)s' % locals())\n if not isfile(config_file):\n err_exit('Not a file: %(config_file)s' % locals())\n if not os.access(config_file, os.R_OK):\n err_exit('File cannot be read: %(config_file)s' % locals())\n self.set_defaults(config_file)\n" ]
class DocumentationViewer(object): def __init__(self, args): """Initialize. """ self.args = args self.set_defaults(expanduser('~/.viewdoc')) def set_defaults(self, config_file): """Set defaults. """ self.defaults = Defaults(config_file) self.python = Python() self.setuptools = Setuptools() self.docutils = Docutils() self.styles = self.defaults.styles self.browser = self.defaults.browser self.list = False def reset_defaults(self, config_file): """Reset defaults. """ if not exists(config_file): err_exit('No such file: %(config_file)s' % locals()) if not isfile(config_file): err_exit('Not a file: %(config_file)s' % locals()) if not os.access(config_file, os.R_OK): err_exit('File cannot be read: %(config_file)s' % locals()) self.set_defaults(config_file) def upgrade_defaults(self): """Upgrade config file and reload. """ self.defaults.upgrade() self.reset_defaults(self.defaults.filename) def parse_options(self, args, depth=0): """Parse command line options. """ style_names = tuple(self.defaults.known_styles) style_opts = tuple('--'+x for x in style_names) try: options, remaining_args = getopt.gnu_getopt(args, 'b:c:hls:v', ('help', 'style=', 'version', 'list-styles', 'browser=', 'config-file=') + style_names) except getopt.GetoptError as e: err_exit('viewdoc: %s\n%s' % (e.msg, USAGE)) for name, value in options: if name in ('-s', '--style'): self.styles = self.defaults.known_styles.get(value, '') elif name in style_opts: self.styles = self.defaults.known_styles.get(name[2:], '') elif name in ('-b', '--browser'): self.browser = value elif name in ('-l', '--list-styles'): self.list = True elif name in ('-h', '--help'): msg_exit(HELP) elif name in ('-v', '--version'): msg_exit(VERSION) elif name in ('-c', '--config-file') and depth == 0: self.reset_defaults(expanduser(value)) return self.parse_options(args, depth+1) if len(remaining_args) > 1: err_exit('viewdoc: too many arguments\n%s' % USAGE) if not isfile(self.defaults.filename) and depth == 0: self.write_defaults() return self.parse_options(args, depth+1) if self.defaults.version < CONFIG_VERSION and depth == 0: self.upgrade_defaults() return self.parse_options(args, depth+1) if self.list: self.list_styles() return remaining_args def list_styles(self): """Print available styles and exit. """ known = sorted(self.defaults.known_styles) if not known: err_exit('No styles', 0) for style in known: if style == self.defaults.default_style: print(style, '(default)') else: print(style) sys.exit(0) def render_file(self, filename): """Convert a reST file to HTML. """ dirname, basename = split(filename) with changedir(dirname): infile = abspath(basename) outfile = abspath('.%s.html' % basename) self.docutils.publish_file(infile, outfile, self.styles) return outfile def render_long_description(self, dirname): """Convert a package's long description to HTML. """ with changedir(dirname): self.setuptools.check_valid_package() long_description = self.setuptools.get_long_description() outfile = abspath('.long-description.html') self.docutils.publish_string(long_description, outfile, self.styles) return outfile def open_in_browser(self, outfile): """Open the given HTML file in a browser. """ if self.browser == 'default': webbrowser.open('file://%s' % outfile) else: browser = webbrowser.get(self.browser) browser.open('file://%s' % outfile) def run(self): """Render and display Python package documentation. """ os.environ['JARN_RUN'] = '1' self.python.check_valid_python() args = self.parse_options(self.args) if args: arg = args[0] else: arg = os.curdir if arg: arg = expanduser(arg) if isfile(arg): outfile = self.render_file(arg) elif isdir(arg): outfile = self.render_long_description(arg) else: err_exit('No such file or directory: %s' % arg) self.open_in_browser(outfile)
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.upgrade_defaults
python
def upgrade_defaults(self): self.defaults.upgrade() self.reset_defaults(self.defaults.filename)
Upgrade config file and reload.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L457-L461
[ "def reset_defaults(self, config_file):\n \"\"\"Reset defaults.\n \"\"\"\n if not exists(config_file):\n err_exit('No such file: %(config_file)s' % locals())\n if not isfile(config_file):\n err_exit('Not a file: %(config_file)s' % locals())\n if not os.access(config_file, os.R_OK):\n err_exit('File cannot be read: %(config_file)s' % locals())\n self.set_defaults(config_file)\n" ]
class DocumentationViewer(object): def __init__(self, args): """Initialize. """ self.args = args self.set_defaults(expanduser('~/.viewdoc')) def set_defaults(self, config_file): """Set defaults. """ self.defaults = Defaults(config_file) self.python = Python() self.setuptools = Setuptools() self.docutils = Docutils() self.styles = self.defaults.styles self.browser = self.defaults.browser self.list = False def reset_defaults(self, config_file): """Reset defaults. """ if not exists(config_file): err_exit('No such file: %(config_file)s' % locals()) if not isfile(config_file): err_exit('Not a file: %(config_file)s' % locals()) if not os.access(config_file, os.R_OK): err_exit('File cannot be read: %(config_file)s' % locals()) self.set_defaults(config_file) def write_defaults(self): """Create default config file and reload. """ self.defaults.write() self.reset_defaults(self.defaults.filename) def parse_options(self, args, depth=0): """Parse command line options. """ style_names = tuple(self.defaults.known_styles) style_opts = tuple('--'+x for x in style_names) try: options, remaining_args = getopt.gnu_getopt(args, 'b:c:hls:v', ('help', 'style=', 'version', 'list-styles', 'browser=', 'config-file=') + style_names) except getopt.GetoptError as e: err_exit('viewdoc: %s\n%s' % (e.msg, USAGE)) for name, value in options: if name in ('-s', '--style'): self.styles = self.defaults.known_styles.get(value, '') elif name in style_opts: self.styles = self.defaults.known_styles.get(name[2:], '') elif name in ('-b', '--browser'): self.browser = value elif name in ('-l', '--list-styles'): self.list = True elif name in ('-h', '--help'): msg_exit(HELP) elif name in ('-v', '--version'): msg_exit(VERSION) elif name in ('-c', '--config-file') and depth == 0: self.reset_defaults(expanduser(value)) return self.parse_options(args, depth+1) if len(remaining_args) > 1: err_exit('viewdoc: too many arguments\n%s' % USAGE) if not isfile(self.defaults.filename) and depth == 0: self.write_defaults() return self.parse_options(args, depth+1) if self.defaults.version < CONFIG_VERSION and depth == 0: self.upgrade_defaults() return self.parse_options(args, depth+1) if self.list: self.list_styles() return remaining_args def list_styles(self): """Print available styles and exit. """ known = sorted(self.defaults.known_styles) if not known: err_exit('No styles', 0) for style in known: if style == self.defaults.default_style: print(style, '(default)') else: print(style) sys.exit(0) def render_file(self, filename): """Convert a reST file to HTML. """ dirname, basename = split(filename) with changedir(dirname): infile = abspath(basename) outfile = abspath('.%s.html' % basename) self.docutils.publish_file(infile, outfile, self.styles) return outfile def render_long_description(self, dirname): """Convert a package's long description to HTML. """ with changedir(dirname): self.setuptools.check_valid_package() long_description = self.setuptools.get_long_description() outfile = abspath('.long-description.html') self.docutils.publish_string(long_description, outfile, self.styles) return outfile def open_in_browser(self, outfile): """Open the given HTML file in a browser. """ if self.browser == 'default': webbrowser.open('file://%s' % outfile) else: browser = webbrowser.get(self.browser) browser.open('file://%s' % outfile) def run(self): """Render and display Python package documentation. """ os.environ['JARN_RUN'] = '1' self.python.check_valid_python() args = self.parse_options(self.args) if args: arg = args[0] else: arg = os.curdir if arg: arg = expanduser(arg) if isfile(arg): outfile = self.render_file(arg) elif isdir(arg): outfile = self.render_long_description(arg) else: err_exit('No such file or directory: %s' % arg) self.open_in_browser(outfile)
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.parse_options
python
def parse_options(self, args, depth=0): style_names = tuple(self.defaults.known_styles) style_opts = tuple('--'+x for x in style_names) try: options, remaining_args = getopt.gnu_getopt(args, 'b:c:hls:v', ('help', 'style=', 'version', 'list-styles', 'browser=', 'config-file=') + style_names) except getopt.GetoptError as e: err_exit('viewdoc: %s\n%s' % (e.msg, USAGE)) for name, value in options: if name in ('-s', '--style'): self.styles = self.defaults.known_styles.get(value, '') elif name in style_opts: self.styles = self.defaults.known_styles.get(name[2:], '') elif name in ('-b', '--browser'): self.browser = value elif name in ('-l', '--list-styles'): self.list = True elif name in ('-h', '--help'): msg_exit(HELP) elif name in ('-v', '--version'): msg_exit(VERSION) elif name in ('-c', '--config-file') and depth == 0: self.reset_defaults(expanduser(value)) return self.parse_options(args, depth+1) if len(remaining_args) > 1: err_exit('viewdoc: too many arguments\n%s' % USAGE) if not isfile(self.defaults.filename) and depth == 0: self.write_defaults() return self.parse_options(args, depth+1) if self.defaults.version < CONFIG_VERSION and depth == 0: self.upgrade_defaults() return self.parse_options(args, depth+1) if self.list: self.list_styles() return remaining_args
Parse command line options.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L463-L507
[ "def msg_exit(msg, rc=0):\n \"\"\"Print msg to stdout and exit with rc.\n \"\"\"\n print(msg)\n sys.exit(rc)\n", "def err_exit(msg, rc=1):\n \"\"\"Print msg to stderr and exit with rc.\n \"\"\"\n print(msg, file=sys.stderr)\n sys.exit(rc)\n", "def reset_defaults(self, config_file):\n \"\"\"Reset defaults.\n \"\"\"\n if not exists(config_file):\n err_exit('No such file: %(config_file)s' % locals())\n if not isfile(config_file):\n err_exit('Not a file: %(config_file)s' % locals())\n if not os.access(config_file, os.R_OK):\n err_exit('File cannot be read: %(config_file)s' % locals())\n self.set_defaults(config_file)\n", "def upgrade_defaults(self):\n \"\"\"Upgrade config file and reload.\n \"\"\"\n self.defaults.upgrade()\n self.reset_defaults(self.defaults.filename)\n", "def parse_options(self, args, depth=0):\n \"\"\"Parse command line options.\n \"\"\"\n style_names = tuple(self.defaults.known_styles)\n style_opts = tuple('--'+x for x in style_names)\n\n try:\n options, remaining_args = getopt.gnu_getopt(args, 'b:c:hls:v',\n ('help', 'style=', 'version', 'list-styles', 'browser=',\n 'config-file=') + style_names)\n except getopt.GetoptError as e:\n err_exit('viewdoc: %s\\n%s' % (e.msg, USAGE))\n\n for name, value in options:\n if name in ('-s', '--style'):\n self.styles = self.defaults.known_styles.get(value, '')\n elif name in style_opts:\n self.styles = self.defaults.known_styles.get(name[2:], '')\n elif name in ('-b', '--browser'):\n self.browser = value\n elif name in ('-l', '--list-styles'):\n self.list = True\n elif name in ('-h', '--help'):\n msg_exit(HELP)\n elif name in ('-v', '--version'):\n msg_exit(VERSION)\n elif name in ('-c', '--config-file') and depth == 0:\n self.reset_defaults(expanduser(value))\n return self.parse_options(args, depth+1)\n\n if len(remaining_args) > 1:\n err_exit('viewdoc: too many arguments\\n%s' % USAGE)\n\n if not isfile(self.defaults.filename) and depth == 0:\n self.write_defaults()\n return self.parse_options(args, depth+1)\n\n if self.defaults.version < CONFIG_VERSION and depth == 0:\n self.upgrade_defaults()\n return self.parse_options(args, depth+1)\n\n if self.list:\n self.list_styles()\n\n return remaining_args\n", "def list_styles(self):\n \"\"\"Print available styles and exit.\n \"\"\"\n known = sorted(self.defaults.known_styles)\n if not known:\n err_exit('No styles', 0)\n for style in known:\n if style == self.defaults.default_style:\n print(style, '(default)')\n else:\n print(style)\n sys.exit(0)\n" ]
class DocumentationViewer(object): def __init__(self, args): """Initialize. """ self.args = args self.set_defaults(expanduser('~/.viewdoc')) def set_defaults(self, config_file): """Set defaults. """ self.defaults = Defaults(config_file) self.python = Python() self.setuptools = Setuptools() self.docutils = Docutils() self.styles = self.defaults.styles self.browser = self.defaults.browser self.list = False def reset_defaults(self, config_file): """Reset defaults. """ if not exists(config_file): err_exit('No such file: %(config_file)s' % locals()) if not isfile(config_file): err_exit('Not a file: %(config_file)s' % locals()) if not os.access(config_file, os.R_OK): err_exit('File cannot be read: %(config_file)s' % locals()) self.set_defaults(config_file) def write_defaults(self): """Create default config file and reload. """ self.defaults.write() self.reset_defaults(self.defaults.filename) def upgrade_defaults(self): """Upgrade config file and reload. """ self.defaults.upgrade() self.reset_defaults(self.defaults.filename) def list_styles(self): """Print available styles and exit. """ known = sorted(self.defaults.known_styles) if not known: err_exit('No styles', 0) for style in known: if style == self.defaults.default_style: print(style, '(default)') else: print(style) sys.exit(0) def render_file(self, filename): """Convert a reST file to HTML. """ dirname, basename = split(filename) with changedir(dirname): infile = abspath(basename) outfile = abspath('.%s.html' % basename) self.docutils.publish_file(infile, outfile, self.styles) return outfile def render_long_description(self, dirname): """Convert a package's long description to HTML. """ with changedir(dirname): self.setuptools.check_valid_package() long_description = self.setuptools.get_long_description() outfile = abspath('.long-description.html') self.docutils.publish_string(long_description, outfile, self.styles) return outfile def open_in_browser(self, outfile): """Open the given HTML file in a browser. """ if self.browser == 'default': webbrowser.open('file://%s' % outfile) else: browser = webbrowser.get(self.browser) browser.open('file://%s' % outfile) def run(self): """Render and display Python package documentation. """ os.environ['JARN_RUN'] = '1' self.python.check_valid_python() args = self.parse_options(self.args) if args: arg = args[0] else: arg = os.curdir if arg: arg = expanduser(arg) if isfile(arg): outfile = self.render_file(arg) elif isdir(arg): outfile = self.render_long_description(arg) else: err_exit('No such file or directory: %s' % arg) self.open_in_browser(outfile)
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.list_styles
python
def list_styles(self): known = sorted(self.defaults.known_styles) if not known: err_exit('No styles', 0) for style in known: if style == self.defaults.default_style: print(style, '(default)') else: print(style) sys.exit(0)
Print available styles and exit.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L509-L520
[ "def err_exit(msg, rc=1):\n \"\"\"Print msg to stderr and exit with rc.\n \"\"\"\n print(msg, file=sys.stderr)\n sys.exit(rc)\n" ]
class DocumentationViewer(object): def __init__(self, args): """Initialize. """ self.args = args self.set_defaults(expanduser('~/.viewdoc')) def set_defaults(self, config_file): """Set defaults. """ self.defaults = Defaults(config_file) self.python = Python() self.setuptools = Setuptools() self.docutils = Docutils() self.styles = self.defaults.styles self.browser = self.defaults.browser self.list = False def reset_defaults(self, config_file): """Reset defaults. """ if not exists(config_file): err_exit('No such file: %(config_file)s' % locals()) if not isfile(config_file): err_exit('Not a file: %(config_file)s' % locals()) if not os.access(config_file, os.R_OK): err_exit('File cannot be read: %(config_file)s' % locals()) self.set_defaults(config_file) def write_defaults(self): """Create default config file and reload. """ self.defaults.write() self.reset_defaults(self.defaults.filename) def upgrade_defaults(self): """Upgrade config file and reload. """ self.defaults.upgrade() self.reset_defaults(self.defaults.filename) def parse_options(self, args, depth=0): """Parse command line options. """ style_names = tuple(self.defaults.known_styles) style_opts = tuple('--'+x for x in style_names) try: options, remaining_args = getopt.gnu_getopt(args, 'b:c:hls:v', ('help', 'style=', 'version', 'list-styles', 'browser=', 'config-file=') + style_names) except getopt.GetoptError as e: err_exit('viewdoc: %s\n%s' % (e.msg, USAGE)) for name, value in options: if name in ('-s', '--style'): self.styles = self.defaults.known_styles.get(value, '') elif name in style_opts: self.styles = self.defaults.known_styles.get(name[2:], '') elif name in ('-b', '--browser'): self.browser = value elif name in ('-l', '--list-styles'): self.list = True elif name in ('-h', '--help'): msg_exit(HELP) elif name in ('-v', '--version'): msg_exit(VERSION) elif name in ('-c', '--config-file') and depth == 0: self.reset_defaults(expanduser(value)) return self.parse_options(args, depth+1) if len(remaining_args) > 1: err_exit('viewdoc: too many arguments\n%s' % USAGE) if not isfile(self.defaults.filename) and depth == 0: self.write_defaults() return self.parse_options(args, depth+1) if self.defaults.version < CONFIG_VERSION and depth == 0: self.upgrade_defaults() return self.parse_options(args, depth+1) if self.list: self.list_styles() return remaining_args def render_file(self, filename): """Convert a reST file to HTML. """ dirname, basename = split(filename) with changedir(dirname): infile = abspath(basename) outfile = abspath('.%s.html' % basename) self.docutils.publish_file(infile, outfile, self.styles) return outfile def render_long_description(self, dirname): """Convert a package's long description to HTML. """ with changedir(dirname): self.setuptools.check_valid_package() long_description = self.setuptools.get_long_description() outfile = abspath('.long-description.html') self.docutils.publish_string(long_description, outfile, self.styles) return outfile def open_in_browser(self, outfile): """Open the given HTML file in a browser. """ if self.browser == 'default': webbrowser.open('file://%s' % outfile) else: browser = webbrowser.get(self.browser) browser.open('file://%s' % outfile) def run(self): """Render and display Python package documentation. """ os.environ['JARN_RUN'] = '1' self.python.check_valid_python() args = self.parse_options(self.args) if args: arg = args[0] else: arg = os.curdir if arg: arg = expanduser(arg) if isfile(arg): outfile = self.render_file(arg) elif isdir(arg): outfile = self.render_long_description(arg) else: err_exit('No such file or directory: %s' % arg) self.open_in_browser(outfile)
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.render_file
python
def render_file(self, filename): dirname, basename = split(filename) with changedir(dirname): infile = abspath(basename) outfile = abspath('.%s.html' % basename) self.docutils.publish_file(infile, outfile, self.styles) return outfile
Convert a reST file to HTML.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L522-L530
null
class DocumentationViewer(object): def __init__(self, args): """Initialize. """ self.args = args self.set_defaults(expanduser('~/.viewdoc')) def set_defaults(self, config_file): """Set defaults. """ self.defaults = Defaults(config_file) self.python = Python() self.setuptools = Setuptools() self.docutils = Docutils() self.styles = self.defaults.styles self.browser = self.defaults.browser self.list = False def reset_defaults(self, config_file): """Reset defaults. """ if not exists(config_file): err_exit('No such file: %(config_file)s' % locals()) if not isfile(config_file): err_exit('Not a file: %(config_file)s' % locals()) if not os.access(config_file, os.R_OK): err_exit('File cannot be read: %(config_file)s' % locals()) self.set_defaults(config_file) def write_defaults(self): """Create default config file and reload. """ self.defaults.write() self.reset_defaults(self.defaults.filename) def upgrade_defaults(self): """Upgrade config file and reload. """ self.defaults.upgrade() self.reset_defaults(self.defaults.filename) def parse_options(self, args, depth=0): """Parse command line options. """ style_names = tuple(self.defaults.known_styles) style_opts = tuple('--'+x for x in style_names) try: options, remaining_args = getopt.gnu_getopt(args, 'b:c:hls:v', ('help', 'style=', 'version', 'list-styles', 'browser=', 'config-file=') + style_names) except getopt.GetoptError as e: err_exit('viewdoc: %s\n%s' % (e.msg, USAGE)) for name, value in options: if name in ('-s', '--style'): self.styles = self.defaults.known_styles.get(value, '') elif name in style_opts: self.styles = self.defaults.known_styles.get(name[2:], '') elif name in ('-b', '--browser'): self.browser = value elif name in ('-l', '--list-styles'): self.list = True elif name in ('-h', '--help'): msg_exit(HELP) elif name in ('-v', '--version'): msg_exit(VERSION) elif name in ('-c', '--config-file') and depth == 0: self.reset_defaults(expanduser(value)) return self.parse_options(args, depth+1) if len(remaining_args) > 1: err_exit('viewdoc: too many arguments\n%s' % USAGE) if not isfile(self.defaults.filename) and depth == 0: self.write_defaults() return self.parse_options(args, depth+1) if self.defaults.version < CONFIG_VERSION and depth == 0: self.upgrade_defaults() return self.parse_options(args, depth+1) if self.list: self.list_styles() return remaining_args def list_styles(self): """Print available styles and exit. """ known = sorted(self.defaults.known_styles) if not known: err_exit('No styles', 0) for style in known: if style == self.defaults.default_style: print(style, '(default)') else: print(style) sys.exit(0) def render_long_description(self, dirname): """Convert a package's long description to HTML. """ with changedir(dirname): self.setuptools.check_valid_package() long_description = self.setuptools.get_long_description() outfile = abspath('.long-description.html') self.docutils.publish_string(long_description, outfile, self.styles) return outfile def open_in_browser(self, outfile): """Open the given HTML file in a browser. """ if self.browser == 'default': webbrowser.open('file://%s' % outfile) else: browser = webbrowser.get(self.browser) browser.open('file://%s' % outfile) def run(self): """Render and display Python package documentation. """ os.environ['JARN_RUN'] = '1' self.python.check_valid_python() args = self.parse_options(self.args) if args: arg = args[0] else: arg = os.curdir if arg: arg = expanduser(arg) if isfile(arg): outfile = self.render_file(arg) elif isdir(arg): outfile = self.render_long_description(arg) else: err_exit('No such file or directory: %s' % arg) self.open_in_browser(outfile)
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.render_long_description
python
def render_long_description(self, dirname): with changedir(dirname): self.setuptools.check_valid_package() long_description = self.setuptools.get_long_description() outfile = abspath('.long-description.html') self.docutils.publish_string(long_description, outfile, self.styles) return outfile
Convert a package's long description to HTML.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L532-L540
null
class DocumentationViewer(object): def __init__(self, args): """Initialize. """ self.args = args self.set_defaults(expanduser('~/.viewdoc')) def set_defaults(self, config_file): """Set defaults. """ self.defaults = Defaults(config_file) self.python = Python() self.setuptools = Setuptools() self.docutils = Docutils() self.styles = self.defaults.styles self.browser = self.defaults.browser self.list = False def reset_defaults(self, config_file): """Reset defaults. """ if not exists(config_file): err_exit('No such file: %(config_file)s' % locals()) if not isfile(config_file): err_exit('Not a file: %(config_file)s' % locals()) if not os.access(config_file, os.R_OK): err_exit('File cannot be read: %(config_file)s' % locals()) self.set_defaults(config_file) def write_defaults(self): """Create default config file and reload. """ self.defaults.write() self.reset_defaults(self.defaults.filename) def upgrade_defaults(self): """Upgrade config file and reload. """ self.defaults.upgrade() self.reset_defaults(self.defaults.filename) def parse_options(self, args, depth=0): """Parse command line options. """ style_names = tuple(self.defaults.known_styles) style_opts = tuple('--'+x for x in style_names) try: options, remaining_args = getopt.gnu_getopt(args, 'b:c:hls:v', ('help', 'style=', 'version', 'list-styles', 'browser=', 'config-file=') + style_names) except getopt.GetoptError as e: err_exit('viewdoc: %s\n%s' % (e.msg, USAGE)) for name, value in options: if name in ('-s', '--style'): self.styles = self.defaults.known_styles.get(value, '') elif name in style_opts: self.styles = self.defaults.known_styles.get(name[2:], '') elif name in ('-b', '--browser'): self.browser = value elif name in ('-l', '--list-styles'): self.list = True elif name in ('-h', '--help'): msg_exit(HELP) elif name in ('-v', '--version'): msg_exit(VERSION) elif name in ('-c', '--config-file') and depth == 0: self.reset_defaults(expanduser(value)) return self.parse_options(args, depth+1) if len(remaining_args) > 1: err_exit('viewdoc: too many arguments\n%s' % USAGE) if not isfile(self.defaults.filename) and depth == 0: self.write_defaults() return self.parse_options(args, depth+1) if self.defaults.version < CONFIG_VERSION and depth == 0: self.upgrade_defaults() return self.parse_options(args, depth+1) if self.list: self.list_styles() return remaining_args def list_styles(self): """Print available styles and exit. """ known = sorted(self.defaults.known_styles) if not known: err_exit('No styles', 0) for style in known: if style == self.defaults.default_style: print(style, '(default)') else: print(style) sys.exit(0) def render_file(self, filename): """Convert a reST file to HTML. """ dirname, basename = split(filename) with changedir(dirname): infile = abspath(basename) outfile = abspath('.%s.html' % basename) self.docutils.publish_file(infile, outfile, self.styles) return outfile def open_in_browser(self, outfile): """Open the given HTML file in a browser. """ if self.browser == 'default': webbrowser.open('file://%s' % outfile) else: browser = webbrowser.get(self.browser) browser.open('file://%s' % outfile) def run(self): """Render and display Python package documentation. """ os.environ['JARN_RUN'] = '1' self.python.check_valid_python() args = self.parse_options(self.args) if args: arg = args[0] else: arg = os.curdir if arg: arg = expanduser(arg) if isfile(arg): outfile = self.render_file(arg) elif isdir(arg): outfile = self.render_long_description(arg) else: err_exit('No such file or directory: %s' % arg) self.open_in_browser(outfile)
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.open_in_browser
python
def open_in_browser(self, outfile): if self.browser == 'default': webbrowser.open('file://%s' % outfile) else: browser = webbrowser.get(self.browser) browser.open('file://%s' % outfile)
Open the given HTML file in a browser.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L542-L549
null
class DocumentationViewer(object): def __init__(self, args): """Initialize. """ self.args = args self.set_defaults(expanduser('~/.viewdoc')) def set_defaults(self, config_file): """Set defaults. """ self.defaults = Defaults(config_file) self.python = Python() self.setuptools = Setuptools() self.docutils = Docutils() self.styles = self.defaults.styles self.browser = self.defaults.browser self.list = False def reset_defaults(self, config_file): """Reset defaults. """ if not exists(config_file): err_exit('No such file: %(config_file)s' % locals()) if not isfile(config_file): err_exit('Not a file: %(config_file)s' % locals()) if not os.access(config_file, os.R_OK): err_exit('File cannot be read: %(config_file)s' % locals()) self.set_defaults(config_file) def write_defaults(self): """Create default config file and reload. """ self.defaults.write() self.reset_defaults(self.defaults.filename) def upgrade_defaults(self): """Upgrade config file and reload. """ self.defaults.upgrade() self.reset_defaults(self.defaults.filename) def parse_options(self, args, depth=0): """Parse command line options. """ style_names = tuple(self.defaults.known_styles) style_opts = tuple('--'+x for x in style_names) try: options, remaining_args = getopt.gnu_getopt(args, 'b:c:hls:v', ('help', 'style=', 'version', 'list-styles', 'browser=', 'config-file=') + style_names) except getopt.GetoptError as e: err_exit('viewdoc: %s\n%s' % (e.msg, USAGE)) for name, value in options: if name in ('-s', '--style'): self.styles = self.defaults.known_styles.get(value, '') elif name in style_opts: self.styles = self.defaults.known_styles.get(name[2:], '') elif name in ('-b', '--browser'): self.browser = value elif name in ('-l', '--list-styles'): self.list = True elif name in ('-h', '--help'): msg_exit(HELP) elif name in ('-v', '--version'): msg_exit(VERSION) elif name in ('-c', '--config-file') and depth == 0: self.reset_defaults(expanduser(value)) return self.parse_options(args, depth+1) if len(remaining_args) > 1: err_exit('viewdoc: too many arguments\n%s' % USAGE) if not isfile(self.defaults.filename) and depth == 0: self.write_defaults() return self.parse_options(args, depth+1) if self.defaults.version < CONFIG_VERSION and depth == 0: self.upgrade_defaults() return self.parse_options(args, depth+1) if self.list: self.list_styles() return remaining_args def list_styles(self): """Print available styles and exit. """ known = sorted(self.defaults.known_styles) if not known: err_exit('No styles', 0) for style in known: if style == self.defaults.default_style: print(style, '(default)') else: print(style) sys.exit(0) def render_file(self, filename): """Convert a reST file to HTML. """ dirname, basename = split(filename) with changedir(dirname): infile = abspath(basename) outfile = abspath('.%s.html' % basename) self.docutils.publish_file(infile, outfile, self.styles) return outfile def render_long_description(self, dirname): """Convert a package's long description to HTML. """ with changedir(dirname): self.setuptools.check_valid_package() long_description = self.setuptools.get_long_description() outfile = abspath('.long-description.html') self.docutils.publish_string(long_description, outfile, self.styles) return outfile def run(self): """Render and display Python package documentation. """ os.environ['JARN_RUN'] = '1' self.python.check_valid_python() args = self.parse_options(self.args) if args: arg = args[0] else: arg = os.curdir if arg: arg = expanduser(arg) if isfile(arg): outfile = self.render_file(arg) elif isdir(arg): outfile = self.render_long_description(arg) else: err_exit('No such file or directory: %s' % arg) self.open_in_browser(outfile)
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.run
python
def run(self): os.environ['JARN_RUN'] = '1' self.python.check_valid_python() args = self.parse_options(self.args) if args: arg = args[0] else: arg = os.curdir if arg: arg = expanduser(arg) if isfile(arg): outfile = self.render_file(arg) elif isdir(arg): outfile = self.render_long_description(arg) else: err_exit('No such file or directory: %s' % arg) self.open_in_browser(outfile)
Render and display Python package documentation.
train
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L551-L572
[ "def err_exit(msg, rc=1):\n \"\"\"Print msg to stderr and exit with rc.\n \"\"\"\n print(msg, file=sys.stderr)\n sys.exit(rc)\n", "def parse_options(self, args, depth=0):\n \"\"\"Parse command line options.\n \"\"\"\n style_names = tuple(self.defaults.known_styles)\n style_opts = tuple('--'+x for x in style_names)\n\n try:\n options, remaining_args = getopt.gnu_getopt(args, 'b:c:hls:v',\n ('help', 'style=', 'version', 'list-styles', 'browser=',\n 'config-file=') + style_names)\n except getopt.GetoptError as e:\n err_exit('viewdoc: %s\\n%s' % (e.msg, USAGE))\n\n for name, value in options:\n if name in ('-s', '--style'):\n self.styles = self.defaults.known_styles.get(value, '')\n elif name in style_opts:\n self.styles = self.defaults.known_styles.get(name[2:], '')\n elif name in ('-b', '--browser'):\n self.browser = value\n elif name in ('-l', '--list-styles'):\n self.list = True\n elif name in ('-h', '--help'):\n msg_exit(HELP)\n elif name in ('-v', '--version'):\n msg_exit(VERSION)\n elif name in ('-c', '--config-file') and depth == 0:\n self.reset_defaults(expanduser(value))\n return self.parse_options(args, depth+1)\n\n if len(remaining_args) > 1:\n err_exit('viewdoc: too many arguments\\n%s' % USAGE)\n\n if not isfile(self.defaults.filename) and depth == 0:\n self.write_defaults()\n return self.parse_options(args, depth+1)\n\n if self.defaults.version < CONFIG_VERSION and depth == 0:\n self.upgrade_defaults()\n return self.parse_options(args, depth+1)\n\n if self.list:\n self.list_styles()\n\n return remaining_args\n", "def render_file(self, filename):\n \"\"\"Convert a reST file to HTML.\n \"\"\"\n dirname, basename = split(filename)\n with changedir(dirname):\n infile = abspath(basename)\n outfile = abspath('.%s.html' % basename)\n self.docutils.publish_file(infile, outfile, self.styles)\n return outfile\n", "def render_long_description(self, dirname):\n \"\"\"Convert a package's long description to HTML.\n \"\"\"\n with changedir(dirname):\n self.setuptools.check_valid_package()\n long_description = self.setuptools.get_long_description()\n outfile = abspath('.long-description.html')\n self.docutils.publish_string(long_description, outfile, self.styles)\n return outfile\n", "def open_in_browser(self, outfile):\n \"\"\"Open the given HTML file in a browser.\n \"\"\"\n if self.browser == 'default':\n webbrowser.open('file://%s' % outfile)\n else:\n browser = webbrowser.get(self.browser)\n browser.open('file://%s' % outfile)\n" ]
class DocumentationViewer(object): def __init__(self, args): """Initialize. """ self.args = args self.set_defaults(expanduser('~/.viewdoc')) def set_defaults(self, config_file): """Set defaults. """ self.defaults = Defaults(config_file) self.python = Python() self.setuptools = Setuptools() self.docutils = Docutils() self.styles = self.defaults.styles self.browser = self.defaults.browser self.list = False def reset_defaults(self, config_file): """Reset defaults. """ if not exists(config_file): err_exit('No such file: %(config_file)s' % locals()) if not isfile(config_file): err_exit('Not a file: %(config_file)s' % locals()) if not os.access(config_file, os.R_OK): err_exit('File cannot be read: %(config_file)s' % locals()) self.set_defaults(config_file) def write_defaults(self): """Create default config file and reload. """ self.defaults.write() self.reset_defaults(self.defaults.filename) def upgrade_defaults(self): """Upgrade config file and reload. """ self.defaults.upgrade() self.reset_defaults(self.defaults.filename) def parse_options(self, args, depth=0): """Parse command line options. """ style_names = tuple(self.defaults.known_styles) style_opts = tuple('--'+x for x in style_names) try: options, remaining_args = getopt.gnu_getopt(args, 'b:c:hls:v', ('help', 'style=', 'version', 'list-styles', 'browser=', 'config-file=') + style_names) except getopt.GetoptError as e: err_exit('viewdoc: %s\n%s' % (e.msg, USAGE)) for name, value in options: if name in ('-s', '--style'): self.styles = self.defaults.known_styles.get(value, '') elif name in style_opts: self.styles = self.defaults.known_styles.get(name[2:], '') elif name in ('-b', '--browser'): self.browser = value elif name in ('-l', '--list-styles'): self.list = True elif name in ('-h', '--help'): msg_exit(HELP) elif name in ('-v', '--version'): msg_exit(VERSION) elif name in ('-c', '--config-file') and depth == 0: self.reset_defaults(expanduser(value)) return self.parse_options(args, depth+1) if len(remaining_args) > 1: err_exit('viewdoc: too many arguments\n%s' % USAGE) if not isfile(self.defaults.filename) and depth == 0: self.write_defaults() return self.parse_options(args, depth+1) if self.defaults.version < CONFIG_VERSION and depth == 0: self.upgrade_defaults() return self.parse_options(args, depth+1) if self.list: self.list_styles() return remaining_args def list_styles(self): """Print available styles and exit. """ known = sorted(self.defaults.known_styles) if not known: err_exit('No styles', 0) for style in known: if style == self.defaults.default_style: print(style, '(default)') else: print(style) sys.exit(0) def render_file(self, filename): """Convert a reST file to HTML. """ dirname, basename = split(filename) with changedir(dirname): infile = abspath(basename) outfile = abspath('.%s.html' % basename) self.docutils.publish_file(infile, outfile, self.styles) return outfile def render_long_description(self, dirname): """Convert a package's long description to HTML. """ with changedir(dirname): self.setuptools.check_valid_package() long_description = self.setuptools.get_long_description() outfile = abspath('.long-description.html') self.docutils.publish_string(long_description, outfile, self.styles) return outfile def open_in_browser(self, outfile): """Open the given HTML file in a browser. """ if self.browser == 'default': webbrowser.open('file://%s' % outfile) else: browser = webbrowser.get(self.browser) browser.open('file://%s' % outfile)
MacHu-GWU/crawlib-project
crawlib/cache.py
create_cache
python
def create_cache(directory, compress_level=6, value_type_is_binary=False, **kwargs): cache = diskcache.Cache( directory, disk=CompressedDisk, disk_compress_level=compress_level, disk_value_type_is_binary=value_type_is_binary, **kwargs ) return cache
Create a html cache. Html string will be automatically compressed. :param directory: path for the cache directory. :param compress_level: 0 ~ 9, 9 is slowest and smallest. :param kwargs: other arguments. :return: a `diskcache.Cache()`
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/cache.py#L75-L91
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A disk cache layer to store url and its html. """ from __future__ import print_function import sys import zlib import requests import diskcache from . import exc from .decode import decoder class CompressedDisk(diskcache.Disk): # pragma: no cover """ Serialization Layer. Value has to be bytes or string type, and will be compressed using zlib before stored to disk. - Key: str, url. - Value: str or bytes, html or binary content. """ def __init__(self, directory, compress_level=6, value_type_is_binary=False, **kwargs): self.compress_level = compress_level self.value_type_is_binary = value_type_is_binary if value_type_is_binary is True: self._decompress = self._decompress_return_bytes self._compress = self._compress_bytes elif value_type_is_binary is False: self._decompress = self._decompress_return_str self._compress = self._compress_str else: msg = "`value_type_is_binary` arg has to be a boolean value!" raise ValueError(msg) super(CompressedDisk, self).__init__(directory, **kwargs) def _decompress_return_str(self, data): return zlib.decompress(data).decode("utf-8") def _decompress_return_bytes(self, data): return zlib.decompress(data) def _compress_str(self, data): return zlib.compress(data.encode("utf-8"), self.compress_level) def _compress_bytes(self, data): return zlib.compress(data, self.compress_level) def get(self, key, raw): data = super(CompressedDisk, self).get(key, raw) return self._decompress(data) def store(self, value, read, **kwargs): if not read: value = self._compress(value) return super(CompressedDisk, self).store(value, read, **kwargs) def fetch(self, mode, filename, value, read): data = super(CompressedDisk, self). \ fetch(mode, filename, value, read) if not read: data = self._decompress(data) return data class CacheBackedDownloader(object): """ Implement a disk cache backed url content downloader functionality. :param cache_dir: str, diskCache directory. :param read_cache_first: bool, If true, downloader will try read binary content from cache. :param alert_when_cache_missing: bool, If true, a log message will be displayed when url has not been seen in cache. :param always_update_cache: bool, If true, the response content will be saved to cache anyway. :param cache_expire: int, number seconds to expire. :param cache_value_type_is_binary: bool :param cache_compress_level: compress level, 1-9. 9 is highest. """ def __init__(self, cache_dir=None, read_cache_first=False, alert_when_cache_missing=False, always_update_cache=False, cache_expire=None, cache_value_type_is_binary=None, cache_compress_level=6, **kwargs): self.cache = None self.cache_dir = cache_dir self.read_cache_first = read_cache_first self.alert_when_cache_missing = alert_when_cache_missing self.always_update_cache = always_update_cache self.cache_expire = cache_expire self.cache_value_type_is_binary = cache_value_type_is_binary # cache if (read_cache_first is True) and (cache_dir is None): raise ValueError( "Please specify the `cache_dir` to read response from cache!") if (read_cache_first is False) and (alert_when_cache_missing is True): raise ValueError( "Please turn on `read_cache_first = True` to enable alert when cache missing!") if (always_update_cache is True) and (cache_dir is None): raise ValueError( "Please specify the `cache_dir` to save response to cache!") if cache_dir: self.cache = create_cache( cache_dir, compress_level=cache_compress_level, value_type_is_binary=cache_value_type_is_binary, ) def close_cache(self): if self.cache_dir is not None: self.cache.close() def try_read_cache(self, url, mute=False): cache_consumed = False value = None if self.read_cache_first: if url in self.cache: value = self.cache[url] cache_consumed = True else: # pragma: no cover if self.alert_when_cache_missing: if mute: pass else: msg = "\n{} doesn't hit cache!".format(url) sys.stdout.write(msg) return cache_consumed, value def should_we_update_cache(self, any_type_response, cache_cb, cache_consumed_flag): """ :param any_type_response: any response object. :param cache_cb: a call back function taking ``any_type_response`` as input, and return a boolean value to indicate that whether we should update cache. :return: bool. **中文文档** 1. 如果 ``cache_consumed_flag`` 为 True, 那么说明已经从cache中读取过数据了, 再存也没有意义. 2. 如果 ``self.always_update_cache`` 为 True, 那么强制更新cache. 我们不用担心 发生已经读取过cache, 然后再强制更新的情况, 因为之前我们已经检查过 ``cache_consumed_flag`` 了. 3. 如果没有指定 ``cache_cb`` 函数, 那么默认不更新cache. """ if cache_consumed_flag: return False if self.always_update_cache: return True if cache_cb is None: return False else: return cache_cb(any_type_response)
MacHu-GWU/crawlib-project
crawlib/downloader/selenium_downloader.py
BaseSeleliumDownloader._create_driver
python
def _create_driver(self, **kwargs): if self.driver is None: self.driver = self.create_driver(**kwargs) self.init_driver_func(self.driver)
Create webdriver, assign it to ``self.driver``, and run webdriver initiation process, which is usually used for manual login.
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/downloader/selenium_downloader.py#L86-L93
[ "init_driver_func=lambda driver: driver,\n", "def create_driver(self, **kwargs):\n \"\"\"\n Create webdriver instance.\n \"\"\"\n raise NotImplementedError\n", "def create_driver(self, **kwargs):\n return webdriver.Chrome(executable_path=self.chromedriver_executable_path)\n" ]
class BaseSeleliumDownloader(DownloaderABC, CacheBackedDownloader): """ Implements common behavior for downloading url content. .. note:: In ``__init__(self, ...)`` method, we only save the parameters. The actually webdriver creation happened in :meth:`BaseSeleliumDownloader.create_driver`. :param testmode: bool, see :meth:`BaseSeleniumDownloader.use_testmode`. """ def __init__(self, init_driver_func=lambda driver: driver, cache_dir=None, read_cache_first=False, alert_when_cache_missing=False, always_update_cache=False, cache_expire=None, testmode=False, **kwargs): self.driver = None self.init_driver_func = init_driver_func self.cache_dir = cache_dir self.read_cache_first = read_cache_first self.alert_when_cache_missing = alert_when_cache_missing self.always_update_cache = always_update_cache self.cache_expire = cache_expire self.testmode = testmode # in testmode we dont't create webdriver object instantly if self.testmode: self.use_testmode() else: self._create_driver() super(BaseSeleliumDownloader, self).__init__( cache_dir=self.cache_dir, read_cache_first=self.read_cache_first, alert_when_cache_missing=self.alert_when_cache_missing, always_update_cache=self.always_update_cache, cache_expire=self.cache_expire, cache_value_type_is_binary=False, cache_compress_level=6, ) def use_testmode(self): """ **中文文档** 在测试中我们会有特殊的需求. 我们希望能用Selenium从测试Url上抓取Html, 然后对 ``html_parser`` 中的函数进行测试. 期间我们希望能对Html进行缓存, 在短时间内重复 运行测试时, 使用缓存中的Html. 当且仅当我们需要时, 才启动浏览器进行抓取. 这种 模式我们称之为 ``测试模式`` (``testmode``). 测试模式: 在测试模式中, 我们设定: 1. 在未遭遇缓存未命中之前, 并不真正的创建 ``WebDriver`` 对象 (并不打开浏览器) 只有在未命中时, 再创建并初始化 :attr:`BaseSeleliumDownloader.driver`. 2. 永远先尝试从缓存中读取数据. 3. 当缓存未命中时显示提示信息. 4. 永远自动更新缓存. """ self.read_cache_first = True self.alert_when_cache_missing = True self.always_update_cache = True def create_driver(self, **kwargs): """ Create webdriver instance. """ raise NotImplementedError def get_html(self, url, params=None, cache_cb=None, **kwargs): """ Get html of an url. """ url = add_params(url, params) cache_consumed, value = self.try_read_cache(url) if cache_consumed: html = value else: self._create_driver() self.driver.get(url) html = self.driver.page_source if self.should_we_update_cache(html, cache_cb, cache_consumed): self.cache.set( url, html, expire=kwargs.get("cache_expire", self.cache_expire), ) return html def download(self, *args, **kwargs): """ .. warning:: NOT IMPLEMENTED! python selenium doesn't support file and image downloading. """ msg = ( "Selenium should not be used to download non-html content. " "For downloading image or files, find the resource url, " "and use requests library to download it." ) raise NotImplementedError(msg) def close_drive(self): if self.driver is not None: self.driver.close() def close(self): self.close_cache() self.close_drive() def __enter__(self): return self def __exit__(self, *exc_info): self.close()
MacHu-GWU/crawlib-project
crawlib/downloader/selenium_downloader.py
BaseSeleliumDownloader.get_html
python
def get_html(self, url, params=None, cache_cb=None, **kwargs): url = add_params(url, params) cache_consumed, value = self.try_read_cache(url) if cache_consumed: html = value else: self._create_driver() self.driver.get(url) html = self.driver.page_source if self.should_we_update_cache(html, cache_cb, cache_consumed): self.cache.set( url, html, expire=kwargs.get("cache_expire", self.cache_expire), ) return html
Get html of an url.
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/downloader/selenium_downloader.py#L101-L123
[ "def add_params(endpoint, params):\n \"\"\"\n Combine query endpoint and params.\n\n Example::\n\n >>> add_params(\"https://www.google.com/search\", {\"q\": \"iphone\"})\n https://www.google.com/search?q=iphone\n \"\"\"\n p = PreparedRequest()\n p.prepare(url=endpoint, params=params)\n if PY2: # pragma: no cover\n return unicode(p.url)\n else: # pragma: no cover\n return p.url\n", "def try_read_cache(self, url, mute=False):\n cache_consumed = False\n value = None\n if self.read_cache_first:\n if url in self.cache:\n value = self.cache[url]\n cache_consumed = True\n else: # pragma: no cover\n if self.alert_when_cache_missing:\n if mute:\n pass\n else:\n msg = \"\\n{} doesn't hit cache!\".format(url)\n sys.stdout.write(msg)\n return cache_consumed, value\n", "def should_we_update_cache(self,\n any_type_response,\n cache_cb,\n cache_consumed_flag):\n \"\"\"\n\n :param any_type_response: any response object.\n :param cache_cb: a call back function taking ``any_type_response``\n as input, and return a boolean value to indicate that whether we\n should update cache.\n :return: bool.\n\n **中文文档**\n\n 1. 如果 ``cache_consumed_flag`` 为 True, 那么说明已经从cache中读取过数据了,\n 再存也没有意义.\n 2. 如果 ``self.always_update_cache`` 为 True, 那么强制更新cache. 我们不用担心\n 发生已经读取过cache, 然后再强制更新的情况, 因为之前我们已经检查过\n ``cache_consumed_flag`` 了.\n 3. 如果没有指定 ``cache_cb`` 函数, 那么默认不更新cache.\n \"\"\"\n if cache_consumed_flag:\n return False\n\n if self.always_update_cache:\n return True\n\n if cache_cb is None:\n return False\n else:\n return cache_cb(any_type_response)\n", "def _create_driver(self, **kwargs):\n \"\"\"\n Create webdriver, assign it to ``self.driver``, and run webdriver\n initiation process, which is usually used for manual login.\n \"\"\"\n if self.driver is None:\n self.driver = self.create_driver(**kwargs)\n self.init_driver_func(self.driver)\n" ]
class BaseSeleliumDownloader(DownloaderABC, CacheBackedDownloader): """ Implements common behavior for downloading url content. .. note:: In ``__init__(self, ...)`` method, we only save the parameters. The actually webdriver creation happened in :meth:`BaseSeleliumDownloader.create_driver`. :param testmode: bool, see :meth:`BaseSeleniumDownloader.use_testmode`. """ def __init__(self, init_driver_func=lambda driver: driver, cache_dir=None, read_cache_first=False, alert_when_cache_missing=False, always_update_cache=False, cache_expire=None, testmode=False, **kwargs): self.driver = None self.init_driver_func = init_driver_func self.cache_dir = cache_dir self.read_cache_first = read_cache_first self.alert_when_cache_missing = alert_when_cache_missing self.always_update_cache = always_update_cache self.cache_expire = cache_expire self.testmode = testmode # in testmode we dont't create webdriver object instantly if self.testmode: self.use_testmode() else: self._create_driver() super(BaseSeleliumDownloader, self).__init__( cache_dir=self.cache_dir, read_cache_first=self.read_cache_first, alert_when_cache_missing=self.alert_when_cache_missing, always_update_cache=self.always_update_cache, cache_expire=self.cache_expire, cache_value_type_is_binary=False, cache_compress_level=6, ) def use_testmode(self): """ **中文文档** 在测试中我们会有特殊的需求. 我们希望能用Selenium从测试Url上抓取Html, 然后对 ``html_parser`` 中的函数进行测试. 期间我们希望能对Html进行缓存, 在短时间内重复 运行测试时, 使用缓存中的Html. 当且仅当我们需要时, 才启动浏览器进行抓取. 这种 模式我们称之为 ``测试模式`` (``testmode``). 测试模式: 在测试模式中, 我们设定: 1. 在未遭遇缓存未命中之前, 并不真正的创建 ``WebDriver`` 对象 (并不打开浏览器) 只有在未命中时, 再创建并初始化 :attr:`BaseSeleliumDownloader.driver`. 2. 永远先尝试从缓存中读取数据. 3. 当缓存未命中时显示提示信息. 4. 永远自动更新缓存. """ self.read_cache_first = True self.alert_when_cache_missing = True self.always_update_cache = True def _create_driver(self, **kwargs): """ Create webdriver, assign it to ``self.driver``, and run webdriver initiation process, which is usually used for manual login. """ if self.driver is None: self.driver = self.create_driver(**kwargs) self.init_driver_func(self.driver) def create_driver(self, **kwargs): """ Create webdriver instance. """ raise NotImplementedError def download(self, *args, **kwargs): """ .. warning:: NOT IMPLEMENTED! python selenium doesn't support file and image downloading. """ msg = ( "Selenium should not be used to download non-html content. " "For downloading image or files, find the resource url, " "and use requests library to download it." ) raise NotImplementedError(msg) def close_drive(self): if self.driver is not None: self.driver.close() def close(self): self.close_cache() self.close_drive() def __enter__(self): return self def __exit__(self, *exc_info): self.close()
MacHu-GWU/crawlib-project
crawlib/decode.py
smart_decode
python
def smart_decode(binary, errors="strict"): d = chardet.detect(binary) encoding = d["encoding"] confidence = d["confidence"] text = binary.decode(encoding, errors=errors) return text, encoding, confidence
Automatically find the right codec to decode binary data to string. :param binary: binary data :param errors: one of 'strict', 'ignore' and 'replace' :return: string
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/decode.py#L12-L25
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This module provide extended power to decode HTML you crawled. """ import chardet from . import util class UrlSpecifiedDecoder(object): """ Designed for automatically decoding html from binary content of an url. First, `chardet.detect` is very expensive in time. Second, usually each website (per domain) only use one encoding algorithm. This class avoid perform `chardet.detect` twice on the same domain. :param domain_encoding_table: dict, key is root domain, and value is the domain's default encoding. """ class ErrorsHandle(object): strict = "strict" ignore = "ignore" replace = "replace" def __init__(self): self.domain_encoding_table = dict() def decode(self, binary, url, encoding=None, errors="strict"): """ Decode binary to string. :param binary: binary content of a http request. :param url: endpoint of the request. :param encoding: manually specify the encoding. :param errors: errors handle method. :return: str """ if encoding is None: domain = util.get_domain(url) if domain in self.domain_encoding_table: encoding = self.domain_encoding_table[domain] html = binary.decode(encoding, errors=errors) else: html, encoding, confidence = smart_decode( binary, errors=errors) # cache domain name and encoding self.domain_encoding_table[domain] = encoding else: html = binary.decode(encoding, errors=errors) return html url_specified_decoder = UrlSpecifiedDecoder() decoder = url_specified_decoder
MacHu-GWU/crawlib-project
crawlib/decode.py
UrlSpecifiedDecoder.decode
python
def decode(self, binary, url, encoding=None, errors="strict"): if encoding is None: domain = util.get_domain(url) if domain in self.domain_encoding_table: encoding = self.domain_encoding_table[domain] html = binary.decode(encoding, errors=errors) else: html, encoding, confidence = smart_decode( binary, errors=errors) # cache domain name and encoding self.domain_encoding_table[domain] = encoding else: html = binary.decode(encoding, errors=errors) return html
Decode binary to string. :param binary: binary content of a http request. :param url: endpoint of the request. :param encoding: manually specify the encoding. :param errors: errors handle method. :return: str
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/decode.py#L49-L73
[ "def smart_decode(binary, errors=\"strict\"):\n \"\"\"\n Automatically find the right codec to decode binary data to string.\n\n :param binary: binary data\n :param errors: one of 'strict', 'ignore' and 'replace'\n :return: string\n \"\"\"\n d = chardet.detect(binary)\n encoding = d[\"encoding\"]\n confidence = d[\"confidence\"]\n\n text = binary.decode(encoding, errors=errors)\n return text, encoding, confidence\n", "def get_domain(url):\n \"\"\"\n Get domain part of an url.\n\n For example: https://www.python.org/doc/ -> https://www.python.org\n \"\"\"\n parse_result = urlparse(url)\n domain = \"{schema}://{netloc}\".format(\n schema=parse_result.scheme, netloc=parse_result.netloc)\n return domain\n" ]
class UrlSpecifiedDecoder(object): """ Designed for automatically decoding html from binary content of an url. First, `chardet.detect` is very expensive in time. Second, usually each website (per domain) only use one encoding algorithm. This class avoid perform `chardet.detect` twice on the same domain. :param domain_encoding_table: dict, key is root domain, and value is the domain's default encoding. """ class ErrorsHandle(object): strict = "strict" ignore = "ignore" replace = "replace" def __init__(self): self.domain_encoding_table = dict()
MacHu-GWU/crawlib-project
crawlib/url_builder/builder.py
BaseUrlBuilder.join_all
python
def join_all(self, *parts): url = util.join_all(self.domain, *parts) return url
Join all parts with domain. Example domain: https://www.python.org :param parts: Other parts, example: "/doc", "/py27" :return: url
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/url_builder/builder.py#L17-L25
[ "def join_all(domain, *parts):\n \"\"\"\n Join all url components.\n\n Example::\n\n >>> join_all(\"https://www.apple.com\", \"iphone\")\n https://www.apple.com/iphone\n\n :param domain: Domain parts, example: https://www.python.org\n :param parts: Other parts, example: \"/doc\", \"/py27\"\n :return: url\n \"\"\"\n l = list()\n\n if domain.endswith(\"/\"):\n domain = domain[:-1]\n l.append(domain)\n\n for part in parts:\n for i in part.split(\"/\"):\n if i.strip():\n l.append(i)\n url = \"/\".join(l)\n return url\n" ]
class BaseUrlBuilder(BaseDomainSpecifiedKlass): """ Base url builder. Provide functional interface to create url. """ def add_params(self, endpoint, params): """ Combine query endpoint and params. """ assert endpoint.startswith(self.domain) return util.add_params(endpoint, params) def build_url(self, *args, **kwargs): """ An example url builder method. """ raise NotImplementedError
MacHu-GWU/crawlib-project
crawlib/url_builder/builder.py
BaseUrlBuilder.add_params
python
def add_params(self, endpoint, params): assert endpoint.startswith(self.domain) return util.add_params(endpoint, params)
Combine query endpoint and params.
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/url_builder/builder.py#L27-L32
[ "def add_params(endpoint, params):\n \"\"\"\n Combine query endpoint and params.\n\n Example::\n\n >>> add_params(\"https://www.google.com/search\", {\"q\": \"iphone\"})\n https://www.google.com/search?q=iphone\n \"\"\"\n p = PreparedRequest()\n p.prepare(url=endpoint, params=params)\n if PY2: # pragma: no cover\n return unicode(p.url)\n else: # pragma: no cover\n return p.url\n" ]
class BaseUrlBuilder(BaseDomainSpecifiedKlass): """ Base url builder. Provide functional interface to create url. """ def join_all(self, *parts): """ Join all parts with domain. Example domain: https://www.python.org :param parts: Other parts, example: "/doc", "/py27" :return: url """ url = util.join_all(self.domain, *parts) return url def build_url(self, *args, **kwargs): """ An example url builder method. """ raise NotImplementedError
MacHu-GWU/crawlib-project
crawlib/html_parser/decorator.py
validate_implementation_for_auto_decode_and_soupify
python
def validate_implementation_for_auto_decode_and_soupify(func): arg_spec = inspect.getargspec(func) for arg in ["response", "html", "soup"]: if arg not in arg_spec.args: raise NotImplementedError( ("{func} method has to take the keyword syntax input: " "{arg}").format(func=func, arg=arg) )
Validate that :func:`auto_decode_and_soupify` is applicable to this function. If not applicable, a ``NotImplmentedError`` will be raised.
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/html_parser/decorator.py#L57-L68
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ There are three major popular libraries widely used for making http request: - ``requests``: http://docs.python-requests.org/en/master/ - ``scrapy``: https://doc.scrapy.org/en/latest/topics/request-response.html - ``selenium``: http://selenium-python.readthedocs.io/index.html And there are two major popular library widely used for extracting data from html: - ``beautifulsoup4``: https://www.crummy.com/software/BeautifulSoup/bs4/doc/ - ``scrapy.selector``: https://doc.scrapy.org/en/latest/topics/selectors.html This module bridge the gap. """ import inspect from bs4 import BeautifulSoup from requests import Response as RequestsResponse try: from scrapy.http import Response as ScrapyResponse except: # pragma: no cover pass from ..decode import decoder from ..exc import DecodeError, SoupError def soupify(html): """ Convert html to BeautifulSoup. It solves api change in bs4.3. """ try: return BeautifulSoup(html, "html.parser") except Exception as e: # pragma: no cover raise SoupError(str(e)) def access_binary(response): if isinstance(response, RequestsResponse): binary = response.content elif isinstance(response, ScrapyResponse): binary = response.body else: # pragma: no cover raise TypeError("It only support ScrapyResponse or RequestsResponse!") return binary _auto_decode_and_soupify_implementation_ok_mapper = dict() def auto_decode_and_soupify(encoding=None, errors=decoder.ErrorsHandle.strict): """ This decorator assume that there are three argument in keyword syntax: - ``response``: ``requests.Response`` or ``scrapy.http.Reponse`` - ``html``: html string - ``soup``: ``bs4.BeautifulSoup`` 1. if ``soup`` is not available, it will automatically be generated from ``html``. 2. if ``html`` is not available, it will automatically be generated from ``response``. Usage:: @auto_decode_and_soupify() def parse(response, html, soup): ... **中文文档** 此装饰器会自动检测函数中名为 ``response``, ``html``, ``soup`` 的参数, 并在 ``html``, ``soup`` 未给出的情况下, 自动生成所期望的值. 被此装饰器装饰的函数必须 要有以上提到的三个参数. 并且在使用时, 必须使用keyword的形式进行输入. """ def deco(func): func_hash = hash(func) if not _auto_decode_and_soupify_implementation_ok_mapper \ .get(func_hash, False): validate_implementation_for_auto_decode_and_soupify(func) _auto_decode_and_soupify_implementation_ok_mapper[func_hash] = True def wrapper(*args, **kwargs): try: response = kwargs.get("response") html = kwargs.get("html") soup = kwargs.get("soup") except KeyError as e: raise NotImplementedError( ("{func} method has to take the keyword syntax input: " "{e}").format(func=func, e=e) ) if html is None: binary = access_binary(response) try: html = decoder.decode( binary=binary, url=response.url, encoding=encoding, errors=errors, ) except Exception as e: # pragma: no cover raise DecodeError(str(e)) kwargs["html"] = html if soup is None: soup = soupify(html) kwargs["soup"] = soup return func(*args, **kwargs) return wrapper return deco
MacHu-GWU/crawlib-project
crawlib/html_parser/decorator.py
auto_decode_and_soupify
python
def auto_decode_and_soupify(encoding=None, errors=decoder.ErrorsHandle.strict): def deco(func): func_hash = hash(func) if not _auto_decode_and_soupify_implementation_ok_mapper \ .get(func_hash, False): validate_implementation_for_auto_decode_and_soupify(func) _auto_decode_and_soupify_implementation_ok_mapper[func_hash] = True def wrapper(*args, **kwargs): try: response = kwargs.get("response") html = kwargs.get("html") soup = kwargs.get("soup") except KeyError as e: raise NotImplementedError( ("{func} method has to take the keyword syntax input: " "{e}").format(func=func, e=e) ) if html is None: binary = access_binary(response) try: html = decoder.decode( binary=binary, url=response.url, encoding=encoding, errors=errors, ) except Exception as e: # pragma: no cover raise DecodeError(str(e)) kwargs["html"] = html if soup is None: soup = soupify(html) kwargs["soup"] = soup return func(*args, **kwargs) return wrapper return deco
This decorator assume that there are three argument in keyword syntax: - ``response``: ``requests.Response`` or ``scrapy.http.Reponse`` - ``html``: html string - ``soup``: ``bs4.BeautifulSoup`` 1. if ``soup`` is not available, it will automatically be generated from ``html``. 2. if ``html`` is not available, it will automatically be generated from ``response``. Usage:: @auto_decode_and_soupify() def parse(response, html, soup): ... **中文文档** 此装饰器会自动检测函数中名为 ``response``, ``html``, ``soup`` 的参数, 并在 ``html``, ``soup`` 未给出的情况下, 自动生成所期望的值. 被此装饰器装饰的函数必须 要有以上提到的三个参数. 并且在使用时, 必须使用keyword的形式进行输入.
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/html_parser/decorator.py#L71-L136
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ There are three major popular libraries widely used for making http request: - ``requests``: http://docs.python-requests.org/en/master/ - ``scrapy``: https://doc.scrapy.org/en/latest/topics/request-response.html - ``selenium``: http://selenium-python.readthedocs.io/index.html And there are two major popular library widely used for extracting data from html: - ``beautifulsoup4``: https://www.crummy.com/software/BeautifulSoup/bs4/doc/ - ``scrapy.selector``: https://doc.scrapy.org/en/latest/topics/selectors.html This module bridge the gap. """ import inspect from bs4 import BeautifulSoup from requests import Response as RequestsResponse try: from scrapy.http import Response as ScrapyResponse except: # pragma: no cover pass from ..decode import decoder from ..exc import DecodeError, SoupError def soupify(html): """ Convert html to BeautifulSoup. It solves api change in bs4.3. """ try: return BeautifulSoup(html, "html.parser") except Exception as e: # pragma: no cover raise SoupError(str(e)) def access_binary(response): if isinstance(response, RequestsResponse): binary = response.content elif isinstance(response, ScrapyResponse): binary = response.body else: # pragma: no cover raise TypeError("It only support ScrapyResponse or RequestsResponse!") return binary _auto_decode_and_soupify_implementation_ok_mapper = dict() def validate_implementation_for_auto_decode_and_soupify(func): """ Validate that :func:`auto_decode_and_soupify` is applicable to this function. If not applicable, a ``NotImplmentedError`` will be raised. """ arg_spec = inspect.getargspec(func) for arg in ["response", "html", "soup"]: if arg not in arg_spec.args: raise NotImplementedError( ("{func} method has to take the keyword syntax input: " "{arg}").format(func=func, arg=arg) )
MacHu-GWU/crawlib-project
crawlib/helper.py
repr_data_size
python
def repr_data_size(size_in_bytes, precision=2): # pragma: no cover if size_in_bytes < 1024: return "%s B" % size_in_bytes magnitude_of_data = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] index = 0 while 1: index += 1 size_in_bytes, mod = divmod(size_in_bytes, 1024) if size_in_bytes < 1024: break template = "{0:.%sf} {1}" % precision s = template.format(size_in_bytes + mod / 1024.0, magnitude_of_data[index]) return s
Return human readable string represent of a file size. Doesn"t support size greater than 1EB. For example: - 100 bytes => 100 B - 100,000 bytes => 97.66 KB - 100,000,000 bytes => 95.37 MB - 100,000,000,000 bytes => 93.13 GB - 100,000,000,000,000 bytes => 90.95 TB - 100,000,000,000,000,000 bytes => 88.82 PB ... Magnitude of data:: 1000 kB kilobyte 1000 ** 2 MB megabyte 1000 ** 3 GB gigabyte 1000 ** 4 TB terabyte 1000 ** 5 PB petabyte 1000 ** 6 EB exabyte 1000 ** 7 ZB zettabyte 1000 ** 8 YB yottabyte
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/helper.py#L5-L42
null
#!/usr/bin/env python # -*- coding: utf-8 -*-
MacHu-GWU/crawlib-project
crawlib/pipeline/mongodb/query_builder.py
finished
python
def finished(finished_status, update_interval, status_key, edit_at_key): return { status_key: {"$gte": finished_status}, edit_at_key: { "$gte": x_seconds_before_now(update_interval), }, }
Create dict query for pymongo that getting all finished task. :param finished_status: int, status code that greater or equal than this will be considered as finished. :param update_interval: int, the record will be updated every x seconds. :param status_key: status code field key, support dot notation. :param edit_at_key: edit_at time field key, support dot notation. :return: dict, a pymongo filter. **中文文档** 状态码大于某个值, 并且, 更新时间在最近一段时间以内.
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/pipeline/mongodb/query_builder.py#L18-L42
[ "def x_seconds_before_now(seconds):\n return datetime.now() - timedelta(seconds=seconds)\n" ]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ **中文文档** 与Scheduler相关的Mongodb Query. """ try: from ...timestamp import x_seconds_before_now from ...status import FINISHED_STATUS_CODE except: # pragma: no cover from crawlib.timestamp import x_seconds_before_now from crawlib.status import FINISHED_STATUS_CODE def finished_50(update_interval, status_key, edit_at_key): # pragma: no cover return finished( FINISHED_STATUS_CODE, update_interval, status_key, edit_at_key ) def unfinished(finished_status, update_interval, status_key, edit_at_key): """ Create dict query for pymongo that getting all unfinished task. :param finished_status: int, status code that less than this will be considered as unfinished. :param update_interval: int, the record will be updated every x seconds. :param status_key: status code field key, support dot notation. :param edit_at_key: edit_at time field key, support dot notation. :return: dict, a pymongo filter. **中文文档** 状态码小于某个值, 或者, 现在距离更新时间已经超过一定阈值. """ return { "$or": [ {status_key: {"$lt": finished_status}}, {edit_at_key: {"$lt": x_seconds_before_now(update_interval)}}, ] } def unfinished_50(update_interval, status_key, edit_at_key): # pragma: no cover return unfinished( FINISHED_STATUS_CODE, update_interval, status_key, edit_at_key, )
MacHu-GWU/crawlib-project
crawlib/pipeline/mongodb/query_builder.py
unfinished
python
def unfinished(finished_status, update_interval, status_key, edit_at_key): return { "$or": [ {status_key: {"$lt": finished_status}}, {edit_at_key: {"$lt": x_seconds_before_now(update_interval)}}, ] }
Create dict query for pymongo that getting all unfinished task. :param finished_status: int, status code that less than this will be considered as unfinished. :param update_interval: int, the record will be updated every x seconds. :param status_key: status code field key, support dot notation. :param edit_at_key: edit_at time field key, support dot notation. :return: dict, a pymongo filter. **中文文档** 状态码小于某个值, 或者, 现在距离更新时间已经超过一定阈值.
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/pipeline/mongodb/query_builder.py#L52-L77
[ "def x_seconds_before_now(seconds):\n return datetime.now() - timedelta(seconds=seconds)\n" ]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ **中文文档** 与Scheduler相关的Mongodb Query. """ try: from ...timestamp import x_seconds_before_now from ...status import FINISHED_STATUS_CODE except: # pragma: no cover from crawlib.timestamp import x_seconds_before_now from crawlib.status import FINISHED_STATUS_CODE def finished(finished_status, update_interval, status_key, edit_at_key): """ Create dict query for pymongo that getting all finished task. :param finished_status: int, status code that greater or equal than this will be considered as finished. :param update_interval: int, the record will be updated every x seconds. :param status_key: status code field key, support dot notation. :param edit_at_key: edit_at time field key, support dot notation. :return: dict, a pymongo filter. **中文文档** 状态码大于某个值, 并且, 更新时间在最近一段时间以内. """ return { status_key: {"$gte": finished_status}, edit_at_key: { "$gte": x_seconds_before_now(update_interval), }, } def finished_50(update_interval, status_key, edit_at_key): # pragma: no cover return finished( FINISHED_STATUS_CODE, update_interval, status_key, edit_at_key ) def unfinished_50(update_interval, status_key, edit_at_key): # pragma: no cover return unfinished( FINISHED_STATUS_CODE, update_interval, status_key, edit_at_key, )
MacHu-GWU/crawlib-project
crawlib/util.py
get_domain
python
def get_domain(url): parse_result = urlparse(url) domain = "{schema}://{netloc}".format( schema=parse_result.scheme, netloc=parse_result.netloc) return domain
Get domain part of an url. For example: https://www.python.org/doc/ -> https://www.python.org
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/util.py#L24-L33
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ url builder related utility methods. """ from six import PY2 from requests.compat import urlparse from requests.models import PreparedRequest def get_netloc(url): """ Get network location part of an url. For example: https://www.python.org/doc/ -> www.python.org """ parse_result = urlparse(url) netloc = parse_result.netloc return netloc def join_all(domain, *parts): """ Join all url components. Example:: >>> join_all("https://www.apple.com", "iphone") https://www.apple.com/iphone :param domain: Domain parts, example: https://www.python.org :param parts: Other parts, example: "/doc", "/py27" :return: url """ l = list() if domain.endswith("/"): domain = domain[:-1] l.append(domain) for part in parts: for i in part.split("/"): if i.strip(): l.append(i) url = "/".join(l) return url def add_params(endpoint, params): """ Combine query endpoint and params. Example:: >>> add_params("https://www.google.com/search", {"q": "iphone"}) https://www.google.com/search?q=iphone """ p = PreparedRequest() p.prepare(url=endpoint, params=params) if PY2: # pragma: no cover return unicode(p.url) else: # pragma: no cover return p.url
MacHu-GWU/crawlib-project
crawlib/util.py
join_all
python
def join_all(domain, *parts): l = list() if domain.endswith("/"): domain = domain[:-1] l.append(domain) for part in parts: for i in part.split("/"): if i.strip(): l.append(i) url = "/".join(l) return url
Join all url components. Example:: >>> join_all("https://www.apple.com", "iphone") https://www.apple.com/iphone :param domain: Domain parts, example: https://www.python.org :param parts: Other parts, example: "/doc", "/py27" :return: url
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/util.py#L36-L60
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ url builder related utility methods. """ from six import PY2 from requests.compat import urlparse from requests.models import PreparedRequest def get_netloc(url): """ Get network location part of an url. For example: https://www.python.org/doc/ -> www.python.org """ parse_result = urlparse(url) netloc = parse_result.netloc return netloc def get_domain(url): """ Get domain part of an url. For example: https://www.python.org/doc/ -> https://www.python.org """ parse_result = urlparse(url) domain = "{schema}://{netloc}".format( schema=parse_result.scheme, netloc=parse_result.netloc) return domain def add_params(endpoint, params): """ Combine query endpoint and params. Example:: >>> add_params("https://www.google.com/search", {"q": "iphone"}) https://www.google.com/search?q=iphone """ p = PreparedRequest() p.prepare(url=endpoint, params=params) if PY2: # pragma: no cover return unicode(p.url) else: # pragma: no cover return p.url
MacHu-GWU/crawlib-project
crawlib/util.py
add_params
python
def add_params(endpoint, params): p = PreparedRequest() p.prepare(url=endpoint, params=params) if PY2: # pragma: no cover return unicode(p.url) else: # pragma: no cover return p.url
Combine query endpoint and params. Example:: >>> add_params("https://www.google.com/search", {"q": "iphone"}) https://www.google.com/search?q=iphone
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/util.py#L63-L77
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ url builder related utility methods. """ from six import PY2 from requests.compat import urlparse from requests.models import PreparedRequest def get_netloc(url): """ Get network location part of an url. For example: https://www.python.org/doc/ -> www.python.org """ parse_result = urlparse(url) netloc = parse_result.netloc return netloc def get_domain(url): """ Get domain part of an url. For example: https://www.python.org/doc/ -> https://www.python.org """ parse_result = urlparse(url) domain = "{schema}://{netloc}".format( schema=parse_result.scheme, netloc=parse_result.netloc) return domain def join_all(domain, *parts): """ Join all url components. Example:: >>> join_all("https://www.apple.com", "iphone") https://www.apple.com/iphone :param domain: Domain parts, example: https://www.python.org :param parts: Other parts, example: "/doc", "/py27" :return: url """ l = list() if domain.endswith("/"): domain = domain[:-1] l.append(domain) for part in parts: for i in part.split("/"): if i.strip(): l.append(i) url = "/".join(l) return url
MacHu-GWU/crawlib-project
crawlib/downloader/requests_downloader.py
RequestsDownloader.get
python
def get(self, url, params=None, cache_cb=None, **kwargs): if self.use_random_user_agent: headers = kwargs.get("headers", dict()) headers.update({Headers.UserAgent.KEY: Headers.UserAgent.random()}) kwargs["headers"] = headers url = add_params(url, params) cache_consumed, value = self.try_read_cache(url) if cache_consumed: response = requests.Response() response.url = url response._content = value else: response = self.ses.get(url, **kwargs) if self.should_we_update_cache(response, cache_cb, cache_consumed): self.cache.set( url, response.content, expire=kwargs.get("cache_expire", self.cache_expire), ) return response
Make http get request. :param url: :param params: :param cache_cb: (optional) a function that taking requests.Response as input, and returns a bool flag, indicate whether should update the cache. :param cache_expire: (optional). :param kwargs: optional arguments.
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/downloader/requests_downloader.py#L103-L138
[ "def add_params(endpoint, params):\n \"\"\"\n Combine query endpoint and params.\n\n Example::\n\n >>> add_params(\"https://www.google.com/search\", {\"q\": \"iphone\"})\n https://www.google.com/search?q=iphone\n \"\"\"\n p = PreparedRequest()\n p.prepare(url=endpoint, params=params)\n if PY2: # pragma: no cover\n return unicode(p.url)\n else: # pragma: no cover\n return p.url\n", "def try_read_cache(self, url, mute=False):\n cache_consumed = False\n value = None\n if self.read_cache_first:\n if url in self.cache:\n value = self.cache[url]\n cache_consumed = True\n else: # pragma: no cover\n if self.alert_when_cache_missing:\n if mute:\n pass\n else:\n msg = \"\\n{} doesn't hit cache!\".format(url)\n sys.stdout.write(msg)\n return cache_consumed, value\n", "def should_we_update_cache(self,\n any_type_response,\n cache_cb,\n cache_consumed_flag):\n \"\"\"\n\n :param any_type_response: any response object.\n :param cache_cb: a call back function taking ``any_type_response``\n as input, and return a boolean value to indicate that whether we\n should update cache.\n :return: bool.\n\n **中文文档**\n\n 1. 如果 ``cache_consumed_flag`` 为 True, 那么说明已经从cache中读取过数据了,\n 再存也没有意义.\n 2. 如果 ``self.always_update_cache`` 为 True, 那么强制更新cache. 我们不用担心\n 发生已经读取过cache, 然后再强制更新的情况, 因为之前我们已经检查过\n ``cache_consumed_flag`` 了.\n 3. 如果没有指定 ``cache_cb`` 函数, 那么默认不更新cache.\n \"\"\"\n if cache_consumed_flag:\n return False\n\n if self.always_update_cache:\n return True\n\n if cache_cb is None:\n return False\n else:\n return cache_cb(any_type_response)\n", "def random(cls):\n return random.choice(cls._all)\n" ]
class RequestsDownloader(DownloaderABC, CacheBackedDownloader): """ Rich feature downloader for making http request. :param use_session: bool, whether you use session to communicate. :param use_tor: bool, whether you use tor network. For information about installation for tor, see https://www.torproject.org/docs/tor-doc-osx.html.en :param tor_port: int, By default, is 9050. :param cache_dir: str, diskCache directory. :param read_cache_first: bool, If true, downloader will try read binary content from cache. :param alert_when_cache_missing: bool, If true, a log message will be displayed when url has not been seen in cache. :param always_update_cache: bool, If true, the response content will be saved to cache anyway. :param cache_expire: int, number seconds to expire. :param use_random_user_agent: bool, if true, a random user agent will be used for http request. """ def __init__(self, use_session=False, use_tor=False, tor_port=9050, cache_dir=None, read_cache_first=False, alert_when_cache_missing=False, always_update_cache=False, cache_expire=None, use_random_user_agent=True, **kwargs): self.use_session = use_session self.use_tor = use_tor self.tor_port = 9050 self.use_random_user_agent = use_random_user_agent # session and tor if (use_session is False) and (use_tor is True): raise ValueError( "You have to use session when you want to use tor.") if use_session is True: self.ses = requests.Session() else: self.ses = requests if use_tor is True: # pragma: no cover self.ses.proxies = { "http": "socks5h://localhost:{tor_port}".format(tor_port=tor_port), "https": "socks5h://localhost:{tor_port}".format(tor_port=tor_port), } super(RequestsDownloader, self).__init__( cache_dir=cache_dir, read_cache_first=read_cache_first, alert_when_cache_missing=alert_when_cache_missing, always_update_cache=always_update_cache, cache_expire=cache_expire, cache_value_type_is_binary=True, cache_compress_level=6, ) def close_session(self): try: self.ses.close() except: pass def close(self): self.close_cache() self.close_session() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def get_html(self, url, params=None, cache_cb=None, decoder_encoding=None, decoder_errors=url_specified_decoder.ErrorsHandle.strict, **kwargs): """ Get html of an url. """ response = self.get( url=url, params=params, cache_cb=cache_cb, **kwargs ) return url_specified_decoder.decode( binary=response.content, url=response.url, encoding=decoder_encoding, errors=decoder_errors, ) def raise_download_oversize_error(self, url, downloaded_size, minimal_size, maximum_size): msg = "resource at %s's size is %s, doesn't fall into %s to %s!" % ( url, repr_data_size(downloaded_size), repr_data_size(minimal_size), repr_data_size(maximum_size), ) raise DownloadOversizeError(msg) def download(self, url, dst, params=None, cache_cb=None, overwrite=False, stream=False, minimal_size=-1, maximum_size=1024 ** 6, **kwargs): """ Download binary content to destination. :param url: binary content url :param dst: path to the 'save_as' file :param cache_cb: (optional) a function that taking requests.Response as input, and returns a bool flag, indicate whether should update the cache. :param overwrite: bool, :param stream: bool, whether we load everything into memory at once, or read the data chunk by chunk :param minimal_size: default -1, if response content smaller than minimal_size, then delete what just download. :param maximum_size: default 1GB, if response content greater than maximum_size, then delete what just download. """ response = self.get( url, params=params, cache_cb=cache_cb, stream=stream, **kwargs ) if not overwrite: # pragma: no cover if os.path.exists(dst): raise OSError("'%s' exists!" % dst) if stream: chunk_size = 1024 * 1024 downloaded_size = 0 with atomic_write(dst, mode="wb") as f: for chunk in response.iter_content(chunk_size): if not chunk: # pragma: no cover break f.write(chunk) downloaded_size += chunk_size if (downloaded_size < minimal_size) or (downloaded_size > maximum_size): self.raise_download_oversize_error( url, downloaded_size, minimal_size, maximum_size) else: content = response.content downloaded_size = sys.getsizeof(content) if (downloaded_size < minimal_size) or (downloaded_size > maximum_size): self.raise_download_oversize_error( url, downloaded_size, minimal_size, maximum_size) else: with atomic_write(dst, mode="wb") as f: f.write(content) def cache_cb_status_code_2xx(self, response): # pragma: no cover if 200 <= response.status_code < 300: return True else: return False
MacHu-GWU/crawlib-project
crawlib/downloader/requests_downloader.py
RequestsDownloader.get_html
python
def get_html(self, url, params=None, cache_cb=None, decoder_encoding=None, decoder_errors=url_specified_decoder.ErrorsHandle.strict, **kwargs): response = self.get( url=url, params=params, cache_cb=cache_cb, **kwargs ) return url_specified_decoder.decode( binary=response.content, url=response.url, encoding=decoder_encoding, errors=decoder_errors, )
Get html of an url.
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/downloader/requests_downloader.py#L140-L161
[ "def decode(self, binary, url, encoding=None, errors=\"strict\"):\n \"\"\"\n Decode binary to string.\n\n :param binary: binary content of a http request.\n :param url: endpoint of the request.\n :param encoding: manually specify the encoding.\n :param errors: errors handle method.\n\n :return: str\n \"\"\"\n if encoding is None:\n domain = util.get_domain(url)\n if domain in self.domain_encoding_table:\n encoding = self.domain_encoding_table[domain]\n html = binary.decode(encoding, errors=errors)\n else:\n html, encoding, confidence = smart_decode(\n binary, errors=errors)\n # cache domain name and encoding\n self.domain_encoding_table[domain] = encoding\n else:\n html = binary.decode(encoding, errors=errors)\n\n return html\n", "def get(self,\n url,\n params=None,\n cache_cb=None,\n **kwargs):\n \"\"\"\n Make http get request.\n\n :param url:\n :param params:\n :param cache_cb: (optional) a function that taking requests.Response\n as input, and returns a bool flag, indicate whether should update the cache.\n :param cache_expire: (optional).\n :param kwargs: optional arguments.\n \"\"\"\n if self.use_random_user_agent:\n headers = kwargs.get(\"headers\", dict())\n headers.update({Headers.UserAgent.KEY: Headers.UserAgent.random()})\n kwargs[\"headers\"] = headers\n\n url = add_params(url, params)\n\n cache_consumed, value = self.try_read_cache(url)\n if cache_consumed:\n response = requests.Response()\n response.url = url\n response._content = value\n else:\n response = self.ses.get(url, **kwargs)\n\n if self.should_we_update_cache(response, cache_cb, cache_consumed):\n self.cache.set(\n url, response.content,\n expire=kwargs.get(\"cache_expire\", self.cache_expire),\n )\n return response\n" ]
class RequestsDownloader(DownloaderABC, CacheBackedDownloader): """ Rich feature downloader for making http request. :param use_session: bool, whether you use session to communicate. :param use_tor: bool, whether you use tor network. For information about installation for tor, see https://www.torproject.org/docs/tor-doc-osx.html.en :param tor_port: int, By default, is 9050. :param cache_dir: str, diskCache directory. :param read_cache_first: bool, If true, downloader will try read binary content from cache. :param alert_when_cache_missing: bool, If true, a log message will be displayed when url has not been seen in cache. :param always_update_cache: bool, If true, the response content will be saved to cache anyway. :param cache_expire: int, number seconds to expire. :param use_random_user_agent: bool, if true, a random user agent will be used for http request. """ def __init__(self, use_session=False, use_tor=False, tor_port=9050, cache_dir=None, read_cache_first=False, alert_when_cache_missing=False, always_update_cache=False, cache_expire=None, use_random_user_agent=True, **kwargs): self.use_session = use_session self.use_tor = use_tor self.tor_port = 9050 self.use_random_user_agent = use_random_user_agent # session and tor if (use_session is False) and (use_tor is True): raise ValueError( "You have to use session when you want to use tor.") if use_session is True: self.ses = requests.Session() else: self.ses = requests if use_tor is True: # pragma: no cover self.ses.proxies = { "http": "socks5h://localhost:{tor_port}".format(tor_port=tor_port), "https": "socks5h://localhost:{tor_port}".format(tor_port=tor_port), } super(RequestsDownloader, self).__init__( cache_dir=cache_dir, read_cache_first=read_cache_first, alert_when_cache_missing=alert_when_cache_missing, always_update_cache=always_update_cache, cache_expire=cache_expire, cache_value_type_is_binary=True, cache_compress_level=6, ) def close_session(self): try: self.ses.close() except: pass def close(self): self.close_cache() self.close_session() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def get(self, url, params=None, cache_cb=None, **kwargs): """ Make http get request. :param url: :param params: :param cache_cb: (optional) a function that taking requests.Response as input, and returns a bool flag, indicate whether should update the cache. :param cache_expire: (optional). :param kwargs: optional arguments. """ if self.use_random_user_agent: headers = kwargs.get("headers", dict()) headers.update({Headers.UserAgent.KEY: Headers.UserAgent.random()}) kwargs["headers"] = headers url = add_params(url, params) cache_consumed, value = self.try_read_cache(url) if cache_consumed: response = requests.Response() response.url = url response._content = value else: response = self.ses.get(url, **kwargs) if self.should_we_update_cache(response, cache_cb, cache_consumed): self.cache.set( url, response.content, expire=kwargs.get("cache_expire", self.cache_expire), ) return response def raise_download_oversize_error(self, url, downloaded_size, minimal_size, maximum_size): msg = "resource at %s's size is %s, doesn't fall into %s to %s!" % ( url, repr_data_size(downloaded_size), repr_data_size(minimal_size), repr_data_size(maximum_size), ) raise DownloadOversizeError(msg) def download(self, url, dst, params=None, cache_cb=None, overwrite=False, stream=False, minimal_size=-1, maximum_size=1024 ** 6, **kwargs): """ Download binary content to destination. :param url: binary content url :param dst: path to the 'save_as' file :param cache_cb: (optional) a function that taking requests.Response as input, and returns a bool flag, indicate whether should update the cache. :param overwrite: bool, :param stream: bool, whether we load everything into memory at once, or read the data chunk by chunk :param minimal_size: default -1, if response content smaller than minimal_size, then delete what just download. :param maximum_size: default 1GB, if response content greater than maximum_size, then delete what just download. """ response = self.get( url, params=params, cache_cb=cache_cb, stream=stream, **kwargs ) if not overwrite: # pragma: no cover if os.path.exists(dst): raise OSError("'%s' exists!" % dst) if stream: chunk_size = 1024 * 1024 downloaded_size = 0 with atomic_write(dst, mode="wb") as f: for chunk in response.iter_content(chunk_size): if not chunk: # pragma: no cover break f.write(chunk) downloaded_size += chunk_size if (downloaded_size < minimal_size) or (downloaded_size > maximum_size): self.raise_download_oversize_error( url, downloaded_size, minimal_size, maximum_size) else: content = response.content downloaded_size = sys.getsizeof(content) if (downloaded_size < minimal_size) or (downloaded_size > maximum_size): self.raise_download_oversize_error( url, downloaded_size, minimal_size, maximum_size) else: with atomic_write(dst, mode="wb") as f: f.write(content) def cache_cb_status_code_2xx(self, response): # pragma: no cover if 200 <= response.status_code < 300: return True else: return False
MacHu-GWU/crawlib-project
crawlib/downloader/requests_downloader.py
RequestsDownloader.download
python
def download(self, url, dst, params=None, cache_cb=None, overwrite=False, stream=False, minimal_size=-1, maximum_size=1024 ** 6, **kwargs): response = self.get( url, params=params, cache_cb=cache_cb, stream=stream, **kwargs ) if not overwrite: # pragma: no cover if os.path.exists(dst): raise OSError("'%s' exists!" % dst) if stream: chunk_size = 1024 * 1024 downloaded_size = 0 with atomic_write(dst, mode="wb") as f: for chunk in response.iter_content(chunk_size): if not chunk: # pragma: no cover break f.write(chunk) downloaded_size += chunk_size if (downloaded_size < minimal_size) or (downloaded_size > maximum_size): self.raise_download_oversize_error( url, downloaded_size, minimal_size, maximum_size) else: content = response.content downloaded_size = sys.getsizeof(content) if (downloaded_size < minimal_size) or (downloaded_size > maximum_size): self.raise_download_oversize_error( url, downloaded_size, minimal_size, maximum_size) else: with atomic_write(dst, mode="wb") as f: f.write(content)
Download binary content to destination. :param url: binary content url :param dst: path to the 'save_as' file :param cache_cb: (optional) a function that taking requests.Response as input, and returns a bool flag, indicate whether should update the cache. :param overwrite: bool, :param stream: bool, whether we load everything into memory at once, or read the data chunk by chunk :param minimal_size: default -1, if response content smaller than minimal_size, then delete what just download. :param maximum_size: default 1GB, if response content greater than maximum_size, then delete what just download.
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/downloader/requests_downloader.py#L176-L233
[ "def get(self,\n url,\n params=None,\n cache_cb=None,\n **kwargs):\n \"\"\"\n Make http get request.\n\n :param url:\n :param params:\n :param cache_cb: (optional) a function that taking requests.Response\n as input, and returns a bool flag, indicate whether should update the cache.\n :param cache_expire: (optional).\n :param kwargs: optional arguments.\n \"\"\"\n if self.use_random_user_agent:\n headers = kwargs.get(\"headers\", dict())\n headers.update({Headers.UserAgent.KEY: Headers.UserAgent.random()})\n kwargs[\"headers\"] = headers\n\n url = add_params(url, params)\n\n cache_consumed, value = self.try_read_cache(url)\n if cache_consumed:\n response = requests.Response()\n response.url = url\n response._content = value\n else:\n response = self.ses.get(url, **kwargs)\n\n if self.should_we_update_cache(response, cache_cb, cache_consumed):\n self.cache.set(\n url, response.content,\n expire=kwargs.get(\"cache_expire\", self.cache_expire),\n )\n return response\n", "def raise_download_oversize_error(self,\n url,\n downloaded_size,\n minimal_size,\n maximum_size):\n msg = \"resource at %s's size is %s, doesn't fall into %s to %s!\" % (\n url,\n repr_data_size(downloaded_size),\n repr_data_size(minimal_size),\n repr_data_size(maximum_size),\n )\n raise DownloadOversizeError(msg)\n" ]
class RequestsDownloader(DownloaderABC, CacheBackedDownloader): """ Rich feature downloader for making http request. :param use_session: bool, whether you use session to communicate. :param use_tor: bool, whether you use tor network. For information about installation for tor, see https://www.torproject.org/docs/tor-doc-osx.html.en :param tor_port: int, By default, is 9050. :param cache_dir: str, diskCache directory. :param read_cache_first: bool, If true, downloader will try read binary content from cache. :param alert_when_cache_missing: bool, If true, a log message will be displayed when url has not been seen in cache. :param always_update_cache: bool, If true, the response content will be saved to cache anyway. :param cache_expire: int, number seconds to expire. :param use_random_user_agent: bool, if true, a random user agent will be used for http request. """ def __init__(self, use_session=False, use_tor=False, tor_port=9050, cache_dir=None, read_cache_first=False, alert_when_cache_missing=False, always_update_cache=False, cache_expire=None, use_random_user_agent=True, **kwargs): self.use_session = use_session self.use_tor = use_tor self.tor_port = 9050 self.use_random_user_agent = use_random_user_agent # session and tor if (use_session is False) and (use_tor is True): raise ValueError( "You have to use session when you want to use tor.") if use_session is True: self.ses = requests.Session() else: self.ses = requests if use_tor is True: # pragma: no cover self.ses.proxies = { "http": "socks5h://localhost:{tor_port}".format(tor_port=tor_port), "https": "socks5h://localhost:{tor_port}".format(tor_port=tor_port), } super(RequestsDownloader, self).__init__( cache_dir=cache_dir, read_cache_first=read_cache_first, alert_when_cache_missing=alert_when_cache_missing, always_update_cache=always_update_cache, cache_expire=cache_expire, cache_value_type_is_binary=True, cache_compress_level=6, ) def close_session(self): try: self.ses.close() except: pass def close(self): self.close_cache() self.close_session() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def get(self, url, params=None, cache_cb=None, **kwargs): """ Make http get request. :param url: :param params: :param cache_cb: (optional) a function that taking requests.Response as input, and returns a bool flag, indicate whether should update the cache. :param cache_expire: (optional). :param kwargs: optional arguments. """ if self.use_random_user_agent: headers = kwargs.get("headers", dict()) headers.update({Headers.UserAgent.KEY: Headers.UserAgent.random()}) kwargs["headers"] = headers url = add_params(url, params) cache_consumed, value = self.try_read_cache(url) if cache_consumed: response = requests.Response() response.url = url response._content = value else: response = self.ses.get(url, **kwargs) if self.should_we_update_cache(response, cache_cb, cache_consumed): self.cache.set( url, response.content, expire=kwargs.get("cache_expire", self.cache_expire), ) return response def get_html(self, url, params=None, cache_cb=None, decoder_encoding=None, decoder_errors=url_specified_decoder.ErrorsHandle.strict, **kwargs): """ Get html of an url. """ response = self.get( url=url, params=params, cache_cb=cache_cb, **kwargs ) return url_specified_decoder.decode( binary=response.content, url=response.url, encoding=decoder_encoding, errors=decoder_errors, ) def raise_download_oversize_error(self, url, downloaded_size, minimal_size, maximum_size): msg = "resource at %s's size is %s, doesn't fall into %s to %s!" % ( url, repr_data_size(downloaded_size), repr_data_size(minimal_size), repr_data_size(maximum_size), ) raise DownloadOversizeError(msg) def cache_cb_status_code_2xx(self, response): # pragma: no cover if 200 <= response.status_code < 300: return True else: return False
MacHu-GWU/crawlib-project
crawlib/pipeline/rds/query_builder.py
finished
python
def finished(finished_status, update_interval, table, status_column, edit_at_column): sql = select([table]).where( and_(*[ status_column >= finished_status, edit_at_column >= x_seconds_before_now(update_interval) ]) ) return sql
Create text sql statement query for sqlalchemy that getting all finished task. :param finished_status: int, status code that greater or equal than this will be considered as finished. :param update_interval: int, the record will be updated every x seconds. :return: sqlalchemy text sql statement. **中文文档** 状态码大于某个值, 并且, 更新时间在最近一段时间以内.
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/pipeline/rds/query_builder.py#L14-L38
[ "def x_seconds_before_now(seconds):\n return datetime.now() - timedelta(seconds=seconds)\n" ]
#!/usr/bin/env python # -*- coding: utf-8 -*- from sqlalchemy import select, and_, or_ try: from ...timestamp import x_seconds_before_now from ...status import FINISHED_STATUS_CODE except: # pragma: no cover from crawlib.timestamp import x_seconds_before_now from crawlib.status import FINISHED_STATUS_CODE def finished_50(update_interval, table, status_column, edit_at_column): # pragma: no cover return finished( FINISHED_STATUS_CODE, update_interval, table, status_column, edit_at_column, ) def unfinished(finished_status, update_interval, table, status_column, edit_at_column): """ Create text sql statement query for sqlalchemy that getting all unfinished task. :param finished_status: int, status code that less than this will be considered as unfinished. :param update_interval: int, the record will be updated every x seconds. :return: sqlalchemy text sql statement. **中文文档** 状态码小于某个值, 或者, 现在距离更新时间已经超过一定阈值. """ sql = select([table]).where( or_(*[ status_column < finished_status, edit_at_column < x_seconds_before_now(update_interval) ]) ) return sql def unfinished_50(update_interval, table, status_column, edit_at_column): # pragma: no cover return unfinished( FINISHED_STATUS_CODE, update_interval, table, status_column, edit_at_column, )
MacHu-GWU/crawlib-project
crawlib/pipeline/rds/query_builder.py
unfinished
python
def unfinished(finished_status, update_interval, table, status_column, edit_at_column): sql = select([table]).where( or_(*[ status_column < finished_status, edit_at_column < x_seconds_before_now(update_interval) ]) ) return sql
Create text sql statement query for sqlalchemy that getting all unfinished task. :param finished_status: int, status code that less than this will be considered as unfinished. :param update_interval: int, the record will be updated every x seconds. :return: sqlalchemy text sql statement. **中文文档** 状态码小于某个值, 或者, 现在距离更新时间已经超过一定阈值.
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/pipeline/rds/query_builder.py#L51-L76
[ "def x_seconds_before_now(seconds):\n return datetime.now() - timedelta(seconds=seconds)\n" ]
#!/usr/bin/env python # -*- coding: utf-8 -*- from sqlalchemy import select, and_, or_ try: from ...timestamp import x_seconds_before_now from ...status import FINISHED_STATUS_CODE except: # pragma: no cover from crawlib.timestamp import x_seconds_before_now from crawlib.status import FINISHED_STATUS_CODE def finished(finished_status, update_interval, table, status_column, edit_at_column): """ Create text sql statement query for sqlalchemy that getting all finished task. :param finished_status: int, status code that greater or equal than this will be considered as finished. :param update_interval: int, the record will be updated every x seconds. :return: sqlalchemy text sql statement. **中文文档** 状态码大于某个值, 并且, 更新时间在最近一段时间以内. """ sql = select([table]).where( and_(*[ status_column >= finished_status, edit_at_column >= x_seconds_before_now(update_interval) ]) ) return sql def finished_50(update_interval, table, status_column, edit_at_column): # pragma: no cover return finished( FINISHED_STATUS_CODE, update_interval, table, status_column, edit_at_column, ) def unfinished_50(update_interval, table, status_column, edit_at_column): # pragma: no cover return unfinished( FINISHED_STATUS_CODE, update_interval, table, status_column, edit_at_column, )
MacHu-GWU/crawlib-project
crawlib/spider.py
execute_one_to_many_job
python
def execute_one_to_many_job(parent_class=None, get_unfinished_kwargs=None, get_unfinished_limit=None, parser_func=None, parser_func_kwargs=None, build_url_func_kwargs=None, downloader_func=None, downloader_func_kwargs=None, post_process_response_func=None, post_process_response_func_kwargs=None, process_item_func_kwargs=None, logger=None, sleep_time=None): # prepare arguments get_unfinished_kwargs = prepare_kwargs(get_unfinished_kwargs) parser_func_kwargs = prepare_kwargs(parser_func_kwargs) build_url_func_kwargs = prepare_kwargs(build_url_func_kwargs) downloader_func_kwargs = prepare_kwargs(downloader_func_kwargs) post_process_response_func_kwargs = prepare_kwargs( post_process_response_func_kwargs) process_item_func_kwargs = prepare_kwargs(process_item_func_kwargs) if post_process_response_func is None: def post_process_response_func(response, **kwargs): pass if not isinstance(logger, SpiderLogger): raise TypeError if sleep_time is None: sleep_time = 0 # do the real job query_set = parent_class.get_all_unfinished(**get_unfinished_kwargs) if get_unfinished_limit is not None: query_set = query_set.limit(get_unfinished_limit) todo = list(query_set) logger.log_todo_volumn(todo) for parent_instance in todo: url = parent_instance.build_url(**build_url_func_kwargs) logger.log_to_crawl_url(url) logger.log_sleeper(sleep_time) time.sleep(sleep_time) try: response_or_html = downloader_func(url, **downloader_func_kwargs) if isinstance(response_or_html, string_types): parser_func_kwargs["html"] = response_or_html else: parser_func_kwargs["response"] = response_or_html post_process_response_func( response_or_html, **post_process_response_func_kwargs) except Exception as e: logger.log_error(e) continue try: parse_result = parser_func( parent=parent_instance, **parser_func_kwargs ) parse_result.process_item(**process_item_func_kwargs) logger.log_status(parse_result) except Exception as e: logger.log_error(e) continue
A standard one-to-many crawling workflow. :param parent_class: :param get_unfinished_kwargs: :param get_unfinished_limit: :param parser_func: html parser function. :param parser_func_kwargs: other keyword arguments for ``parser_func`` :param build_url_func_kwargs: other keyword arguments for ``parent_class().build_url(**build_url_func_kwargs)`` :param downloader_func: a function that taking ``url`` as first arg, make http request and return response/html. :param downloader_func_kwargs: other keyword arguments for ``downloader_func`` :param post_process_response_func: a callback function taking response/html as first argument. You can put any logic in it. For example, you can make it sleep if you detect that you got banned. :param post_process_response_func_kwargs: other keyword arguments for ``post_process_response_func`` :param process_item_func_kwargs: other keyword arguments for ``ParseResult().process_item(**process_item_func_kwargs)`` :param logger: :param sleep_time: default 0, wait time before making each request.
train
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/spider.py#L24-L114
[ "def prepare_kwargs(kwargs):\n if kwargs is None:\n return dict()\n return kwargs\n", "def log_todo_volumn(self, obj_list):\n self.logger.info(\"Job Start!\")\n\n _n_todo = len(obj_list)\n self._n_todo = _n_todo\n self._nth_left_counter = _n_todo\n msg = \"There are {} items in our todo list.\".format(_n_todo)\n self.logger.info(msg)\n", "def log_to_crawl_url(self, url):\n self._nth_left_counter -= 1\n msg = \"Crawling {}, {} left ...\".format(url, self._nth_left_counter)\n self.logger.info(msg)\n", "def log_sleeper(self, sleep_time):\n msg = \"sleep for {} seconds ...\".format(sleep_time)\n self.logger.info(msg, 1)\n", "def log_status(self, parse_result):\n msg = \"status: {}, log: {}\".format(\n parse_result.status, parse_result.log)\n self.logger.info(msg, 1)\n", "def log_error(self, e):\n self.logger.info(str(e), 1)\n", "def get(self,\n url,\n params=None,\n cache_cb=None,\n **kwargs):\n \"\"\"\n Make http get request.\n\n :param url:\n :param params:\n :param cache_cb: (optional) a function that taking requests.Response\n as input, and returns a bool flag, indicate whether should update the cache.\n :param cache_expire: (optional).\n :param kwargs: optional arguments.\n \"\"\"\n if self.use_random_user_agent:\n headers = kwargs.get(\"headers\", dict())\n headers.update({Headers.UserAgent.KEY: Headers.UserAgent.random()})\n kwargs[\"headers\"] = headers\n\n url = add_params(url, params)\n\n cache_consumed, value = self.try_read_cache(url)\n if cache_consumed:\n response = requests.Response()\n response.url = url\n response._content = value\n else:\n response = self.ses.get(url, **kwargs)\n\n if self.should_we_update_cache(response, cache_cb, cache_consumed):\n self.cache.set(\n url, response.content,\n expire=kwargs.get(\"cache_expire\", self.cache_expire),\n )\n return response\n", "def post_process_response_func(response, **kwargs):\n pass\n", "def wrapper(*args, **kwargs):\n try:\n response = kwargs.get(\"response\")\n html = kwargs.get(\"html\")\n soup = kwargs.get(\"soup\")\n except KeyError as e:\n raise NotImplementedError(\n (\"{func} method has to take the keyword syntax input: \"\n \"{e}\").format(func=func, e=e)\n )\n\n if html is None:\n binary = access_binary(response)\n try:\n html = decoder.decode(\n binary=binary,\n url=response.url,\n encoding=encoding,\n errors=errors,\n )\n except Exception as e: # pragma: no cover\n raise DecodeError(str(e))\n kwargs[\"html\"] = html\n\n if soup is None:\n soup = soupify(html)\n kwargs[\"soup\"] = soup\n\n return func(*args, **kwargs)\n" ]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ integrate these modules: - ``crawlib.pipeline.mongodb.orm`` - ``crawlib.data_class`` - ``crawlib.html_parser`` - ``crawlib.logger`` """ import time from six import string_types from crawlib.logger import SpiderLogger def prepare_kwargs(kwargs): if kwargs is None: return dict() return kwargs
ThomasChiroux/attowiki
src/attowiki/git_tools.py
_delta_dir
python
def _delta_dir(): repo = Repo() current_dir = os.getcwd() repo_dir = repo.tree().abspath delta_dir = current_dir.replace(repo_dir, '') if delta_dir: return delta_dir + '/' else: return ''
returns the relative path of the current directory to the git repository. This path will be added the 'filename' path to find the file. It current_dir is the git root, this function returns an empty string. Keyword Arguments: <none> Returns: str -- relative path of the current dir to git root dir empty string if current dir is the git root dir
train
https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/git_tools.py#L32-L52
null
#! /usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2012 Thomas Chiroux # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. # If not, see <http://www.gnu.org/licenses/lgpl-3.0.html> # """git tools functions used in the project.""" __authors__ = [ # alphabetical order by last name 'Thomas Chiroux', ] from datetime import datetime import os from git import Repo, InvalidGitRepositoryError def check_repo(): """checks is local git repo is present or not Keywords Arguments: <none> Returns: boolean -- True if git repo is present, False if not """ try: Repo() except InvalidGitRepositoryError: return False return True def commit(filename): """Commit (git) a specified file This method does the same than a :: $ git commit -a "message" Keyword Arguments: :filename: (str) -- name of the file to commit Returns: <nothing> """ try: repo = Repo() # gitcmd = repo.git # gitcmd.commit(filename) index = repo.index index.commit("Updated file: {0}".format(filename)) except Exception as e: print("exception while commit: %s" % e.message) def add_file_to_repo(filename): """Add a file to the git repo This method does the same than a :: $ git add filename Keyword Arguments: :filename: (str) -- name of the file to commit Returns: <nothing> """ try: repo = Repo() index = repo.index index.add([_delta_dir() + filename]) except Exception as e: print("exception while gitadding file: %s" % e.message) def reset_to_last_commit(): """reset a modified file to his last commit status This method does the same than a :: $ git reset --hard Keyword Arguments: <none> Returns: <nothing> """ try: repo = Repo() gitcmd = repo.git gitcmd.reset(hard=True) except Exception: pass def commit_history(filename): """Retrieve the commit history for a given filename. Keyword Arguments: :filename: (str) -- full name of the file Returns: list of dicts -- list of commit if the file is not found, returns an empty list """ result = [] repo = Repo() for commit in repo.head.commit.iter_parents(paths=_delta_dir() + filename): result.append({'date': datetime.fromtimestamp(commit.committed_date + commit.committer_tz_offset), 'hexsha': commit.hexsha}) return result def read_committed_file(gitref, filename): """Retrieve the content of a file in an old commit and returns it. Ketword Arguments: :gitref: (str) -- full reference of the git commit :filename: (str) -- name (full path) of the file Returns: str -- content of the file """ repo = Repo() commitobj = repo.commit(gitref) blob = commitobj.tree[_delta_dir() + filename] return blob.data_stream.read()
ThomasChiroux/attowiki
src/attowiki/git_tools.py
commit
python
def commit(filename): try: repo = Repo() # gitcmd = repo.git # gitcmd.commit(filename) index = repo.index index.commit("Updated file: {0}".format(filename)) except Exception as e: print("exception while commit: %s" % e.message)
Commit (git) a specified file This method does the same than a :: $ git commit -a "message" Keyword Arguments: :filename: (str) -- name of the file to commit Returns: <nothing>
train
https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/git_tools.py#L71-L91
null
#! /usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2012 Thomas Chiroux # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. # If not, see <http://www.gnu.org/licenses/lgpl-3.0.html> # """git tools functions used in the project.""" __authors__ = [ # alphabetical order by last name 'Thomas Chiroux', ] from datetime import datetime import os from git import Repo, InvalidGitRepositoryError def _delta_dir(): """returns the relative path of the current directory to the git repository. This path will be added the 'filename' path to find the file. It current_dir is the git root, this function returns an empty string. Keyword Arguments: <none> Returns: str -- relative path of the current dir to git root dir empty string if current dir is the git root dir """ repo = Repo() current_dir = os.getcwd() repo_dir = repo.tree().abspath delta_dir = current_dir.replace(repo_dir, '') if delta_dir: return delta_dir + '/' else: return '' def check_repo(): """checks is local git repo is present or not Keywords Arguments: <none> Returns: boolean -- True if git repo is present, False if not """ try: Repo() except InvalidGitRepositoryError: return False return True def add_file_to_repo(filename): """Add a file to the git repo This method does the same than a :: $ git add filename Keyword Arguments: :filename: (str) -- name of the file to commit Returns: <nothing> """ try: repo = Repo() index = repo.index index.add([_delta_dir() + filename]) except Exception as e: print("exception while gitadding file: %s" % e.message) def reset_to_last_commit(): """reset a modified file to his last commit status This method does the same than a :: $ git reset --hard Keyword Arguments: <none> Returns: <nothing> """ try: repo = Repo() gitcmd = repo.git gitcmd.reset(hard=True) except Exception: pass def commit_history(filename): """Retrieve the commit history for a given filename. Keyword Arguments: :filename: (str) -- full name of the file Returns: list of dicts -- list of commit if the file is not found, returns an empty list """ result = [] repo = Repo() for commit in repo.head.commit.iter_parents(paths=_delta_dir() + filename): result.append({'date': datetime.fromtimestamp(commit.committed_date + commit.committer_tz_offset), 'hexsha': commit.hexsha}) return result def read_committed_file(gitref, filename): """Retrieve the content of a file in an old commit and returns it. Ketword Arguments: :gitref: (str) -- full reference of the git commit :filename: (str) -- name (full path) of the file Returns: str -- content of the file """ repo = Repo() commitobj = repo.commit(gitref) blob = commitobj.tree[_delta_dir() + filename] return blob.data_stream.read()
ThomasChiroux/attowiki
src/attowiki/git_tools.py
add_file_to_repo
python
def add_file_to_repo(filename): try: repo = Repo() index = repo.index index.add([_delta_dir() + filename]) except Exception as e: print("exception while gitadding file: %s" % e.message)
Add a file to the git repo This method does the same than a :: $ git add filename Keyword Arguments: :filename: (str) -- name of the file to commit Returns: <nothing>
train
https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/git_tools.py#L94-L112
[ "def _delta_dir():\n \"\"\"returns the relative path of the current directory to the git\n repository.\n This path will be added the 'filename' path to find the file.\n It current_dir is the git root, this function returns an empty string.\n\n Keyword Arguments:\n <none>\n\n Returns:\n str -- relative path of the current dir to git root dir\n empty string if current dir is the git root dir\n \"\"\"\n repo = Repo()\n current_dir = os.getcwd()\n repo_dir = repo.tree().abspath\n delta_dir = current_dir.replace(repo_dir, '')\n if delta_dir:\n return delta_dir + '/'\n else:\n return ''\n" ]
#! /usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2012 Thomas Chiroux # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. # If not, see <http://www.gnu.org/licenses/lgpl-3.0.html> # """git tools functions used in the project.""" __authors__ = [ # alphabetical order by last name 'Thomas Chiroux', ] from datetime import datetime import os from git import Repo, InvalidGitRepositoryError def _delta_dir(): """returns the relative path of the current directory to the git repository. This path will be added the 'filename' path to find the file. It current_dir is the git root, this function returns an empty string. Keyword Arguments: <none> Returns: str -- relative path of the current dir to git root dir empty string if current dir is the git root dir """ repo = Repo() current_dir = os.getcwd() repo_dir = repo.tree().abspath delta_dir = current_dir.replace(repo_dir, '') if delta_dir: return delta_dir + '/' else: return '' def check_repo(): """checks is local git repo is present or not Keywords Arguments: <none> Returns: boolean -- True if git repo is present, False if not """ try: Repo() except InvalidGitRepositoryError: return False return True def commit(filename): """Commit (git) a specified file This method does the same than a :: $ git commit -a "message" Keyword Arguments: :filename: (str) -- name of the file to commit Returns: <nothing> """ try: repo = Repo() # gitcmd = repo.git # gitcmd.commit(filename) index = repo.index index.commit("Updated file: {0}".format(filename)) except Exception as e: print("exception while commit: %s" % e.message) def reset_to_last_commit(): """reset a modified file to his last commit status This method does the same than a :: $ git reset --hard Keyword Arguments: <none> Returns: <nothing> """ try: repo = Repo() gitcmd = repo.git gitcmd.reset(hard=True) except Exception: pass def commit_history(filename): """Retrieve the commit history for a given filename. Keyword Arguments: :filename: (str) -- full name of the file Returns: list of dicts -- list of commit if the file is not found, returns an empty list """ result = [] repo = Repo() for commit in repo.head.commit.iter_parents(paths=_delta_dir() + filename): result.append({'date': datetime.fromtimestamp(commit.committed_date + commit.committer_tz_offset), 'hexsha': commit.hexsha}) return result def read_committed_file(gitref, filename): """Retrieve the content of a file in an old commit and returns it. Ketword Arguments: :gitref: (str) -- full reference of the git commit :filename: (str) -- name (full path) of the file Returns: str -- content of the file """ repo = Repo() commitobj = repo.commit(gitref) blob = commitobj.tree[_delta_dir() + filename] return blob.data_stream.read()