Turns md links to html
500249
def link2html(text):
    '''  '''
    match = r'\[([^\]]+)\]\(([^)]+)\)'
    replace = r'<a href="\2">\1</a>'
    return re.sub(match, replace, text)
157780
def displayhtml(public_key,
                attrs,
                use_ssl=False,
                error=None):
    """"""

    error_param = ''
    if error:
        error_param = '&error=%s' % error

    if use_ssl:
        server = API_SSL_SERVER
    else:
        server = API_SERVER

    if 'lang' not in attrs:
        attrs['lang'] = get_language()[:2]

    return render_to_string(
        WIDGET_TEMPLATE,
        {'api_server': server,
         'public_key': public_key,
         'error_param': error_param,
         'lang': attrs['lang'],
         'options': mark_safe(json.dumps(attrs, indent=2))
         })
893467
function toHTML()
    {

        // get private attributes
        $attributes = $this->get_attributes('label');

        // if access key needs to be showed
        if (preg_match('/(?<!\\\)\$(.{1})/', $attributes['label'], $matches) > 0) {

            // set the requested accesskey
            $this->set_attributes(array('accesskey' => strtolower($matches[1])));

            // make the accesskey visible
            $attributes['label'] = preg_replace('/\$(.{1})/', '<span class="underline">$1</span>', $attributes['label']);

        }

        return '<label ' . $this->_render_attributes() . '>' . preg_replace('/\\\\\$/', '$', $attributes['label']) . '</label>';

    }
532498
def diff_to_html(cls, details):
        """"""
        changes = []

        # Check that there are details to convert to HMTL
        if not details:
            return ''

        def _frame(value):
            """
            Handle converted `Frame` references where the human identifier is
            stored against the `_str` key.
            """
            if isinstance(value, dict) and '_str' in value:
                return value['_str']
            elif isinstance(value, list):
                return ', '.join([_frame(v) for v in value])
            return str(value)

        # Additions
        fields = sorted(details.get('additions', {}))
        for field in fields:
            new_value = _frame(details['additions'][field])
            if isinstance(new_value, list):
                new_value = ', '.join([_frame(v) for v in new_value])

            change = cls._templates['add'].format(
                field=field,
                new_value=new_value
                )
            changes.append(change)

        # Updates
        fields = sorted(details.get('updates', {}))
        for field in fields:
            original_value = _frame(details['updates'][field][0])
            if isinstance(original_value, list):
                original_value = ', '.join([_frame(v) for v in original_value])

            new_value = _frame(details['updates'][field][1])
            if isinstance(new_value, list):
                new_value = ', '.join([_frame(v) for v in new_value])

            change = cls._templates['update'].format(
                field=field,
                original_value=original_value,
                new_value=new_value
                )
            changes.append(change)

        # Deletions
        fields = sorted(details.get('deletions', {}))
        for field in fields:
            original_value = _frame(details['deletions'][field])
            if isinstance(original_value, list):
                original_value = ', '.join([_frame(v) for v in original_value])

            change = cls._templates['delete'].format(
                field=field,
                original_value=original_value
                )
            changes.append(change)

        return '\n'.join(changes)
181049
def rdlfc_to_html(text, node=None, md=None):
    
    if md is None:
        md = markdown.Markdown()

    # --------------------------------------------------------------------------
    # Remove any common indentation
    # --------------------------------------------------------------------------
    linelist = text.splitlines()
    if linelist:
        text = (
            linelist[0].lstrip()
            + "\n"
            + textwrap.dedent("\n".join(linelist[1:]))
        )
    else:
        text = text.strip()

    # --------------------------------------------------------------------------
    # Parse and replace RDLFormatCode Tags
    # --------------------------------------------------------------------------
    token_spec = [
        ('b', r'\[b\]'),
        ('xb', r'\[/b\]'),
        ('i', r'\[i\]'),
        ('xi', r'\[/i\]'),
        ('u', r'\[u\]'),
        ('xu', r'\[/u\]'),
        ('color', r'\[color=[^\]]+\]'),
        ('xcolor', r'\[/color\]'),
        ('size', r'\[size=[^\]]+\]'),
        ('xsize', r'\[/size\]'),
        ('plainurl', r'\[url\].*?\[/url\]'),
        ('url', r'\[url=[^\]]+\]'),
        ('xurl', r'\[/url\]'),
        ('email', r'\[email\].*?\[/email\]'),
        ('img', r'\[img\].*?\[/img\]'),
        ('code', r'\[code\].*?\[/code\]'),
        ('list', r'\[list(?:=[^\]]+)?\]'),
        ('bullet', r'\[\*\]'),
        ('xlist', r'\[/list\]'),
        ('quote', r'\[quote\]'),
        ('xquote', r'\[/quote\]'),
        ('br', r'\[br\]'),
        ('lb', r'\[lb\]'),
        ('rb', r'\[rb\]'),
        ('p', r'\[p\]'),
        ('xp', r'\[/p\]'),
        ('sp', r'\[sp\]'),
        ('index', r'\[index\]'),
        ('index_parent', r'\[index_parent\]'),
        ('name', r'\[name\]'),
        ('instname', r'\[instname\]'),
    ]
    tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_spec)
    pos = 0
    text_segs = []
    is_first_bullet = []
    list_end_tag = []
    for m in re.finditer(tok_regex, text, re.DOTALL):
        start = m.start()
        end = m.end()

        # Emit prior text
        if start != pos:
            text_segs.append(text[pos:start])
        pos = end

        if m.lastgroup == 'b':
            text_segs.append("<b>")
        elif m.lastgroup == 'xb':
            text_segs.append("</b>")
        elif m.lastgroup == 'i':
            text_segs.append("<i>")
        elif m.lastgroup == 'xi':
            text_segs.append("</i>")
        elif m.lastgroup == 'u':
            text_segs.append("<u>")
        elif m.lastgroup == 'xu':
            text_segs.append("</u>")
        elif m.lastgroup == 'color':
            m2 = re.match(r'\[color=([^\]]+)\]', m.group(0))
            text_segs.append('<span style="color:%s">' % m2.group(1))
        elif m.lastgroup == 'xcolor':
            text_segs.append('</span>')
        elif m.lastgroup == 'size':
            m2 = re.match(r'\[size=([^\]]+)\]', m.group(0))
            text_segs.append('<span style="font-size:%s">' % m2.group(1))
        elif m.lastgroup == 'xsize':
            text_segs.append('</span>')
        elif m.lastgroup == 'plainurl':
            m2 = re.match(r'\[url\](.*?)\[/url\]', m.group(0), re.DOTALL)
            text_segs.append('<a href="%s">%s</a>' % (m2.group(1).strip(), m2.group(1).strip()))
        elif m.lastgroup == 'url':
            m2 = re.match(r'\[url=([^\]]+)\]', m.group(0))
            text_segs.append('<a href="%s">' % m2.group(1).strip())
        elif m.lastgroup == 'xurl':
            text_segs.append('</a>')
        elif m.lastgroup == 'email':
            m2 = re.match(r'\[email\](.*?)\[/email\]', m.group(0), re.DOTALL)
            text_segs.append('<a href="mailto:%s">%s</a>' % (m2.group(1).strip(), m2.group(1).strip()))
        elif m.lastgroup == 'img':
            m2 = re.match(r'\[img\](.*?)\[/img\]', m.group(0), re.DOTALL)
            text_segs.append('<img src="%s">' % m2.group(1))
        elif m.lastgroup == 'code':
            m2 = re.match(r'\[code\](.*?)\s*\[/code\]', m.group(0), re.DOTALL)
            text_segs.append('<code>%s</code>' % m2.group(1))

        elif m.lastgroup == 'list':
            # List start tag
            m2 = re.match(r'\[list(?:=([^\]]+))?\]', m.group(0))
            ltype = m2.group(1)
            if ltype is None:
                text_segs.append('<ul>')
                is_first_bullet.append(True)
                list_end_tag.append('</ul>')
            elif ltype.strip() in ("1", "A", "a", "I", "i"):
                text_segs.append('<ol type="%s">' % ltype.strip())
                is_first_bullet.append(True)
                list_end_tag.append('</ol>')
            else:
                # Bad type. re-emit erronous list tag
                text_segs.append(m.group(0))

        elif m.lastgroup == 'bullet':
            if len(is_first_bullet) == 0: #pylint: disable=len-as-condition
                # Not inside a list tag. Re-emit erronous tag
                text_segs.append("\\[\\*\\]")
            else:
                if not is_first_bullet[-1]:
                    text_segs.append("</li>")
                is_first_bullet[-1] = False
                text_segs.append("<li>")

        elif m.lastgroup == 'xlist':
            if len(list_end_tag) == 0: #pylint: disable=len-as-condition
                # Not inside a list tag. Re-emit erronous tag
                text_segs.append(m.group(0))
            else:
                if not is_first_bullet[-1]:
                    text_segs.append("</li>")
                text_segs.append(list_end_tag[-1])
                is_first_bullet.pop()
                list_end_tag.pop()

        elif m.lastgroup == 'quote':
            text_segs.append('"')
        elif m.lastgroup == 'xquote':
            text_segs.append('"')
        elif m.lastgroup == 'br':
            text_segs.append("<br>")
        elif m.lastgroup == 'lb':
            text_segs.append("\\[")
        elif m.lastgroup == 'rb':
            text_segs.append("\\]")
        elif m.lastgroup == 'p':
            text_segs.append("\n\n<p>")
        elif m.lastgroup == 'xp':
            text_segs.append("</p>")
        elif m.lastgroup == 'sp':
            text_segs.append("&nbsp")
        elif m.lastgroup == 'index':
            if (node is not None) and node.inst.is_array:
                subscripts = []
                if node.current_idx is None:
                    # Index is not known. Use range
                    for dim in node.inst.array_dimensions:
                        subscripts.append("[0:%d]" % dim)
                else:
                    # Index is known
                    for idx in node.current_idx:
                        subscripts.append("[%d]" % idx)
                range_str = "".join(subscripts)
                text_segs.append("<span class='rdlfc-index'>%s</span>" % range_str)
            else:
                text_segs.append(m.group(0))
        elif m.lastgroup == 'index_parent':
            if (node is not None) and (node.parent is not None) and node.parent.inst.is_array:
                subscripts = []
                if node.parent.current_idx is None:
                    # Index is not known. Use range
                    for dim in node.parent.inst.array_dimensions:
                        subscripts.append("[0:%d]" % dim)
                else:
                    # Index is known
                    for idx in node.parent.current_idx:
                        subscripts.append("[%d]" % idx)
                range_str = "".join(subscripts)
                text_segs.append("<span class='rdlfc-index_parent'>%s</span>" % range_str)
            else:
                text_segs.append(m.group(0))
        elif m.lastgroup == 'name':
            if node is not None:
                text_segs.append(node.get_property("name"))
            else:
                text_segs.append(m.group(0))
        elif m.lastgroup == 'instname':
            if node is not None:
                text_segs.append(node.inst.inst_name)
            else:
                text_segs.append(m.group(0))

    # Emit trailing text
    text_segs.append(text[pos:])

    text_out = "".join(text_segs)

    #---------------------------------------------------------------------------
    # Pass through markdown processor
    #---------------------------------------------------------------------------
    text_out = md.reset().convert(text_out)

    return text_out
1007886
def _make_links_absolute(html, base_url):
    
    url_changes = []

    soup = BeautifulSoup(html)
    for tag in soup.find_all('a', href=True):
        old = tag['href']
        fixed = urljoin(base_url, old)
        if old != fixed:
            url_changes.append((old, fixed))
            tag['href'] = fixed

    for tag in soup.find_all('img', src=True):
        old = tag['src']
        fixed = urljoin(base_url, old)
        if old != fixed:
            url_changes.append((old, fixed))
            tag['src'] = fixed

    return mark_safe(six.text_type(soup)), url_changes
52422
def as_html(self, table_class='code-difftable', line_class='line',
                new_lineno_class='lineno old', old_lineno_class='lineno new',
                code_class='code'):
        
        def _link_to_if(condition, label, url):
            """
            Generates a link if condition is meet or just the label if not.
            """

            if condition:
                return '''<a href="%(url)s">%(label)s</a>''' % {'url': url,
                                                                'label': label}
            else:
                return label
        diff_lines = self.prepare()
        _html_empty = True
        _html = []
        _html.append('''<table class="%(table_class)s">\n''' \
                                            % {'table_class': table_class})
        for diff in diff_lines:
            for line in diff['chunks']:
                _html_empty = False
                for change in line:
                    _html.append('''<tr class="%(line_class)s %(action)s">\n''' \
                        % {'line_class': line_class,
                           'action': change['action']})
                    anchor_old_id = ''
                    anchor_new_id = ''
                    anchor_old = "%(filename)s_o%(oldline_no)s" % \
                                {'filename': self._safe_id(diff['filename']),
                                 'oldline_no': change['old_lineno']}
                    anchor_new = "%(filename)s_n%(oldline_no)s" % \
                                {'filename': self._safe_id(diff['filename']),
                                 'oldline_no': change['new_lineno']}
                    cond_old = change['old_lineno'] != '...' and \
                                                        change['old_lineno']
                    cond_new = change['new_lineno'] != '...' and \
                                                        change['new_lineno']
                    if cond_old:
                        anchor_old_id = 'id="%s"' % anchor_old
                    if cond_new:
                        anchor_new_id = 'id="%s"' % anchor_new
                    ###########################################################
                    # OLD LINE NUMBER
                    ###########################################################
                    _html.append('''\t<td %(a_id)s class="%(old_lineno_cls)s">''' \
                                    % {'a_id': anchor_old_id,
                                       'old_lineno_cls': old_lineno_class})

                    _html.append('''<pre>%(link)s</pre>''' \
                        % {'link':
                        _link_to_if(cond_old, change['old_lineno'], '#%s' \
                                                                % anchor_old)})
                    _html.append('''</td>\n''')
                    ###########################################################
                    # NEW LINE NUMBER
                    ###########################################################

                    _html.append('''\t<td %(a_id)s class="%(new_lineno_cls)s">''' \
                                    % {'a_id': anchor_new_id,
                                       'new_lineno_cls': new_lineno_class})

                    _html.append('''<pre>%(link)s</pre>''' \
                        % {'link':
                        _link_to_if(cond_new, change['new_lineno'], '#%s' \
                                                                % anchor_new)})
                    _html.append('''</td>\n''')
                    ###########################################################
                    # CODE
                    ###########################################################
                    _html.append('''\t<td class="%(code_class)s">''' \
                                                % {'code_class': code_class})
                    _html.append('''\n\t\t<pre>%(code)s</pre>\n''' \
                                                % {'code': change['line']})
                    _html.append('''\t</td>''')
                    _html.append('''\n</tr>\n''')
        _html.append('''</table>''')
        if _html_empty:
            return None
        return ''.join(_html)
170777
def html(content, **kwargs):
    """"""
    if hasattr(content, 'read'):
        return content
    elif hasattr(content, 'render'):
        return content.render().encode('utf8')

    return str(content).encode('utf8')
1261205
function addMdExts () {
  var args = Array.prototype.slice.call(arguments);
  return args.reduce(function (memo, item) {
    return memo.concat([
      item + '.md',
      item + '.mkdn',
      item + '.mdown',
      item + '.markdown'
    ]);
  }, []);
}
820926
function stripLinkDefinitions(text) {

        var text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|\Z)/gm, function (wholeMatch,m1,m2,m3,m4) {
            m1 = m1.toLowerCase();
            urls[m1] = encodeAmpsAndAngles(m2);
            if (m3) {
                return m3+m4;
            } else if (m4) {
                titles[m1] = m4.replace(/"/g,"&quot;");
            }
            return "";
        });

        return text;
    }
1277298
def _input_file_as_html_links(cls, session: AppSession):
        ''''''
        scrape_result = session.factory['HTMLScraper'].scrape_file(
            session.args.input_file,
            encoding=session.args.local_encoding or 'utf-8'
        )

        for context in scrape_result.link_contexts:
            yield context.link
443271
function html(obj, indents) {
  indents = indents || 1;

  function indent() {
    return Array(indents).join('  ');
  }

  if ('string' == typeof obj) {
    var str = escape(obj);
    if (urlRegex().test(obj)) {
      str = '<a href="' + str + '">' + str + '</a>';
    }
    return span('string value', '"' + str + '"');
  }

  if ('number' == typeof obj) {
    return span('number', obj);
  }

  if ('boolean' == typeof obj) {
    return span('boolean', obj);
  }

  if (null === obj) {
    return span('null', 'null');
  }

  var buf;

  if (Array.isArray(obj)) {
    ++indents;

    buf = '[\n' + obj.map(function(val){
      return indent() + html(val, indents);
    }).join(',\n');

    --indents;
    buf += '\n' + indent() + ']';
    return buf;
  }

  buf = '{';
  var keys = Object.keys(obj);
  var len = keys.length;
  if (len) buf += '\n';

  ++indents;
  buf += keys.map(function(key){
    var val = obj[key];
    key = '"' + key + '"';
    key = span('string key', key);
    return indent() + key + ': ' + html(val, indents);
  }).join(',\n');
  --indents;

  if (len) buf += '\n' + indent();
  buf += '}';

  return buf;
}
781721
function prettify(md) {
  ast(md);
  const render = md.render;

  md.render = function(str, options) {
    if (typeof str !== 'string') {
      throw new TypeError('expected a string');
    }
    str = str.split(/\]\[\]\s*\n\s*\[/).join('][]\n\n[');
    return render.call(md, str, options);
  };

  md.renderer.renderInline = function(tokens, options, env) {
    const _rules = rules;
    let len = tokens.length, i = 0;
    let str = '';

    while (len--) {
      str += _rules[tokens[i].type](tokens, i++, options, env, this);
    }
    return str;
  };

  md.renderer.render = function(tokens, options, env) {
    let _rules = rules;
    let len = tokens.length, i = -1;
    let str = '';

    while (++i < len) {
      let token = tokens[i];
      if (token.type === 'inline') {
        str += this.renderInline(token.children, options, env);
      } else {
        str += _rules[token.type](tokens, i, options, env, this);
      }
    }

    if (options.condense !== false) {
      str = str.split(/(?:\r\n|\n){2,}/).join('\n\n');
    }

    let newline = '\n';
    if (options.newline === false) {
      newline = '';
    }
    if (typeof options.newline === 'string') {
      newline = options.newline;
    }
    str = str.trim() + newline;
    return str;
  };
}
1345854
def as_html(self, path=""):
        
        if path not in self.top_level_links:
            raise StateError("Unknown path")

        header = """
        <html>
            <head>
                <title>VPC-router state</title>
            </head>
            <body>
                <h3>VPC-router state</h3>
                <hr>
                <font face="courier">
        """

        footer = """
                </font>
            </body>
        </html>
        """

        rep = self.get_state_repr(path)

        def make_links(rep):
            # Recursively create clickable links for _href elements
            for e, v in rep.items():
                if e == "_href":
                    v = '<a href=%s>%s</a>' % (v, v)
                    rep[e] = v
                else:
                    if type(v) == dict:
                        make_links(v)

        make_links(rep)

        rep_str_lines = json.dumps(rep, indent=4).split("\n")
        buf = []
        for l in rep_str_lines:
            # Replace leading spaces with '&nbsp;'
            num_spaces = len(l) - len(l.lstrip())
            l = "&nbsp;" * num_spaces + l[num_spaces:]
            buf.append(l)

        return "%s%s%s" % (header, "<br>\n".join(buf), footer)
527450
def linkify_url(value):
    """"""

    value = value.strip()

    rjs = r"[\s]*(&#x.{1,7})?".join(list("javascript:"))
    rvb = r"[\s]*(&#x.{1,7})?".join(list("vbscript:"))
    re_scripts = re.compile(f"({rjs})|({rvb})", re.IGNORECASE)

    value = re_scripts.sub("", value)

    url = value
    if not url.startswith("http://") and not url.startswith("https://"):
        url = "http://" + url

    url = parse.urlsplit(url).geturl()
    if '"' in url:
        url = url.split('"')[0]
    if "<" in url:
        url = url.split("<")[0]

    if value.startswith("http://"):
        value = value[len("http://") :]
    elif value.startswith("https://"):
        value = value[len("https://") :]

    if value.count("/") == 1 and value.endswith("/"):
        value = value[0:-1]

    return '<a href="{}">{}</a>&nbsp;<i class="fa fa-external-link"></i>'.format(
        url, value
    )
901761
def html! query, operations = [], &block
      operations.unshift :to_html
      at! query, operations, &block
    end
239036
def clean_html(context, data):
    """"""
    doc = _get_html_document(context, data)
    if doc is None:
        context.emit(data=data)
        return

    remove_paths = context.params.get('remove_paths')
    for path in ensure_list(remove_paths):
        for el in doc.findall(path):
            el.drop_tree()

    html_text = html.tostring(doc, pretty_print=True)
    content_hash = context.store_data(html_text)
    data['content_hash'] = content_hash
    context.emit(data=data)