import time
import pypandoc
import os

base_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(base_directory)


def generate(markdown_file_strings, lexicon_file, settings):

    concatenated_markdown = '\n'.join(markdown_file_strings)

    if settings['format'] == 'HTML':
        filename = generate_HTML(concatenated_markdown, lexicon_file,
                                 theme=settings['theme'],
                                 title=settings['grammarTitle'],
                                 subtitle=settings['grammarSubtitle'],
                                 author=settings['author'])

    return filename


def generate_HTML(markdown, lexicon, theme='Default', title='My language',
                  subtitle='A grammar', author='An author'):
    '''Takes a markdown string, a lexicon CSV string, and a number of settings.
    Creates a full HTML document and returns the filename.'''

    # Create a metadata block and add it to the beginning of the markdown
    # string.
    metadata = '% {0}\n% {1}\n% {2}\n'.format(title, author,
                                              time.strftime('%d/%m/%Y'))

    markdown = metadata + markdown

    # Create list of pandoc settings, including theme files
    pandoc_arguments = ['--standalone',
                        '--toc',
                        '--smart',
                        '--html-q-tags']

    html_name = '{0}.html'.format(theme)
    css_name = '{0}.css'.format(theme)

    theme_directory = os.path.join(base_directory, 'themes')

    header_files = [html_name, 'before.html', css_name, 'after.html']

    for filename in header_files:
        full_path = os.path.join(theme_directory, filename)
        pandoc_arguments.append('--include-in-header={0}'.format(full_path))

    # Define the filters to use
    filter_path = os.path.join(base_directory, 'filters', 'new_HTML.py')

    # Get the generated HTML as a string
    html = pypandoc.convert_text(markdown, format='md', to='html',
                                 extra_args=pandoc_arguments,
                                 filters=[filter_path])

    # Save the HTML to a temporary file
    # temp_filename = 'temp/{0}.html'.format(str(time.time()))
    temp_filename = 'grammar.html'
    with open(os.path.join(base_directory, 'temp', temp_filename), 'w') as f:
        f.write(html)

    return temp_filename

@@ -30,16 +30,51 @@
 mport os
+%0Aimport re%0Aimport csv%0Aimport string
 %0A%0Abase_d
@@ -148,29 +148,193 @@
 )))%0A
-print(base_directory)
+%0ADEFINITION_TEMPLATE = '''%0A%3Cspan class=%22word%22%3E$word%0A    %3Cspan class=%22definition%22%3E$local_word ($part)%3Cbr%3E%0A        %3Cspan class=%22full-definition%22%3E$definition%3C/span%3E%0A    %3C/span%3E%0A%3C/span%3E%0A'''
 %0A%0A%0Ad
@@ -2303,24 +2303,141 @@
 ter_path%5D)%0A%0A
+    # Replace dictionary words in the HTML with their definitions%0A    html = load_words_from_lexicon(html, lexicon)%0A%0A
     # Save t
@@ -2663,16 +2663,16 @@
 (html)%0A%0A
-
     retu
@@ -2680,16 +2680,1666 @@
 n temp_filename%0A
+%0A%0Adef load_words_from_lexicon(html, lexicon_string):%0A    '''Replace all words surrounded by double curly braces in the HTML string%0A    (created by the filter) with their dictionary definition according to the%0A    given lexicon.'''%0A%0A    # Read the lexicon string as a CSV file.%0A    lexicon = convert_lexicon(lexicon_string)%0A%0A    match_list = re.findall(r'%7B%7B%5Ba-z%5D*%7D%7D', html, re.I)%0A%0A    for match in match_list:%0A        word = match%5B2:-2%5D%0A        try:%0A            local_word = lexicon%5Bword%5D%5B'local_word'%5D%0A            definition = lexicon%5Bword%5D%5B'definition'%5D%0A            part = lexicon%5Bword%5D%5B'part_of_speech'%5D%0A%0A            definition_block = string.Template(DEFINITION_TEMPLATE)%0A            definition_HTML = definition_block.substitute(word=word,%0A                                                          local_word=local_word,%0A                                                          definition=definition,%0A                                                          part=part)%0A%0A            html = html.replace(match, definition_HTML)%0A%0A        except KeyError:%0A            pass%0A%0A    return html%0A%0A%0Adef convert_lexicon(lexicon_string):%0A    '''Convert a lexicon string (CSV) to a dictionary. Each key is a word and%0A    each value is a dictionary containing information about the word.'''%0A    word_lines = csv.reader(lexicon_string.split('%5Cn'))%0A%0A    lexicon = %7B%7D%0A    for line in word_lines:%0A        try:%0A            word_data = %7B'local_word': line%5B1%5D,%0A                         'definition': line%5B4%5D,%0A                         'part_of_speech': line%5B2%5D%7D%0A            lexicon%5Bline%5B0%5D%5D = word_data%0A        except IndexError:%0A            pass%0A%0A    return lexicon%0A

Add lexicon substitution to HTML output