/
meth_lexer.py
47 lines (36 loc) · 1.38 KB
/
meth_lexer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import types
from typing import Type
from sphinx.application import Sphinx
from pygments.lexers.python import NumPyLexer
from inspect import getmembers, isfunction, ismethod, ismodule, isclass
def get_pkg_funcs(pkg: types.ModuleType):
# Get funcs/meths defined in pkg.__init__
funcs_meths = get_funcs(pkg)
modules = getmembers(pkg, ismodule)
# Get funcs/meths of each module in pkg
for name, module in modules:
funcs_meths += get_funcs(module)
classes = getmembers(module, isclass)
for class_name, _class in classes:
funcs_meths += get_funcs(_class)
# Set of all funcs/meths contained in modules used by package
return set(funcs_meths)
def get_funcs(of):
members = getmembers(of, isfunction or ismethod)
return list(dict(members))
class TDKMethLexer(NumPyLexer):
"""Adds syntax highlighting for methods and functions within a python Package
"""
name = 'TDK'
url = 'https://github.com/TDKorn'
aliases = ['tdk']
EXTRA_KEYWORDS = {}
@classmethod
def get_pkg_lexer(cls, pkg_name: str) -> Type["TDKMethLexer"]:
pkg = __import__(pkg_name)
funcs = get_pkg_funcs(pkg)
cls.EXTRA_KEYWORDS = funcs
return cls
def setup(app: Sphinx):
top_level = app.config._raw_config['top_level'] # Set by __init__.setup()
app.add_lexer('python', TDKMethLexer.get_pkg_lexer(top_level))