Welcome to mirror list, hosted at ThFree Co, Russian Federation.

textplugin_suggest.py « scripts « release - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 77ae0488b1c54769890922318d6823387f5ea483 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#!BPY
"""
Name: 'Suggest'
Blender: 243
Group: 'TextPlugin'
Tooltip: 'Suggests completions for the word at the cursor in a python script'
"""

import bpy
from Blender  import Text
from StringIO import StringIO
from inspect  import *
from tokenize import generate_tokens
import token

TK_TYPE  = 0
TK_TOKEN = 1
TK_START = 2 #(srow, scol)
TK_END   = 3 #(erow, ecol)
TK_LINE  = 4
TK_ROW = 0
TK_COL = 1

keywords = ['and', 'del', 'from', 'not', 'while', 'as', 'elif', 'global',
			'or', 'with', 'assert', 'else', 'if', 'pass', 'yield',
			'break', 'except', 'import', 'print', 'class', 'exec', 'in',
			'raise', 'continue', 'finally', 'is', 'return', 'def', 'for',
			'lambda', 'try' ]

execs = [] # Used to establish the same import context across defs (import is scope sensitive)

def getTokens(txt):
	global tokens_cached
	if tokens_cached==None:
		lines = txt.asLines()
		str = '\n'.join(lines)
		readline = StringIO(str).readline
		g = generate_tokens(readline)
		tokens = []
		for t in g: tokens.append(t)
		tokens_cached = tokens
	return tokens_cached
tokens_cached = None

def isNameChar(s):
	return s.isalnum() or s in ['_']

# Returns words preceding the cursor that are separated by periods as a list in the
# same order
def getCompletionSymbols(txt):
	(l, c)= txt.getCursorPos()
	lines = txt.asLines()
	line = lines[l]
	a=0
	for a in range(1, c+1):
		if not isNameChar(line[c-a]) and line[c-a]!='.':
			a -= 1
			break
	return line[c-a:c].split('.')


# Returns a list of tuples of symbol names and their types (name, type) where
# type is one of:
#   m (module/class)  Has its own members (includes classes)
#   v (variable)      Has a type which may have its own members
#   f (function)      Callable and may have a return type (with its own members)
# It also updates the global import context (via execs)
def getGlobals(txt):
	global execs
	
	tokens = getTokens(txt)
	globals = dict()
	for i in range(len(tokens)):
		
		# Handle all import statements
		if i>=1 and tokens[i-1][TK_TOKEN]=='import':
			
			# Find 'from' if it exists
			fr= -1
			for a in range(1, i):
				if tokens[i-a][TK_TYPE]==token.NEWLINE: break
				if tokens[i-a][TK_TOKEN]=='from':
					fr=i-a
					break
			
			# Handle: import ___[,___]
			if fr<0:
				
				while True:
					if tokens[i][TK_TYPE]==token.NAME:
						# Add the import to the execs list
						x = tokens[i][TK_LINE].strip()
						k = tokens[i][TK_TOKEN]
						execs.append(x)
						
						# Add the symbol name to the return list
						globals[k] = 'm'
					elif tokens[i][TK_TOKEN]!=',':
						break
					i += 1
			
			# Handle statement: from ___[.___] import ___[,___]
			else: # fr>=0:
				
				# Add the import to the execs list
				x = tokens[i][TK_LINE].strip()
				execs.append(x)
				
				# Import parent module so we can process it for sub modules
				parent = ''.join([t[TK_TOKEN] for t in tokens[fr+1:i-1]])
				exec "import "+parent
				
				# All submodules, functions, etc.
				if tokens[i][TK_TOKEN]=='*':
					
					# Add each symbol name to the return list
					exec "d="+parent+".__dict__.items()"
					for k,v in d:
						if not globals.has_key(k) or not globals[k]:
							t='v'
							if ismodule(v): t='m'
							elif callable(v): t='f'
							globals[k] = t
				
				# Specific function, submodule, etc.
				else:
					while True:
						if tokens[i][TK_TYPE]==token.NAME:
							k = tokens[i][TK_TOKEN]
							if not globals.has_key(k) or not globals[k]:
								t='v'
								try:
									exec 'v='+parent+'.'+k
									if ismodule(v): t='m'
									elif callable(v): t='f'
								except: pass
								globals[k] = t
						elif tokens[i][TK_TOKEN]!=',':
							break
						i += 1
					
		elif tokens[i][TK_TYPE]==token.NAME and tokens[i][TK_TOKEN] not in keywords and (i==0 or tokens[i-1][TK_TOKEN]!='.'):
			k = tokens[i][TK_TOKEN]
			if not globals.has_key(k) or not globals[k]:
				t=None
				if (i>0 and tokens[i-1][TK_TOKEN]=='def'):
					t='f'
				else:
					t='v'
				globals[k] = t
	
	return globals

def cmpi0(x, y):
	return cmp(x[0].lower(), y[0].lower())

def globalSuggest(txt, cs):
	global execs
	
	suggestions = dict()
	(row, col) = txt.getCursorPos()
	globals = getGlobals(txt)
	
	# Sometimes we have conditional includes which will fail if the module
	# cannot be found. So we protect outselves in a try block
	for x in execs:
		exec 'try: '+x+'\nexcept: pass'
	
	if len(cs)==0:
		sub = ''
	else:
		sub = cs[0].lower()
	print 'Search:', sub
	
	for k,t in globals.items():
		if k.lower().startswith(sub):
			suggestions[k] = t
	
	l = list(suggestions.items())
	return sorted (l, cmp=cmpi0)

# Only works for 'static' members (eg. Text.Get)
def memberSuggest(txt, cs):
	global execs
	
	# Populate the execs for imports
	getGlobals(txt)
	
	# Sometimes we have conditional includes which will fail if the module
	# cannot be found. So we protect outselves in a try block
	for x in execs:
		exec 'try: '+x+'\nexcept: pass'
	
	suggestions = dict()
	(row, col) = txt.getCursorPos()
	
	sub = cs[len(cs)-1].lower()
	print 'Search:', sub
	
	t=None
	pre='.'.join(cs[:-1])
	try:
		exec "t="+pre
	except:
		print 'Failed to assign '+pre
		print execs
		print cs
	
	if t!=None:
		for k,v in t.__dict__.items():
			if ismodule(v): t='m'
			elif callable(v): t='f'
			else: t='v'
			if k.lower().startswith(sub):
				suggestions[k] = t
	
	l = list(suggestions.items())
	return sorted (l, cmp=cmpi0)

def main():
	txt = bpy.data.texts.active
	if txt==None: return
	
	cs = getCompletionSymbols(txt)
	
	if len(cs)<=1:
		l = globalSuggest(txt, cs)
		txt.suggest(l, cs[len(cs)-1])
		
	else:
		l = memberSuggest(txt, cs)
		txt.suggest(l, cs[len(cs)-1])

main()