Skip to content

ddocs.markdown

Core Markdown-to-LaTeX conversion logic plus the Deltares-specific post-processing (UTF-8 tree-character replacement, table column-width fixes, and long-word wrapping in tables). The clean command logic now lives in ddocs.latex.clean.

ddocs.markdown

Convert Markdown documentation to LaTeX (Pandoc + Deltares post-processing).

convert_all_markdown_files

convert_all_markdown_files(input_dir: Path, output_dir: Path, template: Path | None = None, standalone: bool = False, pattern: str = '*.md') -> tuple[int, int]

Convert all Markdown files in a directory to LaTeX.

Parameters:

Name Type Description Default
input_dir Path

Directory containing Markdown files

required
output_dir Path

Directory for output LaTeX files

required
template Path | None

Optional custom Pandoc template

None
standalone bool

If True, generate complete LaTeX documents

False
pattern str

Glob pattern for matching files (default: "*.md")

'*.md'

Returns:

Type Description
tuple[int, int]

Tuple of (successful_conversions, total_files)

Source code in src\ddocs\markdown\markdown.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def convert_all_markdown_files(
    input_dir: Path,
    output_dir: Path,
    template: Path | None = None,
    standalone: bool = False,
    pattern: str = "*.md"
) -> tuple[int, int]:
    """Convert all Markdown files in a directory to LaTeX.

    Args:
        input_dir: Directory containing Markdown files
        output_dir: Directory for output LaTeX files
        template: Optional custom Pandoc template
        standalone: If True, generate complete LaTeX documents
        pattern: Glob pattern for matching files (default: "*.md")

    Returns:
        Tuple of (successful_conversions, total_files)
    """
    # Create output directory if it doesn't exist
    output_dir.mkdir(parents=True, exist_ok=True)

    # Find all markdown files
    md_files = list(input_dir.glob(pattern))

    if not md_files:
        print(f"No markdown files found in {input_dir}")
        return 0, 0

    print(f"Found {len(md_files)} markdown file(s) to convert")


    # Convert each file
    success_count = 0
    for md_file in md_files:
        # Generate output filename
        tex_file = output_dir / f"{md_file.stem}.tex"

        if convert_markdown_to_latex(md_file, tex_file, template, standalone):
            success_count += 1

    return success_count, len(md_files)

convert_markdown_to_latex

convert_markdown_to_latex(input_file: Path, output_file: Path, template: Path | None = None, standalone: bool = False) -> bool

Convert a Markdown file to LaTeX using Pandoc.

Parameters:

Name Type Description Default
input_file Path

Path to input Markdown file

required
output_file Path

Path to output LaTeX file

required
template Path | None

Optional custom Pandoc template

None
standalone bool

If True, generate a complete LaTeX document. If False, generate a fragment that can be included.

False

Returns:

Type Description
bool

True if conversion succeeded, False otherwise

Source code in src\ddocs\markdown\markdown.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
def convert_markdown_to_latex(
    input_file: Path,
    output_file: Path,
    template: Path | None = None,
    standalone: bool = False
) -> bool:
    """Convert a Markdown file to LaTeX using Pandoc.

    Args:
        input_file: Path to input Markdown file
        output_file: Path to output LaTeX file
        template: Optional custom Pandoc template
        standalone: If True, generate a complete LaTeX document.
                   If False, generate a fragment that can be included.

    Returns:
        True if conversion succeeded, False otherwise
    """
    if standalone:
        if not template:
            template = data_dir / 'deltares_template.tex'
    else:
        if not template:
            template = data_dir / 'deltares_fragment_template.tex'

    cmd = [
        'pandoc',
        str(input_file),
        '-o', str(output_file),
        '--from', 'markdown',
        '--to', 'latex',
    ]

    # Add options
    if standalone:
        cmd.append('--standalone')

    if template:
        cmd.extend(['--template', str(template)])

    # Add some useful options for better LaTeX output
    cmd.extend([
        '--listings',  # Use listings package for code blocks
        '--number-sections',  # Number sections
    ])

    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            check=True
        )

        # Post-process the generated LaTeX file to replace UTF-8 characters
        try:
            with open(output_file, 'r', encoding='utf-8') as f:
                content = f.read()

            # Replace UTF-8 box-drawing characters with ASCII
            content = replace_utf8_tree_chars(content)

            # Fix table column widths for better formatting
            content = fix_table_column_widths(content)

            # Wrap long words in tables to enable automatic breaking
            content = wrap_long_words_in_tables(content)

            # If not standalone mode, add necessary commands at the beginning
            if not standalone:
                preamble = (
                    "% Pandoc compatibility commands\n"
                    "\\providecommand{\\tightlist}{%\n"
                    "  \\setlength{\\itemsep}{0pt}\\setlength{\\parskip}{0pt}%\n"
                    "}\n"
                    "\\providecommand{\\passthrough}[1]{#1}\n\n"
                )
                content = preamble + content

            # Write back the modified content
            with open(output_file, 'w', encoding='utf-8') as f:
                f.write(content)
        except Exception as e:
            print(f"  Warning: Could not post-process {output_file.name}: {e}")

        print(f"OK Converted: {input_file.name} -> {output_file.name}")
        return True
    except subprocess.CalledProcessError as e:
        print(f"ERROR converting {input_file.name}:")
        print(f"  {e.stderr}")
        return False

fix_table_column_widths

fix_table_column_widths(content: str) -> str

Fix LaTeX table column widths for better formatting.

Looks for tables and analyzes content to adjust column widths to prevent overlap.

Parameters:

Name Type Description Default
content str

LaTeX content string

required

Returns:

Type Description
str

Content with adjusted table column widths

Source code in src\ddocs\markdown\markdown.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def fix_table_column_widths(content: str) -> str:
    """Fix LaTeX table column widths for better formatting.

    Looks for tables and analyzes content to adjust column widths
    to prevent overlap.

    Args:
        content: LaTeX content string

    Returns:
        Content with adjusted table column widths
    """
    import re

    # Find all longtable environments
    longtable_pattern = r'(\\begin\{longtable\}.*?\\end\{longtable\})'

    def fix_single_table(table_text):
        """Fix a single table by analyzing its content."""

        # Find the column specification line
        col_pattern = r'>\{\\raggedright\\arraybackslash\}p\{\(\\linewidth - (\d+)\\tabcolsep\) \* \\real\{(0\.\d+)\}\}'

        matches = list(re.finditer(col_pattern, table_text))
        if not matches:
            return table_text

        tabcolsep = matches[0].group(1)
        num_cols = len(matches)

        # Check if this table has "Short" and "Long" headers (CLI argument tables)
        if 'Short' in table_text and 'Long' in table_text:
            # CLI argument table
            if num_cols == 5:
                # Check for very long options like --calculate-surge
                if '--calculate-surge' in table_text:
                    # Need extra space for long options
                    new_widths = ['0.16', '0.07', '0.22', '0.10', '0.35']
                else:
                    new_widths = ['0.19', '0.08', '0.18', '0.12', '0.33']
            elif num_cols == 4:
                new_widths = ['0.25', '0.09', '0.22', '0.44']
            else:
                return table_text

        # Check for tables with very long column names
        elif 'Keringstoestand' in table_text or '[open/gesloten]' in table_text:
            # Input file format table with long Dutch column names
            if num_cols == 4:
                # Column, Description, Unit, Required
                # Column has long names like "Keringstoestand[open/gesloten]"
                # Required has "Only with --calculate-surge"
                new_widths = ['0.28', '0.30', '0.12', '0.30']
            else:
                return table_text

        # Check for tables with column headers but not the special cases above
        elif 'Column' in table_text and 'Description' in table_text:
            # Generic column/description table
            if num_cols == 4:
                new_widths = ['0.25', '0.35', '0.15', '0.25']
            else:
                return table_text
        else:
            # Don't modify tables we don't recognize
            return table_text

        # Replace each column width
        result = table_text
        for i, match in enumerate(matches):
            if i < len(new_widths):
                old_spec = match.group(0)
                new_spec = f'>{{\\raggedright\\arraybackslash}}p{{(\\linewidth - {tabcolsep}\\tabcolsep) * \\real{{{new_widths[i]}}}}}'
                result = result.replace(old_spec, new_spec, 1)

        return result

    # Process all longtables
    result = re.sub(longtable_pattern, lambda m: fix_single_table(m.group(0)), content, flags=re.DOTALL)

    return result

replace_utf8_tree_chars

replace_utf8_tree_chars(content: str) -> str

Replace UTF-8 box-drawing characters and symbols with LaTeX equivalents.

Parameters:

Name Type Description Default
content str

LaTeX content string

required

Returns:

Type Description
str

Content with UTF-8 characters replaced

Source code in src\ddocs\markdown\markdown.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def replace_utf8_tree_chars(content: str) -> str:
    """Replace UTF-8 box-drawing characters and symbols with LaTeX equivalents.

    Args:
        content: LaTeX content string

    Returns:
        Content with UTF-8 characters replaced
    """
    # Map UTF-8 box-drawing characters to ASCII equivalents
    replacements = {
        '├': '|',
        '│': '|',
        '└': '`',
        '─': '-',
        '┌': '+',
        '┐': '+',
        '┘': '+',
        '┴': '+',
        '┬': '+',
        '┤': '+',
        '├──': '|--',
        '└──': '`--',
        '│   ': '|   ',
        # Common Unicode symbols to LaTeX commands
        '✓': r'\checkmark',
        '✗': r'\texttimes',
        '⚠': r'\textbf{!}',  # Warning sign
        '⚠️': r'\textbf{!}',  # Warning sign with emoji modifier
        '→': r'$\rightarrow$',
        '←': r'$\leftarrow$',
        '↔': r'$\leftrightarrow$',
        '…': r'\ldots',
        '—': '---',  # em-dash
        '–': '--',   # en-dash
        '"': "``",   # left double quote
        '"': "''",   # right double quote
        ''': "`",    # left single quote
        ''': "'",    # right single quote
        '\ufe0f': '',  # Remove emoji variation selector
    }

    for utf8_char, ascii_char in replacements.items():
        content = content.replace(utf8_char, ascii_char)

    return content

wrap_long_words_in_tables

wrap_long_words_in_tables(content: str) -> str

Wrap very long words in table cells with seqsplit for automatic breaking.

This prevents long words from overflowing table columns by allowing them to break at any character position.

Parameters:

Name Type Description Default
content str

LaTeX content string

required

Returns:

Type Description
str

Content with long words wrapped in seqsplit

Source code in src\ddocs\markdown\markdown.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def wrap_long_words_in_tables(content: str) -> str:
    """Wrap very long words in table cells with seqsplit for automatic breaking.

    This prevents long words from overflowing table columns by allowing them
    to break at any character position.

    Args:
        content: LaTeX content string

    Returns:
        Content with long words wrapped in seqsplit
    """
    import re

    # Find all longtable environments
    longtable_pattern = r'(\\begin\{longtable\}.*?\\end\{longtable\})'

    def wrap_long_words_in_table(table_text):
        """Wrap long words in a single table."""

        # Pattern to find table cell content (between & and \\ or &)
        # This is a simplified approach - wrap text in curly braces that looks problematic

        # Find long words (>15 characters without spaces) that aren't already in commands
        # Exclude content already in \lstinline, \passthrough, math mode, etc.
        def wrap_word(match):
            word = match.group(0)
            # Don't wrap if already in a command or if it's a LaTeX command itself
            return f'\\seqsplit{{{word}}}'

        # Pattern: words with brackets like "Keringstoestand[open/gesloten]"
        # or long words without spaces (>20 chars)
        result = table_text

        # Wrap long column names with brackets (like "Keringstoestand[open/gesloten]")
        # Match pattern: word followed by [text] where total length > 20
        bracket_pattern = r'([A-Za-z]{10,})\{?\[([^\]]+)\]\}?'

        def wrap_bracket_text(match):
            # Check if already wrapped or in a command
            before_match = result[max(0, match.start()-20):match.start()]
            if '\\seqsplit' in before_match or '\\passthrough' in before_match:
                return match.group(0)

            word = match.group(1)
            bracket_content = match.group(2)
            # Return wrapped version
            return f'\\seqsplit{{{word}[{bracket_content}]}}'

        result = re.sub(bracket_pattern, wrap_bracket_text, result)

        return result

    # Process all longtables
    result = re.sub(longtable_pattern, lambda m: wrap_long_words_in_table(m.group(0)), content, flags=re.DOTALL)

    return result

check_pandoc_cli

check_pandoc_cli(args: Namespace | None = None) -> int

CLI handler for the check-pandoc command.

Ensures pandoc is available (downloading it if necessary) and maps the result to a process exit code suitable for sys.exit.

Parameters:

Name Type Description Default
args Namespace | None

Parsed CLI arguments from argparse. Unused -- accepted only so the handler matches the calling convention of the other ddocs subcommand handlers. Defaults to None.

None

Returns:

Type Description
int

0 if pandoc is accessible, 1 otherwise.

Examples:

  • Run the check and use the result as a process exit code:
    >>> import sys
    >>> from ddocs.markdown.pandoc_utils import check_pandoc_cli
    >>> exit_code = check_pandoc_cli()  # doctest: +SKIP
    >>> exit_code  # doctest: +SKIP
    0
    
  • The argparse namespace is accepted but ignored:
    >>> import argparse
    >>> from ddocs.markdown.pandoc_utils import check_pandoc_cli
    >>> ns = argparse.Namespace(command="check-pandoc")
    >>> check_pandoc_cli(ns)  # doctest: +SKIP
    0
    
See Also

check_pandoc_installed: The underlying check-and-install routine.

Source code in src\ddocs\markdown\pandoc_utils.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def check_pandoc_cli(args: argparse.Namespace | None = None) -> int:
    """CLI handler for the ``check-pandoc`` command.

    Ensures pandoc is available (downloading it if necessary) and maps the
    result to a process exit code suitable for ``sys.exit``.

    Args:
        args: Parsed CLI arguments from argparse. Unused -- accepted only so the
            handler matches the calling convention of the other ``ddocs``
            subcommand handlers. Defaults to None.

    Returns:
        0 if pandoc is accessible, 1 otherwise.

    Examples:
        - Run the check and use the result as a process exit code:
            ```python
            >>> import sys
            >>> from ddocs.markdown.pandoc_utils import check_pandoc_cli
            >>> exit_code = check_pandoc_cli()  # doctest: +SKIP
            >>> exit_code  # doctest: +SKIP
            0

            ```
        - The argparse namespace is accepted but ignored:
            ```python
            >>> import argparse
            >>> from ddocs.markdown.pandoc_utils import check_pandoc_cli
            >>> ns = argparse.Namespace(command="check-pandoc")
            >>> check_pandoc_cli(ns)  # doctest: +SKIP
            0

            ```

    See Also:
        check_pandoc_installed: The underlying check-and-install routine.
    """
    return 0 if check_pandoc_installed() else 1

check_pandoc_installed

check_pandoc_installed() -> bool

Ensure pandoc is callable from the command line.

If pandoc is already on PATH this returns immediately. Otherwise the pandoc binary bundled with pypandoc-binary is located and its directory is prepended to this process's PATH so the binary (and any subprocess spawned from this process) can invoke pandoc directly. No network download happens; the PATH change affects only the current process, not the parent shell.

Returns:

Type Description
bool

True if pandoc is accessible after the call, False if the bundled binary

bool

could not be located on PATH.

Examples:

  • Guard a conversion step on pandoc being available:
    >>> from ddocs.markdown.pandoc_utils import check_pandoc_installed
    >>> if check_pandoc_installed():  # doctest: +SKIP
    ...     print("converting")
    converting
    
  • Abort early when pandoc cannot be made available:
    >>> from ddocs.markdown.pandoc_utils import check_pandoc_installed
    >>> ready = check_pandoc_installed()  # doctest: +SKIP
    >>> ready or "could not install pandoc"  # doctest: +SKIP
    True
    
See Also

sanity_check: The PATH-only check this function builds on. check_pandoc_cli: Thin wrapper that maps the result to an exit code.

Source code in src\ddocs\markdown\pandoc_utils.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def check_pandoc_installed() -> bool:
    """Ensure ``pandoc`` is callable from the command line.

    If pandoc is already on ``PATH`` this returns immediately. Otherwise the pandoc
    binary bundled with ``pypandoc-binary`` is located and its directory is prepended
    to this process's ``PATH`` so the binary (and any subprocess spawned from this
    process) can invoke ``pandoc`` directly. No network download happens; the ``PATH``
    change affects only the current process, not the parent shell.

    Returns:
        True if pandoc is accessible after the call, False if the bundled binary
        could not be located on ``PATH``.

    Examples:
        - Guard a conversion step on pandoc being available:
            ```python
            >>> from ddocs.markdown.pandoc_utils import check_pandoc_installed
            >>> if check_pandoc_installed():  # doctest: +SKIP
            ...     print("converting")
            converting

            ```
        - Abort early when pandoc cannot be made available:
            ```python
            >>> from ddocs.markdown.pandoc_utils import check_pandoc_installed
            >>> ready = check_pandoc_installed()  # doctest: +SKIP
            >>> ready or "could not install pandoc"  # doctest: +SKIP
            True

            ```

    See Also:
        sanity_check: The PATH-only check this function builds on.
        check_pandoc_cli: Thin wrapper that maps the result to an exit code.
    """
    installed = sanity_check()
    if not installed:
        pandoc_dir = _get_pandoc_dir()
        if pandoc_dir and os.path.exists(pandoc_dir):
            if pandoc_dir not in os.environ.get("PATH", "").split(os.pathsep):
                os.environ["PATH"] = pandoc_dir + os.pathsep + os.environ.get("PATH", "")
                print(f"Added pandoc to PATH: {pandoc_dir}")

            installed = sanity_check()
            if installed:
                print("Pandoc is now accessible!")

        if not installed:
            print("Warning: bundled Pandoc could not be located on the command line.")

    return installed

sanity_check

sanity_check() -> bool

Check whether a pandoc executable is callable from the command line.

Runs pandoc --version as a subprocess. On success the detected version is printed and True is returned; if pandoc is missing from PATH or the call fails, False is returned. This only inspects what is already reachable -- it never downloads or installs anything.

Returns:

Type Description
bool

True if pandoc --version runs successfully, False otherwise.

Examples:

  • Branch on whether pandoc is available:
    >>> from ddocs.markdown.pandoc_utils import sanity_check
    >>> if sanity_check():  # doctest: +SKIP
    ...     print("ready to convert")
    ... else:
    ...     print("pandoc missing")
    ready to convert
    
  • Use the boolean result to pick a fallback message:
    >>> from ddocs.markdown.pandoc_utils import sanity_check
    >>> available = sanity_check()  # doctest: +SKIP
    >>> "ok" if available else "install pandoc first"  # doctest: +SKIP
    'ok'
    
See Also

check_pandoc_installed: Verify pandoc and download it when it is missing.

Source code in src\ddocs\markdown\pandoc_utils.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def sanity_check() -> bool:
    """Check whether a ``pandoc`` executable is callable from the command line.

    Runs ``pandoc --version`` as a subprocess. On success the detected version is
    printed and ``True`` is returned; if pandoc is missing from ``PATH`` or the
    call fails, ``False`` is returned. This only inspects what is already
    reachable -- it never downloads or installs anything.

    Returns:
        True if ``pandoc --version`` runs successfully, False otherwise.

    Examples:
        - Branch on whether pandoc is available:
            ```python
            >>> from ddocs.markdown.pandoc_utils import sanity_check
            >>> if sanity_check():  # doctest: +SKIP
            ...     print("ready to convert")
            ... else:
            ...     print("pandoc missing")
            ready to convert

            ```
        - Use the boolean result to pick a fallback message:
            ```python
            >>> from ddocs.markdown.pandoc_utils import sanity_check
            >>> available = sanity_check()  # doctest: +SKIP
            >>> "ok" if available else "install pandoc first"  # doctest: +SKIP
            'ok'

            ```

    See Also:
        check_pandoc_installed: Verify pandoc and download it when it is missing.
    """
    try:
        result = subprocess.run(
            ['pandoc', '--version'],
            capture_output=True,
            text=True,
            check=True
        )
        print(f"Found Pandoc: {result.stdout.split()[1]}")
        found = True
    except (subprocess.CalledProcessError, FileNotFoundError):
        found = False
    return found