# lfuns.py         -*- coding: iso-8859-1 -*-
# Copyright (c) 2005 Günter Milde
# Released under the terms of the GNU General Public License (ver. 2 or later)
"""Wrapper to make the lyx functions (LFUNS) directly available to python

Use the list of LFUNS in doc/lfuns.txt to generate python functions calling 
the lfuns via a LyXClient instance. 

Hyphens in an lfun are converted to underscores.

Using an LyXClient instance, it is possible to call a LyX-function via the 
serverpipes.
Example:
    from LyX import lyxserver
    lyx = lyxserver.LyXClient()
    lyx("message", "hi lyx")
    
With lfuns this becomes still easier:
    
    from LyX import lfuns
    lfuns.message("hi lyx")
"""

import sys, os
from LyX import lyxclient, __path__

# the lyxclient used by the lfuns
client = lyxclient.LyXClient()

def wrap_lfun(name, docstring=""):
    """Return python function that calls the lyx function `name`."""
    def lfun(*args):
        return client(name, *args)
    lfun.__doc__ = docstring
    return lfun


def wrap_lfuns(funlist):
    """Wrap all lyx functions listed in `funlist` in the current namespace
    """
    # get the current module as a variable, so we can bind the 
    # functions in the current namespace
    this_module = sys.modules[__name__]
    for line in funlist:
        line = line.strip()
        if not line or line[0] == '#':
            continue
        line = line.split(None, 1) # split at first whitespace, len is 1 or 2
        name = line[0]
        doc  = line[1:] # slice of type list, maybe empty
        synopsis = ["lyx function '%s'"%name]
        # trick: create a list and join
        docstring = '\n\n'.join(synopsis + doc)
        lfun = wrap_lfun(name, docstring)
        setattr(this_module, name.replace("-", "_"), lfun)


# code that runs when the module is imported

txtfile="doc/lfuns.txt"
# normalize txtfile path relative to the LyX package path
txtfile = os.path.join(__path__[0], txtfile)

wrap_lfuns(file(txtfile))

