Skip to content

allow include by section? #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 14 additions & 11 deletions markdown_include/include.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@
from markdown.extensions import Extension
from markdown.preprocessors import Preprocessor

INC_SYNTAX = re.compile(r'\{!\s*(.+?)\s*!\}')
HEADING_SYNTAX = re.compile( '^#+' )
INC_SYNTAX = re.compile(r'\{!\s*(.+?)(#[\w\s-]+?)?\s*!\}')
HEADING_SYNTAX = re.compile(r'^#+')


class MarkdownInclude(Extension):
Expand Down Expand Up @@ -77,27 +77,28 @@ def __init__(self, md, config):

def run(self, lines):
done = False
bonusHeading = ''
bonus_heading = ''
while not done:
for loc, line in enumerate(lines):
m = INC_SYNTAX.search(line)

if m:
filename = m.group(1)
file_section = m.group(2) if len(m.groups()) > 1 else None
filename = os.path.expanduser(filename)
if not os.path.isabs(filename):
filename = os.path.normpath(
os.path.join(self.base_path,filename)
os.path.join(self.base_path, filename)
)
try:
with open(filename, 'r', encoding=self.encoding) as r:
with open(filename, encoding=self.encoding) as r:
text = r.readlines()

except Exception as e:
if not self.throwException:
print('Warning: could not find file {}. Ignoring '
'include statement. Error: {}'.format(filename, e))
lines[loc] = INC_SYNTAX.sub('',line)
lines[loc] = INC_SYNTAX.sub('', line)
break
else:
raise e
Expand All @@ -109,29 +110,31 @@ def run(self, lines):
# Strip the newline, and optionally increase header depth
if self.inheritHeadingDepth or self.headingOffset:
if HEADING_SYNTAX.search(text[i]):
if file_section and file_section not in text[i].strip():
continue
text[i] = text[i].rstrip('\r\n')
if self.inheritHeadingDepth:
text[i] = bonusHeading + text[i]
text[i] = bonus_heading + text[i]
if self.headingOffset:
text[i] = '#' * self.headingOffset + text[i]
else:
text[i] = text[i].rstrip('\r\n')

text[0] = line_split[0] + text[0]
text[-1] = text[-1] + line_split[2]
text[-1] += line_split[2]
lines = lines[:loc] + text + lines[loc+1:]
break

else:
h = HEADING_SYNTAX.search(line)
if h:
headingDepth = len(h.group(0))
bonusHeading = '#' * headingDepth
heading_depth = len(h.group(0))
bonus_heading = '#' * heading_depth

else:
done = True
return lines


def makeExtension(*args,**kwargs):
def makeExtension(*args, **kwargs):
return MarkdownInclude(kwargs)