Skip to content

Commit

Permalink
feat: add more type hints
Browse files Browse the repository at this point in the history
  • Loading branch information
lepture committed Jun 8, 2023
1 parent f0fd85b commit 26a6974
Show file tree
Hide file tree
Showing 7 changed files with 34 additions and 30 deletions.
2 changes: 1 addition & 1 deletion docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Here are the list of API reference; it might be helpful for developers.
Basic
-----

.. function:: html(text)
.. function:: html(text: str)

:param text: markdown formatted text

Expand Down
6 changes: 3 additions & 3 deletions src/mistune/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from .plugins import import_plugin


def create_markdown(escape=True, hard_wrap=False, renderer='html', plugins=None):
def create_markdown(escape: bool=True, hard_wrap: bool=False, renderer='html', plugins=None) -> Markdown:
"""Create a Markdown instance based on the given condition.
:param escape: Boolean. If using html renderer, escape html.
Expand All @@ -43,7 +43,7 @@ def create_markdown(escape=True, hard_wrap=False, renderer='html', plugins=None)
return Markdown(renderer=renderer, inline=inline, plugins=plugins)


html = create_markdown(
html: Markdown = create_markdown(
escape=False,
plugins=['strikethrough', 'footnotes', 'table', 'speedup']
)
Expand All @@ -52,7 +52,7 @@ def create_markdown(escape=True, hard_wrap=False, renderer='html', plugins=None)
__cached_parsers = {}


def markdown(text, escape=True, renderer='html', plugins=None):
def markdown(text, escape=True, renderer='html', plugins=None) -> str:
key = (escape, renderer, plugins)
if key in __cached_parsers:
return __cached_parsers[key](text)
Expand Down
23 changes: 12 additions & 11 deletions src/mistune/core.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import re
from typing import Dict, Any

_LINE_END = re.compile(r'\n|$')

Expand All @@ -23,35 +24,35 @@ def __init__(self, parent=None):
else:
self.env = {'ref_links': {}}

def child_state(self, src):
def child_state(self, src: str):
child = self.__class__(self)
child.process(src)
return child

def process(self, src):
def process(self, src: str):
self.src = src
self.cursor_max = len(src)

def find_line_end(self):
m = _LINE_END.search(self.src, self.cursor)
return m.end()

def get_text(self, end_pos):
def get_text(self, end_pos: int):
return self.src[self.cursor:end_pos]

def last_token(self):
if self.tokens:
return self.tokens[-1]

def prepend_token(self, token):
def prepend_token(self, token: Dict[str, Any]):
"""Insert token before the last token."""
self.tokens.insert(len(self.tokens) - 1, token)

def append_token(self, token):
def append_token(self, token: Dict[str, Any]):
"""Add token to the end of token list."""
self.tokens.append(token)

def add_paragraph(self, text):
def add_paragraph(self, text: str):
last_token = self.last_token()
if last_token and last_token['type'] == 'paragraph':
last_token['text'] += text
Expand All @@ -76,7 +77,7 @@ def depth(self):

class InlineState:
"""The state to save inline parser's tokens."""
def __init__(self, env):
def __init__(self, env: Dict[str, Any]):
self.env = env
self.src = ''
self.tokens = []
Expand All @@ -85,11 +86,11 @@ def __init__(self, env):
self.in_emphasis = False
self.in_strong = False

def prepend_token(self, token):
def prepend_token(self, token: Dict[str, Any]):
"""Insert token before the last token."""
self.tokens.insert(len(self.tokens) - 1, token)

def append_token(self, token):
def append_token(self, token: Dict[str, Any]):
"""Add token to the end of token list."""
self.tokens.append(token)

Expand Down Expand Up @@ -133,7 +134,7 @@ def compile_sc(self, rules=None):
self.__sc[key] = sc
return sc

def register(self, name, pattern, func, before=None):
def register(self, name: str, pattern, func, before=None):
"""Register a new rule to parse the token. This method is usually used to
create a new plugin.
Expand Down Expand Up @@ -173,7 +174,7 @@ class BaseRenderer(object):
def __init__(self):
self.__methods = {}

def register(self, name, method):
def register(self, name: str, method):
"""Register a render method for the named token. For example::
def render_wiki(renderer, key, title):
Expand Down
4 changes: 2 additions & 2 deletions src/mistune/inline_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ class InlineParser(Parser):
'linebreak',
)

def __init__(self, hard_wrap=False):
def __init__(self, hard_wrap: bool=False):
super(InlineParser, self).__init__()

self.hard_wrap = hard_wrap
Expand Down Expand Up @@ -283,7 +283,7 @@ def parse_codespan(self, m: re.Match, state: InlineState) -> int:
marker = m.group(0)
# require same marker with same length at end

pattern = re.compile(r'(.*?(?:[^`]))' + marker + r'(?!`)', re.S)
pattern = re.compile(r'(.*?[^`])' + marker + r'(?!`)', re.S)

pos = m.end()
m = pattern.match(state.src, pos)
Expand Down
9 changes: 6 additions & 3 deletions src/mistune/markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,19 @@ class Markdown:
:param inline: inline level syntax parser
:param plugins: mistune plugins to use
"""
def __init__(self, renderer=None, block=None, inline=None, plugins=None):
def __init__(self, renderer=None,
block: Optional[BlockParser]=None,
inline: Optional[InlineParser]=None,
plugins=None):
if block is None:
block = BlockParser()

if inline is None:
inline = InlineParser()

self.renderer = renderer
self.block = block
self.inline = inline
self.block: BlockParser = block
self.inline: InlineParser = inline
self.before_parse_hooks = []
self.before_render_hooks = []
self.after_render_hooks = []
Expand Down
2 changes: 1 addition & 1 deletion src/mistune/renderers/markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from ..core import BaseRenderer, BlockState
from ..util import strip_end

fenced_re = re.compile(r'^(?:`|~)+', re.M)
fenced_re = re.compile(r'^[`~]+', re.M)


class MarkdownRenderer(BaseRenderer):
Expand Down
18 changes: 9 additions & 9 deletions src/mistune/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,19 @@
_expand_tab_re = re.compile(r'^( {0,3})\t', flags=re.M)


def expand_leading_tab(text, width=4):
def expand_leading_tab(text: str, width=4):
def repl(m):
s = m.group(1)
return s + ' ' * (width - len(s))
return _expand_tab_re.sub(repl, text)


def expand_tab(text, space=' '):
def expand_tab(text: str, space: str=' '):
repl = r'\1' + space
return _expand_tab_re.sub(repl, text)


def escape(s, quote=True):
def escape(s: str, quote: bool=True):
"""Escape characters of ``&<>``. If quote=True, ``"`` will be
converted to ``&quote;``."""
s = s.replace("&", "&amp;")
Expand All @@ -29,7 +29,7 @@ def escape(s, quote=True):
return s


def escape_url(link):
def escape_url(link: str):
"""Escape URL for safety."""
safe = (
':/?#@' # gen-delims - '[]' (rfc3986)
Expand All @@ -39,12 +39,12 @@ def escape_url(link):
return escape(quote(unescape(link), safe=safe))


def safe_entity(s):
def safe_entity(s: str):
"""Escape characters for safety."""
return escape(unescape(s))


def unikey(s):
def unikey(s: str):
"""Generate a unique key for links and footnotes."""
key = ' '.join(s.split()).strip()
return key.lower().upper()
Expand All @@ -57,7 +57,7 @@ def unikey(s):
)


def unescape(s):
def unescape(s: str):
"""
Copy from `html.unescape`, but `_charref` is different. CommonMark
does not accept entity references without a trailing semicolon
Expand All @@ -70,12 +70,12 @@ def unescape(s):
_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')


def striptags(s):
def striptags(s: str):
return _striptags_re.sub('', s)


_strip_end_re = re.compile(r'\n\s+$')


def strip_end(src):
def strip_end(src: str):
return _strip_end_re.sub('\n', src)

0 comments on commit 26a6974

Please sign in to comment.