On  7.04.05, [EMAIL PROTECTED] wrote:
> On Thu, 7 Apr 2005, G. Milde wrote:
> > On  6.04.05, Alfredo Braunstein wrote:
> > > Geoffrey Lloyd wrote:
> > 
> > > > ... is there a list of all the in built keyboard shortcuts for lyx.
> > 
> > The LyX Wiki has even a list of such lists at
> > 
> >    http://wiki.lyx.org/LyX/KeyboardShortcuts   # Group LyX instead of Tips!
> > 
> > and a tcsh script to extract such a list from your bind files.

> (The idea was that it could be used to generate a nice list of the
> keybindings for each new version of lyx - not that the keybindings
> change that often though).

But such a script is nice to get a list of your customised keybindings
too. 

For people (like me) without tcsh, I'll append a python script
that parses the bind files recursively. The output is a plain ASCII
list, but it also provides 2 functions 
    where_is(lfun)
    get_binding(key)
to grep in the keybindings list for a specific keybinding.

G�nter


-- 
G.Milde web.de
# -*- coding: iso-8859-1 -*-
"""
A dictionary of LyX keybindings

Scans recursively for `\bind_file`s and stores keybindings in a dictionary
`bindings`. Starts with the preferences file `rcfile`.

Uses the following defaults from LyX.lyx_constants.py
   SYSTEM_DIR, USER_DIR, LYXRC_FILE
Change this variables in `~/.lyx/pyclient/config.py`, if your settings differ

Doesnot currently 'normalize' the keynames, i.e. if different spellings for 
the same key occure in different bind-files, both bindings will be reported.
(Normally, the latter binding will overwrite the first one, get_bindings()
will only overwrite bindings with equal spelling.)

Copyright (c) 2005 G�nter Milde
Released under the terms of the GNU General Public License (ver. 2 or later)
"""

import os, sys, logging

# Customizable values
from LyX.lyx_constants import SYSTEM_DIR, USER_DIR, LYXRC_FILE, LOG_LEVEL

# set up the logger instance
logger = logging.getLogger("lyx_bindings")
logging.basicConfig()
#set verbosity to show all messages of severity >= LOG_LEVEL
logger.setLevel(LOG_LEVEL) 

# debugging
# logger.setLevel(logging.DEBUG)

def bindfile_path(filename):
    """Return the full path for the bind file `filename`
    
    Return empty string, if file is not found.
    
    Like the LyX binary, this looks first in USER_DIR and then in SYSTEM_DIR
    """
    # Add extension (if not present)
    ext = os.path.splitext(filename)[1]
    if not ext:
        filename += '.bind'
    for base_path in (USER_DIR, SYSTEM_DIR):
        path = os.path.join(base_path, 'bind', filename)
        if os.path.isfile(path):
            return path
    return ''


def get_bindings(path=LYXRC_FILE):
    """Return a dictionary of keybindings.
    
    Scan `path` recursively for `\bind_file`s, collect bindings in a 
    "keyname: binding" dictionary
    """
    # if not path: 
    #     return {}
    bindings = {}
    logger.info(" scanning '%s'"%path)
    for line in file(path):
        # logger.debug(" get_bindigs: parsing %s"%line.strip)
        if line.startswith(r'\bind_file'):
            (command, bindfile) = line.split(None, 1)
            bindfile = bindfile_path(bindfile.strip())
            bindings.update(get_bindings(bindfile))
        elif line.startswith(r'\bind'):
            (command, key, binding) = line.split('"', 2)
            bindings[key] = binding.strip()
    return bindings


def print_bindings(bindings):
    """Pretty print the keybindings dictionary with adjusted columns and
    TAB separated keyname and function (to facilitate reading as CSV data)
    """
    keys = bindings.keys()
    keys.sort()
    # sort non-regarding case
    # tmplist = [(key.lower(), key) for key in keys]
    # tmplist.sort()
    # keys = [key for (lowkey, key) in tmplist]
    max_keylen = max(map(len, keys))
    for key in keys:
        print "%s\t%s"%(key.ljust(max_keylen), bindings[key])


def where_is(lfun):
    """Print the key(s) a lfun is bound to
    
    Does a regexp search for `lfun` in the keybindings dictionary
    """
    for key, value in lyx_bindings.bindings.iteritems():
        if re.search(lfun, value):
            print "%s: %s"%(key, value)

def get_binding(key):
    """Print the binding for a key
    
    Doesnot currently 'normalize' the keynames, i.e. only works for keynames
    as found in the *.bind files
    """
    try:
        print "%s: %s"%(key, lyx_bindings.bindings[key])
    except KeyError:
        print "Key %s undefined (maybe different spelling?)"%key



# Code that is always run when importing the module
bindings = get_bindings()

if __name__ == '__main__':
    print_bindings(bindings)

# -*- coding: iso-8859-1 -*-
# lyx_constants.py

"""Customizable constants for the LyX package modules

This module is loaded by all LyX-package modules that need customizable 
constants for values that might differ in different settings.

 - LyX settings and properties
 - pyLyX settings and properties

CUSTOMIZATION:
    * per user:
        create ~/.lyx/pyclient/config.py with your defaults
        
    * per module:
        import LyX.lyx_constants first, 
        set the new value, and
        import the needed module

      EXAMPLE:
          # myclient.py
          '''a client that connects to a different serverpipe'''
          from LyX import lyx_constants
          lyx_constants.SERVERPIPE = "~/.lyx/alternative-serverpipe"
          import LyX.lyxserver
          ...
"""

import sys, os, logging

# LyX settings and properties
# ---------------------------

# the lyx binary
LYXCMD = 'lyx'                

# system wide LyX directory for layouts, bind-files, ...
SYSTEM_DIR = "/usr/share/lyx"  # this works for Debian

# per-user LyX directory
USER_DIR = "~/.lyx"            # what is the correct value for Windows?

# per-user LyX config file (Edit>Preferences)
LYXRC_FILE = os.path.join(USER_DIR, "preferences")

# the server pipe path (without ".in" and ".out") (Edit>Preferences>Paths)
SERVERPIPE = os.environ.get("LYXPIPE", "~/.lyx/lyxpipe" )

# command-line options (from `man lyx`)
LYX_OPTIONS = {'-help': 0, 
               '-version': 0, 
               '-sysdir': 1, 
               '-userdir': 1, 
               '-dbg': 1, 
               '-x': 1, '--execute': 1, 
               '-e': 1, '--export': 1,
               '-i': 2, '--import': 2,
               # xfroms fronted options
               '-geometry': 1, 
               '-display': 1, 
               '-bw': 1, 
               '-visual': 1, 
               '-depth': 1, 
               '-debug': 1, 
               '-sync': 0, 
               '-private': 0, 
               '-shared': 0, 
               '-stdcmap': 0, 
               '-name': 1
               }


# pyLyX settings and properties
# -----------------------------

# per-user pyLyX configuration file
RC_FILE = os.path.join(USER_DIR, "pyclient", "config.py")

# Verbosity: show all messages of severity >= LOG_LEVEL 
# 0: ALL, 10: DEBUG, 20: INFO, 30: WARN, 40: ERROR, 50: CRITICAL
# (see `logging` standard module)
LOG_LEVEL = logging.INFO   

# default timeout for reading the outpipe (in ms)
LYXSERVER_POLL_TIMEOUT = 1000 

# after starting, lyx, needs some time to setup the serverpipes
LYXSERVER_SETUP_DELAY = 2      # wait n seconds
LYXSERVER_SETUP_RETRIES = 10   # try n times to connect

# Setup
# -----

def setup():
    """Set up lyx_constants
    
       * Set up the logger instance
       * Read user configuration
       * Normalize paths and convert '~' to home directory
    """
    global SERVERPIPE, RC_FILE, USER_DIR, SYSTEM_DIR, LYXRC_FILE
    # Set up the logger instance
    logging.basicConfig()
    logger = logging.getLogger("lyx_constants")
    #set verbosity to show all messages of severity >= LOG_LEVEL
    logger.setLevel(LOG_LEVEL)
    # Read user configuration, log IOErrors (no file, ...) as warning
    RC_FILE = os.path.abspath(os.path.expanduser(RC_FILE))
    namespace = sys.modules[__name__].__dict__
    try:
        execfile(RC_FILE, namespace)
    except IOError:
        logger.warning(" Could not load config file")
        logger.debug(" Error message was", exc_info=True)
    # Normalize paths and convert '~' to home directory
    SERVERPIPE = os.path.abspath(os.path.expanduser(SERVERPIPE))
    USER_DIR = os.path.abspath(os.path.expanduser(USER_DIR))
    SYSTEM_DIR = os.path.abspath(os.path.expanduser(SYSTEM_DIR))
    LYXRC_FILE = os.path.abspath(os.path.expanduser(LYXRC_FILE))
    return

# run setup when imported
setup()

Reply via email to