Advertisement
Guest User

Untitled

a guest
May 22nd, 2015
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.04 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. #
  4. # Copyright (c) 2008 Doug Hellmann All rights reserved.
  5. #
  6. """
  7. """
  8.  
  9. __version__ = "$Id$"
  10. #end_pymotw_header
  11.  
  12. import readline
  13. import logging
  14.  
  15. LOG_FILENAME = '/tmp/completer.log'
  16. logging.basicConfig(filename=LOG_FILENAME,
  17. level=logging.DEBUG,
  18. )
  19.  
  20. class BufferAwareCompleter(object):
  21.  
  22. def __init__(self, options):
  23. self.options = options
  24. self.current_candidates = []
  25. return
  26.  
  27. def complete(self, text, state):
  28. response = None
  29. if state == 0:
  30. # This is the first time for this text,
  31. # so build a match list.
  32.  
  33. origline = readline.get_line_buffer()
  34. begin = readline.get_begidx()
  35. end = readline.get_endidx()
  36. being_completed = origline[begin:end]
  37. words = origline.split()
  38.  
  39. logging.debug('origline=%s', repr(origline))
  40. logging.debug('begin=%s', begin)
  41. logging.debug('end=%s', end)
  42. logging.debug('being_completed=%s', being_completed)
  43. logging.debug('words=%s', words)
  44.  
  45. if not words:
  46. self.current_candidates = sorted(self.options.keys())
  47. else:
  48. try:
  49. if begin == 0:
  50. # first word
  51. candidates = self.options.keys()
  52. else:
  53. # later word
  54. first = words[0]
  55. candidates = self.options[first]
  56.  
  57. if being_completed:
  58. # match options with portion of input
  59. # being completed
  60. self.current_candidates = [
  61. w for w in candidates
  62. if w.startswith(being_completed)
  63. ]
  64. else:
  65. # matching empty string so use all candidates
  66. self.current_candidates = candidates
  67.  
  68. logging.debug('candidates=%s',
  69. self.current_candidates)
  70.  
  71. except (KeyError, IndexError), err:
  72. logging.error('completion error: %s', err)
  73. self.current_candidates = []
  74.  
  75. try:
  76. response = self.current_candidates[state]
  77. except IndexError:
  78. response = None
  79. logging.debug('complete(%s, %s) => %s',
  80. repr(text), state, response)
  81. return response
  82.  
  83.  
  84. def input_loop():
  85. line = ''
  86. while line != 'stop':
  87. line = raw_input('Prompt ("stop" to quit): ')
  88. print 'Dispatch %s' % line
  89.  
  90. # Register our completer function
  91. readline.set_completer(BufferAwareCompleter(
  92. {'list':['files', 'directories'],
  93. 'print':['byname', 'bysize'],
  94. 'stop':[],
  95. }).complete)
  96.  
  97. # Use the tab key for completion
  98. readline.parse_and_bind('tab: complete')
  99.  
  100. # Prompt the user for text
  101. input_loop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement