import re


def space_in_tables(filestr):
    """
    Add spaces around | in tables such that substitutions $...$ and
    `...` get right.
    """
    pattern = r'^\s*\|.+\| *$'  # table lines
    table_lines = re.findall(pattern, filestr, re.MULTILINE)
    horizontal_rule = r'^\s*\|[-lrc]+\|\s*$'
    inserted_space_around_pipe = False
    for line in table_lines:
        if not re.search(horizontal_rule, line, flags=re.MULTILINE) \
           and (re.search(r'[$`]\|', line) or re.search(r'\|[$`]', line)) \
           and line.count('|') > 2:
            # Found $|, |$, `|, or |` in table line, insert space
            line_wspaces = re.sub(r'([$`])\|', r'\g<1> |', line)
            line_wspaces = re.sub(r'\|([$`])', r'| \g<1>', line_wspaces)
            filestr = filestr.replace(line, line_wspaces)
            inserted_space_around_pipe = True
    return filestr, inserted_space_around_pipe