home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_1709 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  11.6 KB  |  453 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import __builtin__
  5. import __main__
  6. import glob
  7. import keyword
  8. import os
  9. import re
  10. import shlex
  11. import sys
  12. import IPython.rlineimpl as readline
  13. import itertools
  14. from IPython.ipstruct import Struct
  15. from IPython import ipapi
  16. from IPython import generics
  17. import types
  18.  
  19. try:
  20.     set()
  21. except NameError:
  22.     from sets import Set as set
  23.  
  24. from IPython.genutils import debugx, dir2
  25. __all__ = [
  26.     'Completer',
  27.     'IPCompleter']
  28.  
  29. class Completer:
  30.     
  31.     def __init__(self, namespace = None, global_namespace = None):
  32.         if namespace is None:
  33.             self.use_main_ns = 1
  34.         else:
  35.             self.use_main_ns = 0
  36.             self.namespace = namespace
  37.         if global_namespace is None:
  38.             self.global_namespace = { }
  39.         else:
  40.             self.global_namespace = global_namespace
  41.  
  42.     
  43.     def complete(self, text, state):
  44.         if self.use_main_ns:
  45.             self.namespace = __main__.__dict__
  46.         
  47.         if state == 0:
  48.             if '.' in text:
  49.                 self.matches = self.attr_matches(text)
  50.             else:
  51.                 self.matches = self.global_matches(text)
  52.         
  53.         
  54.         try:
  55.             return self.matches[state]
  56.         except IndexError:
  57.             return None
  58.  
  59.  
  60.     
  61.     def global_matches(self, text):
  62.         matches = []
  63.         match_append = matches.append
  64.         n = len(text)
  65.         for lst in [
  66.             keyword.kwlist,
  67.             __builtin__.__dict__.keys(),
  68.             self.namespace.keys(),
  69.             self.global_namespace.keys()]:
  70.             for word in lst:
  71.                 if word[:n] == text and word != '__builtins__':
  72.                     match_append(word)
  73.                     continue
  74.             
  75.         
  76.         return matches
  77.  
  78.     
  79.     def attr_matches(self, text):
  80.         import re
  81.         m = re.match('(\\S+(\\.\\w+)*)\\.(\\w*)$', text)
  82.         if not m:
  83.             return []
  84.         (expr, attr) = m.group(1, 3)
  85.         
  86.         try:
  87.             obj = eval(expr, self.namespace)
  88.         except:
  89.             m
  90.             
  91.             try:
  92.                 obj = eval(expr, self.global_namespace)
  93.             return []
  94.  
  95.  
  96.         words = dir2(obj)
  97.         
  98.         try:
  99.             words = generics.complete_object(obj, words)
  100.         except ipapi.TryNext:
  101.             m
  102.             m
  103.         except:
  104.             m
  105.  
  106.         n = len(attr)
  107.         res = _[1]
  108.         return res
  109.  
  110.  
  111.  
  112. class IPCompleter(Completer):
  113.     
  114.     def __init__(self, shell, namespace = None, global_namespace = None, omit__names = 0, alias_table = None):
  115.         Completer.__init__(self, namespace, global_namespace)
  116.         self.magic_prefix = shell.name + '.magic_'
  117.         self.magic_escape = shell.ESC_MAGIC
  118.         self.readline = readline
  119.         delims = self.readline.get_completer_delims()
  120.         delims = delims.replace(self.magic_escape, '')
  121.         self.readline.set_completer_delims(delims)
  122.         self.get_line_buffer = self.readline.get_line_buffer
  123.         self.get_endidx = self.readline.get_endidx
  124.         self.omit__names = omit__names
  125.         self.merge_completions = shell.rc.readline_merge_completions
  126.         if alias_table is None:
  127.             alias_table = { }
  128.         
  129.         self.alias_table = alias_table
  130.         self.space_name_re = re.compile('([^\\\\] )')
  131.         self.glob = glob.glob
  132.         term = os.environ.get('TERM', 'xterm')
  133.         self.dumb_terminal = term in ('dumb', 'emacs')
  134.         if sys.platform == 'win32':
  135.             self.clean_glob = self._clean_glob_win32
  136.         else:
  137.             self.clean_glob = self._clean_glob
  138.         self.matchers = [
  139.             self.python_matches,
  140.             self.file_matches,
  141.             self.alias_matches,
  142.             self.python_func_kw_matches]
  143.  
  144.     
  145.     def all_completions(self, text):
  146.         completions = []
  147.         comp_append = completions.append
  148.         
  149.         try:
  150.             for i in xrange(sys.maxint):
  151.                 res = self.complete(text, i)
  152.                 if not res:
  153.                     break
  154.                 
  155.                 comp_append(res)
  156.         except NameError:
  157.             pass
  158.  
  159.         return completions
  160.  
  161.     
  162.     def _clean_glob(self, text):
  163.         return self.glob('%s*' % text)
  164.  
  165.     
  166.     def _clean_glob_win32(self, text):
  167.         return [ f.replace('\\', '/') for f in self.glob('%s*' % text) ]
  168.  
  169.     
  170.     def file_matches(self, text):
  171.         if sys.platform == 'win32':
  172.             protectables = ' '
  173.         else:
  174.             protectables = ' ()'
  175.         if text.startswith('!'):
  176.             text = text[1:]
  177.             text_prefix = '!'
  178.         else:
  179.             text_prefix = ''
  180.         
  181.         def protect_filename(s):
  182.             return []([ ch for ch in s ])
  183.  
  184.         
  185.         def single_dir_expand(matches):
  186.             if len(matches) == 1 and os.path.isdir(matches[0]):
  187.                 d = matches[0]
  188.                 if d[-1] in ('/', '\\'):
  189.                     d = d[:-1]
  190.                 
  191.                 subdirs = os.listdir(d)
  192.                 if subdirs:
  193.                     matches = [ d + '/' + p for p in subdirs ]
  194.                     return single_dir_expand(matches)
  195.                 return matches
  196.             os.path.isdir(matches[0])
  197.             return matches
  198.  
  199.         lbuf = self.lbuf
  200.         open_quotes = 0
  201.         
  202.         try:
  203.             lsplit = shlex.split(lbuf)[-1]
  204.         except ValueError:
  205.             ((None,),)
  206.             ((None,),)
  207.             if lbuf.count('"') == 1:
  208.                 open_quotes = 1
  209.                 lsplit = lbuf.split('"')[-1]
  210.             elif lbuf.count("'") == 1:
  211.                 open_quotes = 1
  212.                 lsplit = lbuf.split("'")[-1]
  213.             else:
  214.                 return []
  215.             lbuf.count('"') == 1
  216.             except IndexError:
  217.                 lsplit = ''
  218.             except:
  219.                 None<EXCEPTION MATCH>IndexError
  220.             
  221.  
  222.         if lsplit != protect_filename(lsplit):
  223.             has_protectables = 1
  224.             text0 = text
  225.             text = lsplit
  226.         else:
  227.             has_protectables = 0
  228.             text = os.path.expanduser(text)
  229.         if text == '':
  230.             return [ text_prefix + protect_filename(f) for f in self.glob('*') ]
  231.         m0 = self.clean_glob(text.replace('\\', ''))
  232.         if has_protectables:
  233.             len_lsplit = len(lsplit)
  234.             matches = [ text_prefix + text0 + protect_filename(f[len_lsplit:]) for f in m0 ]
  235.         elif open_quotes:
  236.             matches = m0
  237.         else:
  238.             matches = [ text_prefix + protect_filename(f) for f in m0 ]
  239.         return single_dir_expand(matches)
  240.  
  241.     
  242.     def alias_matches(self, text):
  243.         if ' ' in self.lbuf.lstrip() and not self.lbuf.lstrip().startswith('sudo'):
  244.             return []
  245.         text = os.path.expanduser(text)
  246.         aliases = self.alias_table.keys()
  247.         if text == '':
  248.             return aliases
  249.         return _[1]
  250.  
  251.     
  252.     def python_matches(self, text):
  253.         if '.' in text:
  254.             
  255.             try:
  256.                 matches = self.attr_matches(text)
  257.                 if text.endswith('.') and self.omit__names:
  258.                     if self.omit__names == 1:
  259.                         
  260.                         no__name = lambda txt: re.match('.*\\.__.*?__', txt) is None
  261.                     else:
  262.                         
  263.                         no__name = lambda txt: re.match('.*\\._.*?', txt) is None
  264.                     matches = filter(no__name, matches)
  265.             except NameError:
  266.                 matches = []
  267.             except:
  268.                 None<EXCEPTION MATCH>NameError
  269.             
  270.  
  271.         None<EXCEPTION MATCH>NameError
  272.         matches = self.global_matches(text)
  273.         if matches == [] and not text.startswith(os.sep) and ' ' not in self.lbuf:
  274.             matches = self.attr_matches(self.magic_prefix + text)
  275.         
  276.         return matches
  277.  
  278.     
  279.     def _default_arguments(self, obj):
  280.         if not inspect.isfunction(obj) or inspect.ismethod(obj):
  281.             if inspect.isclass(obj):
  282.                 if not getattr(obj, '__init__', None):
  283.                     pass
  284.                 obj = getattr(obj, '__new__', None)
  285.             elif hasattr(obj, '__call__'):
  286.                 obj = obj.__call__
  287.             
  288.         
  289.         
  290.         try:
  291.             (args, _, _1, defaults) = inspect.getargspec(obj)
  292.             if defaults:
  293.                 return args[-len(defaults):]
  294.         except TypeError:
  295.             pass
  296.  
  297.         return []
  298.  
  299.     
  300.     def python_func_kw_matches(self, text):
  301.         if '.' in text:
  302.             return []
  303.         
  304.         try:
  305.             regexp = self._IPCompleter__funcParamsRegex
  306.         except AttributeError:
  307.             '.' in text
  308.             '.' in text
  309.             regexp = self._IPCompleter__funcParamsRegex = re.compile('\n                \'.*?\' |    # single quoted strings or\n                ".*?" |    # double quoted strings or\n                \\w+   |    # identifier\n                \\S         # other characters\n                ', re.VERBOSE | re.DOTALL)
  310.         except:
  311.             '.' in text
  312.  
  313.         tokens = regexp.findall(self.get_line_buffer())
  314.         tokens.reverse()
  315.         iterTokens = iter(tokens)
  316.         openPar = 0
  317.         for token in iterTokens:
  318.             if token == ')':
  319.                 openPar -= 1
  320.                 continue
  321.             '.' in text
  322.             if token == '(':
  323.                 openPar += 1
  324.                 if openPar > 0:
  325.                     break
  326.                 
  327.             openPar > 0
  328.         else:
  329.             return []
  330.         ids = None
  331.         isId = re.compile('\\w+$').match
  332.         while True:
  333.             
  334.             try:
  335.                 ids.append(iterTokens.next())
  336.                 if not isId(ids[-1]):
  337.                     ids.pop()
  338.                     break
  339.                 
  340.                 if not iterTokens.next() == '.':
  341.                     break
  342.             continue
  343.             except StopIteration:
  344.                 break
  345.                 continue
  346.             
  347.  
  348.             None<EXCEPTION MATCH>StopIteration
  349.         if len(ids) == 1:
  350.             callableMatches = self.global_matches(ids[0])
  351.         else:
  352.             callableMatches = self.attr_matches('.'.join(ids[::-1]))
  353.         argMatches = []
  354.         for callableMatch in callableMatches:
  355.             
  356.             try:
  357.                 namedArgs = self._default_arguments(eval(callableMatch, self.namespace))
  358.             except:
  359.                 continue
  360.  
  361.             for namedArg in namedArgs:
  362.                 if namedArg.startswith(text):
  363.                     argMatches.append('%s=' % namedArg)
  364.                     continue
  365.             
  366.         
  367.         return argMatches
  368.  
  369.     
  370.     def dispatch_custom_completer(self, text):
  371.         line = self.full_lbuf
  372.         if not line.strip():
  373.             return None
  374.         event = Struct()
  375.         event.line = line
  376.         event.symbol = text
  377.         cmd = line.split(None, 1)[0]
  378.         event.command = cmd
  379.         if not cmd.startswith(self.magic_escape):
  380.             try_magic = self.custom_completers.s_matches(self.magic_escape + cmd)
  381.         else:
  382.             try_magic = []
  383.         for c in itertools.chain(self.custom_completers.s_matches(cmd), try_magic, self.custom_completers.flat_matches(self.lbuf)):
  384.             
  385.             try:
  386.                 res = c(event)
  387.                 withcase = _[1]
  388.                 if withcase:
  389.                     return withcase
  390.                 return _[2]
  391.             continue
  392.             except ipapi.TryNext:
  393.                 continue
  394.             
  395.  
  396.         
  397.  
  398.     
  399.     def complete(self, text, state, line_buffer = None):
  400.         if line_buffer is None:
  401.             self.full_lbuf = self.get_line_buffer()
  402.         else:
  403.             self.full_lbuf = line_buffer
  404.         if not self.dumb_terminal or self.full_lbuf.strip():
  405.             self.readline.insert_text('\t')
  406.             return None
  407.         magic_escape = self.magic_escape
  408.         magic_prefix = self.magic_prefix
  409.         self.lbuf = self.full_lbuf[:self.get_endidx()]
  410.         
  411.         try:
  412.             if text.startswith(magic_escape):
  413.                 text = text.replace(magic_escape, magic_prefix)
  414.             elif text.startswith('~'):
  415.                 text = os.path.expanduser(text)
  416.             
  417.             if state == 0:
  418.                 custom_res = self.dispatch_custom_completer(text)
  419.                 if custom_res is not None:
  420.                     self.matches = custom_res
  421.                 elif self.merge_completions:
  422.                     self.matches = []
  423.                     for matcher in self.matchers:
  424.                         self.matches.extend(matcher(text))
  425.                     
  426.                 else:
  427.                     for matcher in self.matchers:
  428.                         self.matches = matcher(text)
  429.                         if self.matches:
  430.                             break
  431.                             continue
  432.                     
  433.                 
  434.                 def uniq(alist):
  435.                     set = { }
  436.                     return _[1]
  437.  
  438.                 self.matches = uniq(self.matches)
  439.             
  440.             
  441.             try:
  442.                 ret = self.matches[state].replace(magic_prefix, magic_escape)
  443.                 return ret
  444.             except IndexError:
  445.                 return None
  446.  
  447.         except:
  448.             self.full_lbuf.strip()
  449.             return None
  450.  
  451.  
  452.  
  453.