├── mkdocs_pandoc ├── cli │ ├── __init__.py │ └── mkdocs2pandoc.py ├── filters │ ├── __init__.py │ ├── anchors.py │ ├── toc.py │ ├── include.py │ ├── exclude.py │ ├── chapterhead.py │ ├── headlevels.py │ ├── xref.py │ ├── images.py │ └── tables.py ├── __init__.py ├── exceptions.py └── pandoc_converter.py ├── .gitignore ├── CHANGES ├── setup.py ├── README.md └── LICENSE /mkdocs_pandoc/cli/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /mkdocs_pandoc/filters/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.egg-info 2 | *.pyc 3 | *.swp 4 | -------------------------------------------------------------------------------- /mkdocs_pandoc/__init__.py: -------------------------------------------------------------------------------- 1 | from mkdocs_pandoc.pandoc_converter import PandocConverter 2 | -------------------------------------------------------------------------------- /mkdocs_pandoc/exceptions.py: -------------------------------------------------------------------------------- 1 | class FatalError(Exception): 2 | """Exception wrapper that contains an exit status in addition to a message""" 3 | def __init__(self, message, status=1): 4 | self.message = message 5 | self.status = status 6 | -------------------------------------------------------------------------------- /CHANGES: -------------------------------------------------------------------------------- 1 | 0.2.6: 2 | 3 | * Fixed issues/11 (added support for underwide header rows in tables) 4 | * Fixed issues/9 (added support for list-style pages data structure) 5 | 6 | 0.2.5: 7 | 8 | * Fixed issues/8 (missing empty lines between pages) 9 | * Fixed issues/5 (path delimiter handling on Windows) 10 | * Documented installation on Windows 11 | 12 | 0.2.4: 13 | 14 | * Fixed crash on missing `markdown_extensions` in mkdocs.yml 15 | 16 | 0.2.3: 17 | 18 | * Fixed writing to standard output (broke in 0.2.2). 19 | 20 | 0.2.2: 21 | 22 | * Merged Marcin Klick's Python3 compatibility fixes 23 | * Documented packages required for generating PDF from Pandoc source 24 | 25 | 0.2.1: 26 | 27 | Initial public release. 28 | -------------------------------------------------------------------------------- /mkdocs_pandoc/filters/anchors.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Johannes Grassler 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | 16 | import re 17 | 18 | class AnchorFilter(object): 19 | """Strips out HTML anchor tags""" 20 | 21 | def run(self, lines): 22 | """Filter method""" 23 | ret = [] 24 | for line in lines: 25 | ret.append(re.sub(r'', '', line)) 26 | 27 | return ret 28 | -------------------------------------------------------------------------------- /mkdocs_pandoc/filters/toc.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Johannes Grassler 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | 16 | import re 17 | 18 | class TocFilter(object): 19 | """Strips out python-markdown [TOC] keyword""" 20 | 21 | def run(self, lines): 22 | """Filter method""" 23 | ret = [] 24 | for line in lines: 25 | ret.append(re.sub(r'^\s*\[TOC\]\s*', '', line)) 26 | 27 | return ret 28 | -------------------------------------------------------------------------------- /mkdocs_pandoc/filters/include.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Johannes Grassler 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | """Wrapper for using markdown.markdown_include as simple preprocessor (just 16 | pulls in includes without running the HTML generator)""" 17 | 18 | from __future__ import print_function 19 | import markdown_include.include as incl 20 | 21 | 22 | ### This class is merely a wrapper for providing markdown_include.include 23 | class IncludeFilter(incl.IncludePreprocessor): 24 | def __init__(self, **kwargs): 25 | self.base_path = kwargs.get('base_path', '.') 26 | self.encoding = kwargs.get('encoding', 'utf-8') 27 | -------------------------------------------------------------------------------- /mkdocs_pandoc/filters/exclude.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Johannes Grassler 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | 16 | import re 17 | 18 | class ExcludeFilter(object): 19 | """Removes selected mkdown_include include statements (useful for excluding 20 | a macros include pulled in by every chapter)""" 21 | 22 | def __init__(self, **kwargs): 23 | self.exclude = kwargs.get('exclude', []) 24 | 25 | def run(self, lines): 26 | """Filter method""" 27 | ret = [] 28 | for line in lines: 29 | for exclude in self.exclude: 30 | line = re.sub(r'\{!%s!\}' % exclude, '', line) 31 | ret.append(line) 32 | 33 | return ret 34 | -------------------------------------------------------------------------------- /mkdocs_pandoc/filters/chapterhead.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Johannes Grassler 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | 16 | class ChapterheadFilter(object): 17 | """Filter for adding chapter titles from mkdocs.yml to chapter files""" 18 | 19 | def __init__(self, **kwargs): 20 | self.headlevel = kwargs.get('headlevel', 1) 21 | self.title = kwargs.get('title', None) 22 | if self.title == None: 23 | raise ValueError( 24 | 'Mandatory keyword argument `title` missing.') 25 | 26 | def run(self, lines): 27 | """Filter method""" 28 | 29 | head = [('#' * self.headlevel) + ' ' + self.title, ''] 30 | 31 | head.extend(lines) 32 | 33 | return head 34 | -------------------------------------------------------------------------------- /mkdocs_pandoc/filters/headlevels.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Johannes Grassler 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | 16 | import re 17 | 18 | # TODO: Implement handling for Setext style headers. 19 | 20 | class HeadlevelFilter(object): 21 | """Filter for increasing Markdown header levels (only Atx style)""" 22 | 23 | def __init__(self, pages): 24 | max_offset = 0 25 | 26 | # Determine maximum header level from nesting in mkdocs.yml 27 | for page in pages: 28 | if page['level'] > max_offset: 29 | max_offset = page['level'] 30 | 31 | self.offset = max_offset 32 | 33 | 34 | def run(self, lines): 35 | """Filter method""" 36 | ret = [] 37 | for line in lines: 38 | ret.append(re.sub(r'^#', '#' + ('#' * self.offset), line)) 39 | 40 | return ret 41 | -------------------------------------------------------------------------------- /mkdocs_pandoc/filters/xref.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Johannes Grassler 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | 16 | import re 17 | 18 | # TODO: Implement working cross-references (for now they are simply replaced by 19 | # their link titles). 20 | 21 | class XrefFilter(object): 22 | """Replaces mkdocs style cross-references by just their title""" 23 | 24 | def run(self, lines): 25 | """Filter method""" 26 | ret = [] 27 | for line in lines: 28 | while True: 29 | match = re.search(r'\[(.*?)\]\((.*?\.md)\)', line) 30 | if match != None: 31 | title = match.group(1) 32 | line = re.sub(r'\[.*?\]\(.*?\.md\)', title, line, count=1) 33 | else: 34 | break 35 | ret.append(line) 36 | 37 | return ret 38 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env/python 2 | 3 | from setuptools import setup, find_packages 4 | from codecs import open 5 | from os import path 6 | 7 | here = path.abspath(path.dirname(__file__)) 8 | 9 | long_description = ( 10 | "mkdocs_pandoc is a library of preprocessors that convert mkdocs style markdown " 11 | "(multiple files, with the document structure defined in the mkdocs " 12 | "configuration file mkdocs.yml) into a single markdown document digestible by " 13 | "pandoc. It ships with the command line frontend tool mkdocs2pandoc as its primary " 14 | "user interface." 15 | ) 16 | 17 | setup( 18 | name='mkdocs-pandoc', 19 | 20 | version='0.2.6', 21 | 22 | description='A translator from mkdocs style markdown to pandoc style ' 23 | + 'markdown', 24 | 25 | long_description=long_description, 26 | 27 | url='https://github.com/jgrassler/mkdocs-pandoc', 28 | author='Johannes Grassler', 29 | author_email='johannes@btw23.de', 30 | license='Apache', 31 | 32 | # See https://pypi.python.org/pypi?%3Aaction=list_classifiers 33 | classifiers=[ 34 | 'Development Status :: 3 - Alpha', 35 | 'Intended Audience :: End Users/Desktop', 36 | 'Intended Audience :: Developers', 37 | 'Intended Audience :: Information Technology', 38 | 'Intended Audience :: System Administrators', 39 | 'Topic :: Documentation', 40 | 'Topic :: Text Processing', 41 | 'License :: OSI Approved :: Apache Software License', 42 | 'Programming Language :: Python :: 2.7', 43 | ], 44 | 45 | keywords='mkdoc markdown pandoc', 46 | packages=find_packages(), 47 | 48 | install_requires=['mkdocs>=0.14.0', 49 | 'markdown-include>=0.5.1' 50 | ], 51 | 52 | entry_points={ 53 | 'console_scripts': [ 54 | 'mkdocs2pandoc=mkdocs_pandoc.cli.mkdocs2pandoc:main', 55 | ], 56 | }, 57 | ) 58 | -------------------------------------------------------------------------------- /mkdocs_pandoc/cli/mkdocs2pandoc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # Copyright 2015 Johannes Grassler 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | # mkdocs2pandoc - converts mkdocs documentation into a single pandoc markdown document 18 | 19 | from __future__ import print_function 20 | 21 | import argparse 22 | import codecs 23 | import sys 24 | 25 | import mkdocs.config 26 | from mkdocs_pandoc.exceptions import FatalError 27 | 28 | import mkdocs_pandoc 29 | 30 | def main(): 31 | opts = argparse.ArgumentParser( 32 | description="mdtableconv.py " + 33 | "- converts pipe delimited tables to Pandoc's grid tables") 34 | 35 | opts.add_argument('-e', '--encoding', default='utf-8', 36 | help="Set encoding for input files (default: utf-8)") 37 | 38 | opts.add_argument('-f', '--config-file', default='mkdocs.yml', 39 | help="mkdocs configuration file to use") 40 | 41 | opts.add_argument('-i', '--image-ext', default=None, 42 | help="Extension to substitute image extensions by (default: no replacement)") 43 | 44 | opts.add_argument('-w', '--width', default=100, 45 | help="Width of generated grid tables in characters (default: 100)") 46 | 47 | opts.add_argument('-x', '--exclude', default=None, action='append', 48 | help="Include files to skip (default: none)") 49 | 50 | opts.add_argument('-o', '--outfile', default=None, 51 | help="File to write finished pandoc document to (default: STDOUT)") 52 | 53 | args = opts.parse_args() 54 | 55 | # Python 2 and Python 3 have mutually incompatible approaches to writing 56 | # encoded data to sys.stdout, so we'll have to pick the appropriate one. 57 | 58 | if sys.version_info.major == 2: 59 | out = codecs.getwriter(args.encoding)(sys.stdout) 60 | elif sys.version_info.major >= 3: 61 | out = open(sys.stdout.fileno(), mode='w', encoding=args.encoding, buffering=1) 62 | 63 | try: 64 | pconv = mkdocs_pandoc.PandocConverter( 65 | config_file=args.config_file, 66 | exclude=args.exclude, 67 | image_ext=args.image_ext, 68 | width=args.width, 69 | encoding=args.encoding, 70 | ) 71 | except FatalError as e: 72 | print(e.message, file=sys.stderr) 73 | return(e.status) 74 | if args.outfile: 75 | try: 76 | out = codecs.open(args.outfile, 'w', encoding=args.encoding) 77 | except IOError as e: 78 | print("Couldn't open %s for writing: %s" % (args.outfile, e.strerror), file=sys.stderr) 79 | 80 | for line in pconv.convert(): 81 | out.write(line + '\n') 82 | out.close() 83 | -------------------------------------------------------------------------------- /mkdocs_pandoc/filters/images.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Johannes Grassler 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | 16 | from __future__ import print_function 17 | import os 18 | import re 19 | 20 | 21 | class ImageFilter(object): 22 | """Filter for adjusting image targets (absolute file names, optionally 23 | different extensions""" 24 | def __init__(self, **kwargs): 25 | self.filename = kwargs.get('filename', None) 26 | self.image_path = kwargs.get('image_path', None) 27 | self.adjust_path = kwargs.get('adjust_path', True) 28 | self.image_ext = kwargs.get('image_ext', None) 29 | 30 | def run(self, lines): 31 | """Filter method""" 32 | # Nothing to do in this case 33 | if (not self.adjust_path) and (not self.image_ext): 34 | return lines 35 | 36 | ret = [] 37 | 38 | for line in lines: 39 | processed = {} 40 | while True: 41 | alt = '' 42 | img_name = '' 43 | 44 | match = re.search(r'!\[(.*?)\]\((.*?)\)', line) 45 | 46 | # Make sure there is in fact an image file name 47 | if match: 48 | # Skip images we already processed 49 | if match.group(0) in processed: 50 | break 51 | # Skip URLs 52 | if re.match('\w+://', match.group(2)): 53 | break 54 | alt = match.group(1) 55 | img_name = match.group(2) 56 | else: 57 | break 58 | 59 | if self.image_ext: 60 | img_name = re.sub(r'\.\w+$', '.' + self.image_ext, img_name) 61 | 62 | if self.adjust_path and (self.image_path or self.filename): 63 | # explicitely specified image path takes precedence over 64 | # path relative to chapter 65 | if self.image_path and self.filename: 66 | img_name = os.path.join( 67 | os.path.abspath(self.image_path), 68 | os.path.dirname(self.filename), 69 | img_name) 70 | 71 | # generate image path relative to file name 72 | if self.filename and (not self.image_path): 73 | img_name = os.path.join( 74 | os.path.abspath( 75 | os.path.dirname(self.filename)), 76 | img_name) 77 | 78 | # handle Windows '\', although this adds a small amount of unnecessary work on Unix systems 79 | img_name = img_name.replace(os.path.sep, '/') 80 | 81 | line = re.sub(r'!\[(.*?)\]\((.*?)\)', 82 | '![%s](%s)' % (alt, img_name), line) 83 | 84 | # Mark this image as processed 85 | processed[match.group(0)] = True 86 | 87 | ret.append(line) 88 | 89 | return ret 90 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DESCRIPTION 2 | 3 | This module contains a set of filters for converting 4 | [mkdocs](http://www.mkdocs.org) style markdown documentation into a single 5 | [pandoc(1)](http://www.pandoc.org) flavoured markdown document. This is useful 6 | for 7 | 8 | * Generating PDF or EPUB from your mkdocs documentation 9 | * Generating single-page HTML from your mkdocs documentation 10 | * Converting your mkdocs documentation to other formats, such as asciidoc. 11 | 12 | Aside from the filters the module contains a converter class tying them 13 | together into a coherent whole and the command line converter `mkdocs2pandoc`. 14 | 15 | # PREREQUISITES 16 | 17 | For generating PDF through pandoc(1) you will need to install a few things 18 | pip(1) won't handle, namely pandoc and the somewhat exotic LaTeX packages its 19 | default LaTeX template uses. On a Ubuntu 14.04 system this amounts to the 20 | following packages: 21 | 22 | ``` 23 | fonts-lmodern 24 | lmodern 25 | pandoc 26 | texlive-base 27 | texlive-latex-extra 28 | texlive-fonts-recommended 29 | texlive-latex-recommended 30 | texlive-xetex 31 | ``` 32 | On a Windows system you can get them through 33 | [Chocolatey](https://chocolatey.org/). Once you have Chocolatey up and running 34 | the following commands should leave you with everything you need to create PDF 35 | output from Pandoc: 36 | 37 | ``` 38 | choco install python 39 | choco install pandocpdf 40 | ``` 41 | 42 | # INSTALLATION 43 | 44 | _Note: The following instructions apply to both Unixoid systems and Windows._ 45 | 46 | Make sure, you have [pip](https://pip.pypa.io/en/stable/) installed, then issue 47 | the following command: 48 | 49 | ``` 50 | pip install mkdocs-pandoc 51 | ``` 52 | 53 | This will install the stable version. If you'd like to use the development 54 | version, use 55 | 56 | ``` 57 | pip install git+https://github.com/jgrassler/mkdocs-pandoc 58 | ``` 59 | 60 | instead. Note that if you are behind a proxy, you might need to add the `--proxy` option like this 61 | 62 | ``` 63 | pip --proxy=http[s]://user@mydomain:port install ... 64 | ``` 65 | 66 | # USAGE 67 | 68 | When executed in the directory where your documentation's `mkdoc.yml` and the 69 | `docs/` directory containing the actual documentation resides, `mkdocs2pandoc` 70 | should print one long Markdown document suitable for `pandoc(1)` on standard 71 | output. This works under the following assumptions: 72 | 73 | ## Usage example 74 | 75 | ``` 76 | cd ~/mydocs 77 | mkdocs2pandoc > mydocs.pd 78 | pandoc --toc -f markdown+grid_tables+table_captions -o mydocs.pdf mydocs.pd # Generate PDF 79 | pandoc --toc -f markdown+grid_tables -t epub -o mydocs.epub mydocs.pd # Generate EPUB 80 | ``` 81 | 82 | # BUGS 83 | 84 | The following things are known to be broken: 85 | 86 | * `mdtableconv.py`: Line wrapping in table cells will wrap links, which causes 87 | whitespace to be inserted in their target URLs, at least in PDF output. While 88 | this is a bit of a Pandoc problem, it can and should be fixed in this module. 89 | 90 | * [Internal Hyperlinks](http://www.mkdocs.org/user-guide/writing-your-docs/#internal-hyperlinks) 91 | between markdown documents will be reduced to their link titles, i.e. they 92 | will not be links in the resulting Pandoc document. 93 | 94 | # COPYRIGHT 95 | 96 | (C) 2015 Johannes Grassler 97 | 98 | Licensed under the Apache License, Version 2.0 (the "License"); 99 | you may not use this file except in compliance with the License. 100 | You may obtain a copy of the License at 101 | 102 | http://www.apache.org/licenses/LICENSE-2.0 103 | 104 | You will also find a copy of the License in the file `LICENSE` in the top level 105 | directory of this source code repository. In case the above URL is unreachable 106 | and/or differs from the copy in this file, the file takes precedence. 107 | 108 | Unless required by applicable law or agreed to in writing, software 109 | distributed under the License is distributed on an "AS IS" BASIS, 110 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 111 | See the License for the specific language governing permissions and 112 | limitations under the License. 113 | -------------------------------------------------------------------------------- /mkdocs_pandoc/pandoc_converter.py: -------------------------------------------------------------------------------- 1 | import mkdocs_pandoc.filters.anchors 2 | import mkdocs_pandoc.filters.chapterhead 3 | import mkdocs_pandoc.filters.headlevels 4 | import mkdocs_pandoc.filters.images 5 | import mkdocs_pandoc.filters.exclude 6 | import mkdocs_pandoc.filters.include 7 | import mkdocs_pandoc.filters.tables 8 | import mkdocs_pandoc.filters.toc 9 | import mkdocs_pandoc.filters.xref 10 | 11 | from mkdocs_pandoc.exceptions import FatalError 12 | 13 | import codecs 14 | import os 15 | import yaml 16 | 17 | 18 | class PandocConverter: 19 | """Top level converter class. Instatiate separately for each mkdocs.yml.""" 20 | 21 | def __init__(self, **kwargs): 22 | self.config_file = kwargs.get('config_file', 'mkdocs.yml') 23 | self.encoding = kwargs.get('encoding', 'utf-8') 24 | self.exclude = kwargs.get('exclude', None) 25 | self.filter_tables = kwargs.get('filter_tables', True) 26 | self.filter_xrefs = kwargs.get('filter_xrefs', True) 27 | self.image_ext = kwargs.get('image_ext', None) 28 | self.strip_anchors = kwargs.get('strip_anchors', True) 29 | self.width = kwargs.get('width', 100) 30 | 31 | try: 32 | cfg = codecs.open(self.config_file, 'r', self.encoding) 33 | except IOError as e: 34 | raise FatalError("Couldn't open %s for reading: %s" % (self.config_file, 35 | e.strerror), 1) 36 | 37 | self.config = yaml.load(cfg) 38 | 39 | if not 'docs_dir' in self.config: 40 | self.config['docs_dir'] = 'docs' 41 | 42 | if not 'site_dir' in self.config: 43 | self.config['site_dir'] = 'site' 44 | 45 | # Set filters depending on markdown extensions from config 46 | # Defaults first... 47 | self.filter_include = False 48 | self.filter_toc = False 49 | 50 | # ...then override defaults based on config, if any: 51 | 52 | if 'markdown_extensions' in self.config: 53 | for ext in self.config['markdown_extensions']: 54 | extname = '' 55 | # extension entries may be dicts (for passing extension parameters) 56 | if type(ext) is dict: 57 | extname = list(ext.keys())[0] 58 | if type(ext) is str: 59 | extname = ext 60 | 61 | if extname == 'markdown_include.include': 62 | self.filter_include = True 63 | if extname == 'toc': 64 | self.filter_toc = True 65 | 66 | cfg.close() 67 | 68 | def flatten_pages(self, pages, level=1): 69 | """Recursively flattens pages data structure into a one-dimensional data structure""" 70 | flattened = [] 71 | 72 | for page in pages: 73 | if type(page) is list: 74 | flattened.append( 75 | { 76 | 'file': page[0], 77 | 'title': page[1], 78 | 'level': level, 79 | }) 80 | if type(page) is dict: 81 | if type(list(page.values())[0]) is str: 82 | flattened.append( 83 | { 84 | 'file': list(page.values())[0], 85 | 'title': list(page.keys())[0], 86 | 'level': level, 87 | }) 88 | if type(list(page.values())[0]) is list: 89 | flattened.extend( 90 | self.flatten_pages( 91 | list(page.values())[0], 92 | level + 1) 93 | ) 94 | 95 | 96 | return flattened 97 | 98 | def convert(self): 99 | """User-facing conversion method. Returns pandoc document as a list of 100 | lines.""" 101 | lines = [] 102 | 103 | pages = self.flatten_pages(self.config['pages']) 104 | 105 | f_exclude = mkdocs_pandoc.filters.exclude.ExcludeFilter( 106 | exclude=self.exclude) 107 | 108 | f_include = mkdocs_pandoc.filters.include.IncludeFilter( 109 | base_path=self.config['docs_dir'], 110 | encoding=self.encoding) 111 | 112 | # First, do the processing that must be done on a per-file basis: 113 | # Adjust header levels, insert chapter headings and adjust image paths. 114 | 115 | f_headlevel = mkdocs_pandoc.filters.headlevels.HeadlevelFilter(pages) 116 | 117 | for page in pages: 118 | fname = os.path.join(self.config['docs_dir'], page['file']) 119 | try: 120 | p = codecs.open(fname, 'r', self.encoding) 121 | except IOError as e: 122 | raise FatalError("Couldn't open %s for reading: %s" % (fname, 123 | e.strerror), 1) 124 | f_chapterhead = mkdocs_pandoc.filters.chapterhead.ChapterheadFilter( 125 | headlevel=page['level'], 126 | title=page['title'] 127 | ) 128 | 129 | f_image = mkdocs_pandoc.filters.images.ImageFilter( 130 | filename=page['file'], 131 | image_path=self.config['site_dir'], 132 | image_ext=self.image_ext) 133 | 134 | lines_tmp = [] 135 | 136 | for line in p.readlines(): 137 | lines_tmp.append(line.rstrip()) 138 | 139 | if self.exclude: 140 | lines_tmp = f_exclude.run(lines_tmp) 141 | 142 | if self.filter_include: 143 | lines_tmp = f_include.run(lines_tmp) 144 | 145 | lines_tmp = f_headlevel.run(lines_tmp) 146 | lines_tmp = f_chapterhead.run(lines_tmp) 147 | lines_tmp = f_image.run(lines_tmp) 148 | lines.extend(lines_tmp) 149 | # Add an empty line between pages to prevent text from a previous 150 | # file from butting up against headers in a subsequent file. 151 | lines.append('') 152 | 153 | # Strip anchor tags 154 | if self.strip_anchors: 155 | lines = mkdocs_pandoc.filters.anchors.AnchorFilter().run(lines) 156 | 157 | # Fix cross references 158 | if self.filter_xrefs: 159 | lines = mkdocs_pandoc.filters.xref.XrefFilter().run(lines) 160 | 161 | if self.filter_toc: 162 | lines = mkdocs_pandoc.filters.toc.TocFilter().run(lines) 163 | 164 | if self.filter_tables: 165 | lines = mkdocs_pandoc.filters.tables.TableFilter().run(lines) 166 | 167 | return(lines) 168 | -------------------------------------------------------------------------------- /mkdocs_pandoc/filters/tables.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # Copyright 2015 Johannes Grassler 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | # mdtableconv.py - converts pipe tables to Pandoc's grid tables 18 | 19 | import markdown.extensions.tables as tbl 20 | import markdown.blockparser 21 | import re 22 | import string 23 | import textwrap 24 | 25 | class TableFilter(tbl.TableProcessor): 26 | def __init__(self, width=100, encoding='utf-8'): 27 | self.width = width 28 | self.width_default = 20 # Default column width for rogue rows with more cells than the first row. 29 | 30 | 31 | def blocks(self, lines): 32 | """Groups lines into markdown blocks""" 33 | state = markdown.blockparser.State() 34 | blocks = [] 35 | 36 | # We use three states: start, ``` and '\n' 37 | state.set('start') 38 | 39 | # index of current block 40 | currblock = 0 41 | 42 | for line in lines: 43 | line += '\n' 44 | if state.isstate('start'): 45 | if line[:3] == '```': 46 | state.set('```') 47 | else: 48 | state.set('\n') 49 | blocks.append('') 50 | currblock = len(blocks) - 1 51 | else: 52 | marker = line[:3] # Will capture either '\n' or '```' 53 | if state.isstate(marker): 54 | state.reset() 55 | blocks[currblock] += line 56 | 57 | return blocks 58 | 59 | 60 | def convert_table(self, block): 61 | """"Converts a table to grid table format""" 62 | lines_orig = block.split('\n') 63 | lines_orig.pop() # Remove extra newline at end of block 64 | widest_cell = [] # Will hold the width of the widest cell for each column 65 | widest_word = [] # Will hold the width of the widest word for each column 66 | widths = [] # Will hold the computed widths of grid table columns 67 | 68 | rows = [] # Will hold table cells during processing 69 | lines = [] # Will hold the finished table 70 | 71 | has_border = False # Will be set to True if this is a bordered table 72 | 73 | width_unit = 0.0 # This number is used to divide up self.width according 74 | # to the following formula: 75 | # 76 | # self.width = width_unit * maxwidth 77 | # 78 | # Where maxwidth is the sum over all elements of 79 | # widest_cell. 80 | 81 | # Only process tables, leave everything else untouched 82 | 83 | if not self.test(None, block): 84 | return lines_orig 85 | 86 | if lines_orig[0].startswith('|'): 87 | has_border = True 88 | 89 | # Initialize width arrays 90 | 91 | for i in range(0, len(self._split_row(lines_orig[0], has_border))): 92 | widest_cell.append(0) 93 | widest_word.append(0) 94 | widths.append(0) 95 | 96 | # Parse lines into array of cells and record width of widest cell/word 97 | 98 | for line in lines_orig: 99 | row = self._split_row(line, has_border) 100 | # pad widest_cell to account for under length first row 101 | for i in range(0, len(row) - len(widest_cell)): 102 | widest_cell.append(0) 103 | widest_word.append(0) 104 | widths.append(0) 105 | for i in range(0, len(row)): 106 | # Record cell width 107 | if len(row[i]) > widest_cell[i]: 108 | widest_cell[i] = len(row[i]) 109 | # Record longest word 110 | words = row[i].split() 111 | for word in words: 112 | # Keep URLs from throwing the word length count off too badly. 113 | match = re.match(r'\[(.*?)\]\(.*?\)', word) 114 | if match: 115 | word = match.group(1) 116 | 117 | if len(word) > widest_word[i]: 118 | widest_word[i] = len(word) 119 | rows.append(row) 120 | 121 | # Remove table header divider line from rows 122 | rows.pop(1) 123 | 124 | # Compute first approximation of column widths based on maximum cell width 125 | 126 | for width in widest_cell: 127 | width_unit += float(width) 128 | 129 | width_unit = self.width / width_unit 130 | 131 | for i in range(0, len(widest_cell)): 132 | widths[i] = int(widest_cell[i] * width_unit) 133 | 134 | # Add rounding errors to narrowest column 135 | if sum(widths) < self.width: 136 | widths[widths.index(min(widths))] += self.width - sum(widths) 137 | 138 | # Attempt to correct first approximation of column widths based on 139 | # words that fail to fit their cell's width (if this fails textwrap 140 | # will break up long words but since it does not add hyphens this 141 | # should be avoided) 142 | 143 | for i in range(0, len(widths)): 144 | if widths[i] < widest_word[i]: 145 | offset = widest_word[i] - widths[i] 146 | for j in range(0, len(widths)): 147 | if widths[j] - widest_word[j] >= offset: 148 | widths[j] -= offset 149 | widths[i] += offset 150 | offset = 0 151 | 152 | lines.append(self.ruler_line(widths, linetype='-')) 153 | 154 | # Only add header row if it contains more than just whitespace 155 | if ''.join(rows[0]).strip() != '': 156 | lines.extend(self.wrap_row(widths, rows[0])) 157 | lines.append(self.ruler_line(widths, linetype='=')) 158 | 159 | for row in rows[1:]: 160 | # Skip empty rows 161 | if ''.join(row).strip() == '': 162 | continue 163 | lines.extend(self.wrap_row(widths, row)) 164 | lines.append(self.ruler_line(widths, linetype='-')) 165 | 166 | # Append empty line after table 167 | lines.append('') 168 | 169 | return lines 170 | 171 | 172 | def run(self, lines): 173 | """Filter method: Passes all blocks through convert_table() and returns a list of lines.""" 174 | ret = [] 175 | 176 | for block in self.blocks(lines): 177 | ret.extend(self.convert_table(block)) 178 | 179 | return ret 180 | 181 | 182 | def ruler_line(self, widths, linetype='-'): 183 | """Generates a ruler line for separating rows from each other""" 184 | cells = [] 185 | for w in widths: 186 | cells.append(linetype * (w+2)) 187 | return '+' + '+'.join(cells) + '+' 188 | 189 | 190 | def wrap_row(self, widths, row, width_default=None): 191 | """Wraps a single line table row into a fixed width, multi-line table.""" 192 | lines = [] 193 | longest = 0 # longest wrapped column in row 194 | 195 | if not width_default: 196 | width_default = self.width_default 197 | 198 | # Wrap column contents 199 | for i in range(0, len(row)): 200 | w=width_default # column width 201 | 202 | # Only set column width dynamicaly for non-rogue rows 203 | if i < len(widths): 204 | w = widths[i] 205 | 206 | tw = textwrap.TextWrapper(width=w, break_on_hyphens=False) 207 | # Wrap and left-justify 208 | row[i] = tw.wrap(textwrap.dedent(row[i])) 209 | # Pad with spaces up to to fixed column width 210 | for l in range(0, len(row[i])): 211 | row[i][l] += (w - len(row[i][l])) * ' ' 212 | if len(row[i]) > longest: 213 | longest = len(row[i]) 214 | 215 | # Pad all columns to have the same number of lines 216 | for i in range(0, len(row)): 217 | w=width_default # column width 218 | 219 | # Only set column width dynamicaly for non-rogue rows 220 | if i < len(widths): 221 | w = widths[i] 222 | 223 | if len(row[i]) < longest: 224 | for j in range(len(row[i]), longest): 225 | row[i].append(w * ' ') 226 | 227 | for l in range(0,longest): 228 | line = [] 229 | for c in range(len(row)): 230 | line.append(row[c][l]) 231 | line = '| ' + ' | '.join(line) + ' |' 232 | lines.append(line) 233 | 234 | return lines 235 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2015 Johannes Grassler 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | 192 | --------------------------------------------------------------------------------