#! /usr/bin/env python
#####################      A U T H O R        ##########################
#   Copyright (C) 2010 Jack Desert                                     #
#   jackdesert556@gmail.com                                            #
#   http://www.LetsEATalready.com                                      #
#                                                                      #
######################     L I C E N S E      ##########################
#   This program is free software; you can redistribute it and/or      #
#   modify it under the terms of the GNU General Public License        #
#   as published by the Free Software Foundation; either version 2     #
#   of the License, or any later version.                              #
#                                                                      #
#   This program is distributed in the hope that it will be useful,    #
#   but WITHOUT ANY WARRANTY; without even the implied warranty of     #
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      #
#   GNU General Public License for more details.                       #
#                                                                      #
#   You should have received a copy of the GNU General Public License  #
#   along with this program; if not, write to                          #
#                                                                      #
#   the Free Software Foundation, Inc.,                                #
#   59 Temple Place - Suite 330,                                       #
#   Boston, MA   02111-1307, USA.                                      #
#                                                                      #
########################################################################
# LyX(.lyx) --> clipboard(.html)
# This python script takes a LyX file as an input,
# Converts it to TeX
# Convertes that to HTML (no extra tags)
# And copies the HTML to your clipboard for inserting into blog posts
# Here is an article describing how it came about
# Author: Jack Desert
# Author's Website: http://LetsEATalready.com
# Date: March 10, 2010
# From the blog article
# http://letseatalready.com/2010/03/08/lyxblogger-blogging-with-lyx/

#~ Finding a LYX to HTML Converter
#~ My first attempts to solve this problem slowly shifted from excitement
#~ to despair as I tried a few options lurking in the Internet underworld.
#~ The jump from from LYX or from LATEX into html is the tricky part in
#~ this bend of the river. Several solutions are out there, but each has
#~ its quirks:
#~
#~ Elyxer (.lyx to .html)
#~ Elyxer seems to go straight from lyx code to html, skipping the usual
#~ intermediary of LATEX. Footnotes are in a box to the side of the page,
#~ which I kind of like because you see them immediately. But there is no
#~ number indicating where it is referenced from. Ordered lists had this
#~ unusual problem of each item starting with the number "1" instead of
#~ consecutive numbering. I tried to edit the Elyxer source code to fix
#~ the numbering issue but it turned out to be a difficult chore.
#~
#~ HeVeA (.tex to .html) -
#~ HeVeA does a nice job with footnotes, and the numbered lists are
#~ better- but not perfect. Somehow HeVeA manages to insert a bunch of
#~ extra 'br' tags into the html which makes the right edge all raggedy.
#~ And the numbered list issue is also that there's an extra 'br' tag
#~ inside the first item in each list, which looks weird.
#~
#~ LATEX2Html (.tex to .html)
#~ This rendition is quite sophisticated, and it ultimately makes one
#~ little blog into a multiple page linked document. Nice for some things,
#~ but not what I was after.
#~
#~ TtH (.tex to .html)
#~ TtH turned out to be the one that blew all my whistles just the way I
#~ wanted- well almost. The footnotes are immaculate. It even uses the
#~ word footnote to label the footnotes, which is helpful because not
#~ too many people use them in blogs and I don't want to confuse my mother
#~ or anything. It's extremely fast (about a tenth of a second for one of
#~ my three page blogs!) And it comes with a fabulous '-r' option which
#~ automatically leaves off all the rubbish you don't need inside a blog
#~ post- like the head-, title-, and html- tags. The '-r' even leaves off
#~ the link at the bottom that normally would say "translated from TEX to
#~ html using TtH." It was truly intended for pastable html code. :) :) :)
#~
#~ Packaging it All Up - lyxblogger
#~ So I have created lyxblogger, which runs on Linux as it depends on
#~ Xclip. lyxblogger uses LYX (.lyx to .tex), then TtH(.tex to .html) and
#~ finally Xclip(.html to "clipboard") to produce the desired result. So
#~ after saving my .lyx document, I run just run one command
#~ $ lyxblogger file.lyx
#~ and about two seconds later the contents of my lyx file, now in clean-
#~ looking html format, are pasted to my clipboard. All that remains is
#~ to open a new post on wordpress and paste the html right in there.
#~ Voila.
#~ This file comprises the lyxblogger Source Code. To use lyxblogger, save
#~ this file as /usr/bin/lyxblogger, install dependencies using
#~ $ sudo apt-get install lyx tth xclip
#~ and make it executable with
#~ $ chmod +x /usr/bin/lyxblogger
#~ Then invoke
#~ $ lyxblogger my_new_post.lyx


import sys, os
TEMP_DIR = '.temp_latex_665917/'
INPUT_COPY = 'copy_of_input_file.lyx'
error_msg = ''
input_file = sys.argv[1]    # Incoming file name
print 'input_file is:  ' + input_file
# Make sure input file ends in .lyx
if(input_file[-4:] == '.lyx'):
    # Make a temporary directory and work from there
    if (os.path.exists(TEMP_DIR) == False):
        os.system('mkdir %s' % (TEMP_DIR))
    os.system('cp %s %s%s' % (input_file, TEMP_DIR, INPUT_COPY))
    ############Convert from LyX to TeX
    os.system('lyx --export latex %s%s' % (TEMP_DIR, INPUT_COPY))
    int_tex_file = TEMP_DIR + INPUT_COPY[0:-4] + '.tex'
    if(os.path.exists(int_tex_file)):
        ############## Convert from TeX to HTML
        os.system('tth -r %s' % (int_tex_file))
    else:
        error_msg += 'Error: int_tex_file does not exist/n/n'
        print(error_msg)
else:
    error_msg += 'Error: Input file must be of type .lyx/n/n'
    print(error_msg)

OUTPUT_FILE = int_tex_file[0:-4] + '.html'
#~ # EDIT THIS SECTION IF YOU WANT TO TRIM THE OUTPUT (not needed with tth -r)
# Read data from file
f = open(OUTPUT_FILE, 'r')
html = f.read()
f.close()
#~ # Strip off the beginning stuff I don't want
#~ html = html.partition('<!--STARTHTML-->')[2]
#~ # Strip off the end clutter
#~ html = html.partition('<!--ENDHTML-->')[0]

# Remove <div class="p"> tags that exist inside list items
html = html.replace('<div class="p"><!----></div>\n</li>', '</li>')

# Rename remaining <div class="p"> tags
html = html.replace('<div class="p">', '<div class="p_separator">')

# Reinvoke <code> and </code> tags from their escape sequence counterparts
html = html.replace('&lt;code&#62;', '<code>')
html = html.replace('&lt;/code&#62;', '</code>')
# Save footnotes, if there are any, to be added at the end
footnotes = html.partition('<h3>Footnotes:</h3>')
footnotes = footnotes[1] + footnotes[2]
# Strip off cut material using the flag '#! CUT MATERIAL'
html = html.partition('#! CUT MATERIAL')[0]
html = html + footnotes

# Add tags so that html-raw plugin works
html = '<!--start_raw-->' + html + '<!--end_raw-->'
# Write data to file
f = open(OUTPUT_FILE, 'w')
f.write(html)
f.close()

if(error_msg == ''):
    os.system('xclip -i -selection clipboard %s' % (OUTPUT_FILE))
else:
    print '\n\nERROR: \n\nPlease Try Again\n\n'

# Clean up
if (os.path.exists(TEMP_DIR)):
    os.system('rm -r %s' % (TEMP_DIR))
