Text plugin script updates: Better error handling, variable parsing, token caching...
[blender.git] / release / scripts / textplugin_imports.py
1 #!BPY
2 """
3 Name: 'Import Complete'
4 Blender: 246
5 Group: 'TextPlugin'
6 Shortcut: 'Space'
7 Tooltip: 'Lists modules when import or from is typed'
8 """
9
10 # Only run if we have the required modules
11 OK = False
12 try:
13         import bpy, sys
14         from BPyTextPlugin import *
15         OK = True
16 except ImportError:
17         pass
18
19 def main():
20         txt = bpy.data.texts.active
21         line, c = current_line(txt)
22         
23         # Check we are in a normal context
24         if get_context(txt) != 0:
25                 return
26         
27         pos = line.rfind('from ', 0, c)
28         
29         # No 'from' found
30         if pos == -1:
31                 # Check instead for straight 'import'
32                 pos2 = line.rfind('import ', 0, c)
33                 if pos2 != -1 and (pos2 == c-7 or (pos2 < c-7 and line[c-2]==',')):
34                         items = [(m, 'm') for m in sys.builtin_module_names]
35                         items.sort(cmp = suggest_cmp)
36                         txt.suggest(items, '')
37         
38         # Immediate 'from' before cursor
39         elif pos == c-5:
40                 items = [(m, 'm') for m in sys.builtin_module_names]
41                 items.sort(cmp = suggest_cmp)
42                 txt.suggest(items, '')
43         
44         # Found 'from' earlier
45         else:
46                 pos2 = line.rfind('import ', pos+5, c)
47                 
48                 # No 'import' found after 'from' so suggest it
49                 if pos2 == -1:
50                         txt.suggest([('import', 'k')], '')
51                         
52                 # Immediate 'import' before cursor and after 'from...'
53                 elif pos2 == c-7 or line[c-2] == ',':
54                         between = line[pos+5:pos2-1].strip()
55                         try:
56                                 mod = get_module(between)
57                         except ImportError:
58                                 print 'Module not found:', between
59                                 return
60                         
61                         items = [('*', 'k')]
62                         for (k,v) in mod.__dict__.items():
63                                 if is_module(v): t = 'm'
64                                 elif callable(v): t = 'f'
65                                 else: t = 'v'
66                                 items.append((k, t))
67                         items.sort(cmp = suggest_cmp)
68                         txt.suggest(items, '')
69
70 if OK:
71         main()