Input completion

Eugene <[email protected]>
Newsgroups gmane.comp.games.mud.client.lyntin
Message-ID <[email protected]>
I have added a completion functionality into cursesui.py. 
To make an actual completion the completion.py module 
should be present in moduledir, as well as one or more 
"completer" modules. The hot key is "Tab".

This functionality could easily be added to tkui, using 
the same completion module. More completers could be added 
later.

I'm not sure about putting the completion module into the 
core distribution, so it is in attachment so far.

--
Eugene
---
Professional hosting for everyone - http://www.host.ru
completion.py (application/octet-stream, 1.5 KB)
from lyntin import exported, manager


class CompletionManager(manager.Manager):
  """
  This manager should help to an UI module to build
  a completion list for given user input.
  """
  def __init__(self, *args, **kargs):
    manager.Manager.__init__(self, *args, **kargs)
    self.reset()

  def reset(self):
    """
    Resets the completer object, so the completion list
    will be rebuilt on next get_completion call.
    """
    self.list_ = []

  def _mapping(self, x, y):
    self.list_ += y
    return x
    
  def get_completion(self, text='', position=None):
    """
    This method should be called with some hotkey pressing.

    @param text: the text to be completed
    @type  text: string

    @param position: current position in the text
    @type  position: int

    @returns: next possible completion pair (newtext, newposition)
    @rtype:   (string, int)
    """
    if not self.list_:
      #
      # Rebuild the completion list if it is empty after reset.
      #
      if position==None or position<0 or position>len(text):
        position = len(text)
      exported.hook_spam("completer_hook",
                         { 'text': text, 'position': position },
                         self._mapping
                        )
      self.list_.append((text, position))  # put an anchor at the end of list
      
    completion = self.list_[0]
    self.list_[:1] = []
    self.list_.append(completion)
    return completion


def load():
  exported.add_manager("completion", CompletionManager())


def unload():
  exported.remove_manager("completion")
completer.py (application/octet-stream, 2.6 KB)
from lyntin import exported 


def make_alias_completer(args):
  """Returns the alias completion list."""
  text = args['text']
  position = args['position']
  cmdchar = exported.get_config("commandchar")
  if not text.startswith(cmdchar):
    al = exported.get_manager("alias")
    aliases = filter(lambda x: x.startswith(text[:position]),
        al.getAliasData(exported.get_current_session()).getAliases() )
    return [ (x+' ', len(x)+1) for x in aliases ]
  return []        


def make_command_completer(args):
  """Returns the command completion list."""
  text = args['text']
  position = args['position']
  cmdchar = exported.get_config("commandchar")
  if text.startswith(cmdchar):
    cm = exported.get_manager("command")
    return map(lambda x: (''.join( (cmdchar, x, ' ') ), len(x)+2),
               filter(lambda x: x.startswith(text[1:]),
                      cm.getCommands()))
  return []


import re

def make_var_completer(args):
  """
  Returns the variable completion list,
  if the text at the given position looks like a variable
  """
  text = args['text']
  position = args['position']

  #
  # Checking for "#showme $foo" form:
  #
  mch = re.match('(.*)\$(\S*)', text[:position])
  if mch:
    tail = re.match('(\S*)(.*)$', text[position:])
    varname = mch.group(2)+tail.group(1)
    list = []
    for var in filter( lambda x: x.startswith(varname), 
                       exported.get_current_session()._vars.keys() ):
      start = ''.join( (mch.group(1), '$', var) )
      list.append( (start+tail.group(2), len(start)) )
    return list
  #
  # TODO process the "#showme ${foo}" form
  #

  #
  # Processing the "#unvar" command:
  #
  cmdchar = exported.get_config("commandchar")
  mch = re.match(cmdchar+'unvariable (\S*)$', text)
  if mch:
    list = []
    for var in filter( lambda x: x.startswith(mch.group(1)), 
                       exported.get_current_session()._vars.keys() ):
      command = '#unvariable ' + var                       
      list.append( (command, len(command)) )
    return list
    
  return []  
    

def load():
  """
  These 3 completer hooks below could be united into one big hook function
  as well, but for demonstration purposes they are divided.
  Later they could be moved in their own modules.
  """
  exported.hook_register("completer_hook", make_command_completer)
  exported.hook_register("completer_hook", make_alias_completer)
  exported.hook_register("completer_hook", make_var_completer)


def unload():
  exported.hook_unregister("completer_hook", make_var_completer)
  exported.hook_unregister("completer_hook", make_command_completer)
  exported.hook_unregister("completer_hook", make_alias_completer)
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.