#!/usr/bin/env python
# lyx-with-client         -*- coding: iso-8859-1 -*-
# Copyright (c) 2005 Gnter Milde
# Released under the terms of the GNU General Public License (ver. 2 or later)
"""
   Start LyX (or connect to running LyX) with a Python LyXClient in the
   background.
   
   This way you can extend LyX with scripted functions.
   
   This example adds a word counting and an external edit function.
   
   TODO: Currently, read-write operations break the listening loop
         --> external_edit does not work
         (I suppose a bug in LyX prevents the polling for new info)
"""

# Needs the LyX-Server running (Set Edit>Preferences>Paths>Server-pipe)
# 
# This example works with the following bindings in your *.bind file:
#     
# # Send a notification to the Lyxserver (lyxpipe.out)
# \bind "F12"   "server-notify"  # external_edit
# \bind "M-w"   "server-notify"  # word_count
# \bind "M-q"   "server-notify"  # kbd-quit

# import sys
import logging

# Customizable values (defaults shown)
# ------------------------------------

from LyX import constants
# default timeout for reading the outpipe (in ms)
# constants.LYXSERVER_POLL_TIMEOUT = 1000 # default 1 s
# constants.LOG_LEVEL = logging.DEBUG # default INFO
constants.LOG_LEVEL = logging.WARN # default INFO

# now import with the set defaults
from LyX.lyxclient import lyx_remote
from LyX.pyfuns import *

# LyXClient instance.
client = lyx_remote()

# Set some bindings 
# (only works, if the relevant keys are bound to "server-notify")
client.bindings["F12"] = external_edit
client.bindings["M-w"] = count_words
client.bindings["M-q"] = kbd_quit

# start listening for notifications (start LyX, if not running)
client.listen(timeout=-1)  # timeout == infinity
