-
-
Notifications
You must be signed in to change notification settings - Fork 252
Expand file tree
/
Copy pathcli.py
More file actions
2425 lines (2023 loc) · 79.2 KB
/
cli.py
File metadata and controls
2425 lines (2023 loc) · 79.2 KB
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# The MIT License
#
# Copyright (c) 2008 Bob Farrell
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from __future__ import with_statement
import codecs
import os
import sys
import curses
import code
import traceback
import re
import time
import urllib
import rlcompleter
import inspect
import signal
import struct
import termios
import fcntl
import string
import socket
import pydoc
import types
import unicodedata
import textwrap
from cStringIO import StringIO
from itertools import takewhile
from locale import LC_ALL, getpreferredencoding, setlocale
from optparse import OptionParser
from urlparse import urljoin
from xmlrpclib import ServerProxy, Error as XMLRPCError
from ConfigParser import ConfigParser, NoSectionError, NoOptionError
# These are used for syntax hilighting.
from pygments import format
from pygments.lexers import PythonLexer
from pygments.token import Token
from bpython.formatter import BPythonFormatter, Parenthesis
# This for completion
from bpython import importcompletion
from glob import glob
# This for config
from bpython.config import Struct, loadini, migrate_rc
# This for keys
from bpython.keys import key_dispatch
from bpython import __version__
from bpython.pager import page
def log(x):
f = open('/tmp/bpython.log', 'a')
f.write('%s\n' % (x,))
py3 = sys.version_info[0] == 3
stdscr = None
def calculate_screen_lines(tokens, width, cursor=0):
"""Given a stream of tokens and a screen width plus an optional
initial cursor position, return the amount of needed lines on the
screen."""
lines = 1
pos = cursor
for (token, value) in tokens:
if token is Token.Text and value == '\n':
lines += 1
else:
pos += len(value)
lines += pos // width
pos %= width
return lines
def parsekeywordpairs(signature):
tokens = PythonLexer().get_tokens(signature)
stack = []
substack = []
parendepth = 0
begin = False
for token, value in tokens:
if not begin:
if token is Token.Punctuation and value == u'(':
begin = True
continue
if token is Token.Punctuation:
if value == u'(':
parendepth += 1
elif value == u')':
parendepth -= 1
elif value == ':' and parendepth == -1:
# End of signature reached
break
if parendepth > 0:
substack.append(value)
continue
if (token is Token.Punctuation and
(value == ',' or (value == ')' and parendepth == -1))):
stack.append(substack[:])
del substack[:]
continue
if value and value.strip():
substack.append(value)
d = {}
for item in stack:
if len(item) >= 3:
d[item[0]] = ''.join(item[2:])
return d
def fixlongargs(f, argspec):
"""Functions taking default arguments that are references to other objects
whose str() is too big will cause breakage, so we swap out the object
itself with the name it was referenced with in the source by parsing the
source itself !"""
if argspec[3] is None:
# No keyword args, no need to do anything
return
values = list(argspec[3])
if not values:
return
keys = argspec[0][-len(values):]
try:
src = inspect.getsourcelines(f)
except IOError:
return
signature = ''.join(src[0])
kwparsed = parsekeywordpairs(signature)
for i, (key, value) in enumerate(zip(keys, values)):
if len(str(value)) != len(kwparsed[key]):
values[i] = kwparsed[key]
argspec[3] = values
class FakeStdin(object):
"""Provide a fake stdin type for things like raw_input() etc."""
def __init__(self, interface):
"""Take the curses Repl on init and assume it provides a get_key method
which, fortunately, it does."""
self.encoding = getpreferredencoding()
self.interface = interface
self.buffer = list()
def __iter__(self):
return iter(self.readlines())
def isatty(self):
return True
def readline(self, size=-1):
"""I can't think of any reason why anything other than readline would
be useful in the context of an interactive interpreter so this is the
only one I've done anything with. The others are just there in case
someone does something weird to stop it from blowing up."""
if not size:
return ''
elif self.buffer:
buffer = self.buffer.pop(0)
else:
buffer = ''
curses.raw(True)
try:
while not buffer.endswith('\n'):
key = self.interface.get_key()
if key in [curses.erasechar(), 'KEY_BACKSPACE']:
y, x = self.interface.scr.getyx()
if buffer:
self.interface.scr.delch(y, x - 1)
buffer = buffer[:-1]
continue
elif key == chr(4) and not buffer:
# C-d
return ''
elif (key != '\n' and
(len(key) > 1 or unicodedata.category(key) == 'Cc')):
continue
sys.stdout.write(key)
# Include the \n in the buffer - raw_input() seems to deal with trailing
# linebreaks and will break if it gets an empty string.
buffer += key
finally:
curses.raw(False)
if size > 0:
rest = buffer[size:]
if rest:
self.buffer.append(rest)
buffer = buffer[:size]
if py3:
return buffer
else:
return buffer.encode(getpreferredencoding())
def read(self, size=None):
if size == 0:
return ''
data = list()
while size is None or size > 0:
line = self.readline(size or -1)
if not line:
break
if size is not None:
size -= len(line)
data.append(line)
return ''.join(data)
def readlines(self, size=-1):
return list(iter(self.readline, ''))
OPTS = Struct()
DO_RESIZE = False
# TODO:
#
# Tab completion does not work if not at the end of the line.
#
# Numerous optimisations can be made but it seems to do all the lookup stuff
# fast enough on even my crappy server so I'm not too bothered about that
# at the moment.
#
# The popup window that displays the argspecs and completion suggestions
# needs to be an instance of a ListWin class or something so I can wrap
# the addstr stuff to a higher level.
#
def DEBUG(s):
"""This shouldn't ever be called in any release of bpython, so
beat me up if you find anything calling it."""
open('/tmp/bpython-debug', 'a').write("%s\n" % (str(s), ))
def get_color(name):
return colors[OPTS.color_scheme[name].lower()]
def get_colpair(name):
return curses.color_pair(get_color(name) + 1)
def make_colors():
"""Init all the colours in curses and bang them into a dictionary"""
# blacK, Red, Green, Yellow, Blue, Magenta, Cyan, White, Default:
c = {
'k' : 0,
'r' : 1,
'g' : 2,
'y' : 3,
'b' : 4,
'm' : 5,
'c' : 6,
'w' : 7,
'd' : -1,
}
for i in range(63):
if i > 7:
j = i // 8
else:
j = c[OPTS.color_scheme['background']]
curses.init_pair(i+1, i % 8, j)
return c
def next_token_inside_string(s, inside_string):
"""Given a code string s and an initial state inside_string, return
whether the next token will be inside a string or not."""
for token, value in PythonLexer().get_tokens(s):
if token is Token.String:
value = value.lstrip('bBrRuU')
if value in ['"""', "'''", '"', "'"]:
if not inside_string:
inside_string = value
elif value == inside_string:
inside_string = False
return inside_string
class MatchesIterator(object):
def __init__(self, current_word='', matches=[]):
self.current_word = current_word
self.matches = list(matches)
self.index = -1
def __nonzero__(self):
return self.index != -1
def __iter__(self):
return self
def current(self):
if self.index == -1:
raise ValueError('No current match.')
return self.matches[self.index]
def next(self):
self.index = (self.index + 1) % len(self.matches)
return self.matches[self.index]
def update(self, current_word='', matches=[]):
if current_word != self.current_word:
self.current_word = current_word
self.matches = list(matches)
self.index = -1
class Interpreter(code.InteractiveInterpreter):
def __init__(self, locals=None, encoding=sys.getdefaultencoding()):
"""The syntaxerror callback can be set at any time and will be called
on a caught syntax error. The purpose for this in bpython is so that
the repl can be instantiated after the interpreter (which it
necessarily must be with the current factoring) and then an exception
callback can be added to the Interpeter instance afterwards - more
specifically, this is so that autoindentation does not occur after a
traceback."""
self.encoding = encoding
self.syntaxerror_callback = None
# Unfortunately code.InteractiveInterpreter is a classic class, so no super()
code.InteractiveInterpreter.__init__(self, locals)
if not py3:
def runsource(self, source):
source = '# coding: %s\n%s' % (self.encoding,
source.encode(self.encoding))
return code.InteractiveInterpreter.runsource(self, source)
def showsyntaxerror(self, filename=None):
"""Override the regular handler, the code's copied and pasted from
code.py, as per showtraceback, but with the syntaxerror callback called
and the text in a pretty colour."""
if self.syntaxerror_callback is not None:
self.syntaxerror_callback()
type, value, sys.last_traceback = sys.exc_info()
sys.last_type = type
sys.last_value = value
if filename and type is SyntaxError:
# Work hard to stuff the correct filename in the exception
try:
msg, (dummy_filename, lineno, offset, line) = value
except:
# Not the format we expect; leave it alone
pass
else:
# Stuff in the right filename and right lineno
value = SyntaxError(msg, (filename, lineno - 1, offset, line))
sys.last_value = value
list = traceback.format_exception_only(type, value)
self.writetb(list)
def showtraceback(self):
"""This needs to override the default traceback thing
so it can put it into a pretty colour and maybe other
stuff, I don't know"""
try:
t, v, tb = sys.exc_info()
sys.last_type = t
sys.last_value = v
sys.last_traceback = tb
tblist = traceback.extract_tb(tb)
del tblist[:1]
# Set the right lineno (encoding header adds an extra line)
tblist[0] = (tblist[0][0], 1) + tblist[0][2:]
l = traceback.format_list(tblist)
if l:
l.insert(0, "Traceback (most recent call last):\n")
l[len(l):] = traceback.format_exception_only(t, v)
finally:
tblist = tb = None
self.writetb(l)
def writetb(self, l):
"""This outputs the traceback and should be overridden for anything
fancy."""
map(self.write, ["\x01%s\x03%s" % (OPTS.color_scheme['error'], i) for i in l])
class AttrCleaner(object):
"""A context manager that tries to make an object not exhibit side-effects
on attribute lookup."""
def __init__(self, obj):
self.obj = obj
def __enter__(self):
"""Try to make an object not exhibit side-effects on attribute
lookup."""
type_ = type(self.obj)
__getattribute__ = None
__getattr__ = None
# Dark magic:
# If __getattribute__ doesn't exist on the class and __getattr__ does
# then __getattr__ will be called when doing
# getattr(type_, '__getattribute__', None)
# so we need to first remove the __getattr__, then the
# __getattribute__, then look up the attributes and then restore the
# original methods. :-(
# The upshot being that introspecting on an object to display its
# attributes will avoid unwanted side-effects.
if py3 or type_ != types.InstanceType:
__getattr__ = getattr(type_, '__getattr__', None)
if __getattr__ is not None:
try:
setattr(type_, '__getattr__', (lambda _: None))
except TypeError:
__getattr__ = None
__getattribute__ = getattr(type_, '__getattribute__', None)
if __getattribute__ is not None:
try:
setattr(type_, '__getattribute__', object.__getattribute__)
except TypeError:
# XXX: This happens for e.g. built-in types
__getattribute__ = None
self.attribs = (__getattribute__, __getattr__)
# /Dark magic
def __exit__(self, exc_type, exc_val, exc_tb):
"""Restore an object's magic methods."""
type_ = type(self.obj)
__getattribute__, __getattr__ = self.attribs
# Dark magic:
if __getattribute__ is not None:
setattr(type_, '__getattribute__', __getattribute__)
if __getattr__ is not None:
setattr(type_, '__getattr__', __getattr__)
# /Dark magic
class Repl(object):
"""Implements the necessary guff for a Python-repl-alike interface
The execution of the code entered and all that stuff was taken from the
Python code module, I had to copy it instead of inheriting it, I can't
remember why. The rest of the stuff is basically what makes it fancy.
It reads what you type, passes it to a lexer and highlighter which
returns a formatted string. This then gets passed to echo() which
parses that string and prints to the curses screen in appropriate
colours and/or bold attribute.
The Repl class also keeps two stacks of lines that the user has typed in:
One to be used for the undo feature. I am not happy with the way this
works. The only way I have been able to think of is to keep the code
that's been typed in in memory and re-evaluate it in its entirety for each
"undo" operation. Obviously this means some operations could be extremely
slow. I'm not even by any means certain that this truly represents a
genuine "undo" implementation, but it does seem to be generally pretty
effective.
If anyone has any suggestions for how this could be improved, I'd be happy
to hear them and implement it/accept a patch. I researched a bit into the
idea of keeping the entire Python state in memory, but this really seems
very difficult (I believe it may actually be impossible to work) and has
its own problems too.
The other stack is for keeping a history for pressing the up/down keys
to go back and forth between lines.
"""#TODO: Split the class up a bit so the curses stuff isn't so integrated.
"""
"""
def __init__(self, scr, interp, statusbar=None, idle=None):
"""Initialise the repl with, unfortunately, a curses screen passed to
it. This needs to be split up so the curses crap isn't in here.
interp is a Python code.InteractiveInterpreter instance
The optional 'idle' parameter is a function that the repl call while
it's blocking (waiting for keypresses). This, again, should be in a
different class"""
self.cut_buffer = ''
self.buffer = []
self.scr = scr
self.interp = interp
self.match = False
self.rl_hist = []
self.stdout_hist = ''
self.s_hist = []
self.history = []
self.h_i = 0
self.in_hist = False
self.evaluating = False
self.do_exit = False
self.cpos = 0
# Use the interpreter's namespace only for the readline stuff:
self.completer = rlcompleter.Completer(self.interp.locals)
self.completer.attr_matches = self.attr_matches
# Gna, Py 2.6's rlcompleter searches for __call__ inside the
# instance instead of the type, so we monkeypatch to prevent
# side-effects (__getattr__/__getattribute__)
self.completer._callable_postfix = self._callable_postfix
self.statusbar = statusbar
self.list_win = newwin(1, 1, 1, 1)
self.idle = idle
self.f_string = ''
self.matches = []
self.matches_iter = MatchesIterator()
self.argspec = None
self.s = ''
self.inside_string = False
self.highlighted_paren = None
self.list_win_visible = False
self._C = {}
sys.stdin = FakeStdin(self)
self.paste_mode = False
self.last_key_press = time.time()
self.paste_time = OPTS.paste_time
self.prev_block_finished = 0
sys.path.insert(0, '.')
if not OPTS.arg_spec:
return
pythonhist = os.path.expanduser(OPTS.hist_file)
if os.path.exists(pythonhist):
with codecs.open(pythonhist, 'r', getpreferredencoding(),
'ignore') as hfile:
self.rl_hist = hfile.readlines()
def attr_matches(self, text):
"""Taken from rlcompleter.py and bent to my will."""
m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
if not m:
return []
expr, attr = m.group(1, 3)
if expr.isdigit():
# Special case: float literal, using attrs here will result in
# a SyntaxError
return []
obj = eval(expr, self.interp.locals)
with AttrCleaner(obj):
matches = self.attr_lookup(obj, expr, attr)
return matches
def attr_lookup(self, obj, expr, attr):
"""Second half of original attr_matches method factored out so it can
be wrapped in a safe try/finally block in case anything bad happens to
restore the original __getattribute__ method."""
words = dir(obj)
if hasattr(obj, '__class__'):
words.append('__class__')
words = words + rlcompleter.get_class_members(obj.__class__)
matches = []
n = len(attr)
for word in words:
if word[:n] == attr and word != "__builtins__":
matches.append("%s.%s" % (expr, word))
return matches
def _callable_postfix(self, value, word):
"""rlcompleter's _callable_postfix done right."""
with AttrCleaner(value):
if hasattr(value, '__call__'):
word += '('
return word
def current_string(self):
"""Return the current string.
Note: This method will not really work for multiline strings."""
inside_string = next_token_inside_string(self.s, self.inside_string)
if inside_string:
string = list()
next_char = ''
for (char, next_char) in zip(reversed(self.s),
reversed(self.s[:-1])):
if char == inside_string and next_char != '\\':
return ''.join(reversed(string))
string.append(char)
else:
if next_char == inside_string:
return ''.join(reversed(string))
return ''
def cw(self):
"""Return the current word, i.e. the (incomplete) word directly to the
left of the cursor"""
if self.cpos:
# I don't know if autocomplete should be disabled if the cursor
# isn't at the end of the line, but that's what this does for now.
return
l = len(self.s)
if (not self.s or
(not self.s[l-1].isalnum() and
self.s[l-1] not in ('.', '_'))):
return
i = 1
while i < l+1:
if not self.s[-i].isalnum() and self.s[-i] not in ('.', '_'):
break
i += 1
return self.s[-i +1:]
def get_args(self):
"""Check if an unclosed parenthesis exists, then attempt to get the
argspec() for it. On success, update self.argspec and return True,
otherwise set self.argspec to None and return False"""
self.current_func = None
def getpydocspec(f, func):
try:
argspec = pydoc.getdoc(f)
except NameError:
return None
rx = re.compile(r'([a-zA-Z_][a-zA-Z0-9_]*?)\((.*?)\)')
s = rx.search(argspec)
if s is None:
return None
if not hasattr(f, '__name__') or s.groups()[0] != f.__name__:
return None
args = [i.strip() for i in s.groups()[1].split(',')]
return [func, (args, None, None, None)]
def getargspec(func):
try:
if func in self.interp.locals:
f = self.interp.locals[func]
except TypeError:
return None
else:
try:
f = eval(func, self.interp.locals)
except Exception:
# Same deal with the exceptions :(
return None
else:
self.current_func = f
is_bound_method = inspect.ismethod(f) and f.im_self is not None
try:
if inspect.isclass(f):
self.current_func = f
argspec = inspect.getargspec(f.__init__)
self.current_func = f.__init__
is_bound_method = True
else:
argspec = inspect.getargspec(f)
self.current_func = f
argspec = list(argspec)
fixlongargs(f, argspec)
self.argspec = [func, argspec, is_bound_method]
return True
except (NameError, TypeError, KeyError):
with AttrCleaner(f):
t = getpydocspec(f, func)
if t is None:
return None
self.argspec = t
if inspect.ismethoddescriptor(f):
self.argspec[1][0].insert(0, 'obj')
self.argspec.append(is_bound_method)
return True
except AttributeError:
# This happens if no __init__ is found
return None
if not OPTS.arg_spec:
return False
stack = [['', 0, '']]
try:
for (token, value) in PythonLexer().get_tokens(self.s):
if token is Token.Punctuation:
if value in '([{':
stack.append(['', 0, value])
elif value in ')]}':
stack.pop()
elif value == ',':
try:
stack[-1][1] += 1
except TypeError:
stack[-1][1] = ''
elif (token is Token.Name or token in Token.Name.subtypes or
token is Token.Operator and value == '.'):
stack[-1][0] += value
elif token is Token.Operator and value == '=':
stack[-1][1] = stack[-1][0]
else:
stack[-1][0] = ''
while stack[-1][2] in '[{':
stack.pop()
_, arg_number, _ = stack.pop()
func, _, _ = stack.pop()
except IndexError:
return False
if getargspec(func):
self.argspec.append(arg_number)
return True
return False
def check(self):
"""Check if paste mode should still be active and, if not, deactivate
it and force syntax highlighting."""
if (self.paste_mode
and time.time() - self.last_key_press > self.paste_time):
self.paste_mode = False
self.print_line(self.s)
def complete(self, tab=False):
"""Wrap the _complete method to determine the visibility of list_win
since there can be several reasons why it won't be displayed; this
makes it more manageable."""
if self.paste_mode and self.list_win_visible:
self.scr.touchwin()
if self.paste_mode:
return
if self.list_win_visible and not OPTS.auto_display_list:
self.scr.touchwin()
self.list_win_visible = False
return
if OPTS.auto_display_list or tab:
self.list_win_visible = self._complete(tab)
if not self.list_win_visible:
self.scr.redrawwin()
self.scr.refresh()
return
def _complete(self, tab=False):
"""Construct a full list of possible completions and construct and
display them in a window. Also check if there's an available argspec
(via the inspect module) and bang that on top of the completions too.
The return value is whether the list_win is visible or not."""
if not self.get_args():
self.argspec = None
self.docstring = None
cw = self.cw()
cs = self.current_string()
if not cw:
self.matches = []
self.matches_iter.update()
if not (cw or cs or self.argspec):
return False
if cs and tab:
# Filename completion
self.matches = list()
user_dir = os.path.expanduser('~')
for filename in glob(os.path.expanduser(cs + '*')):
if os.path.isdir(filename):
filename += os.path.sep
if cs.startswith('~'):
filename = '~' + filename[len(user_dir):]
self.matches.append(filename)
self.matches_iter.update(cs, self.matches)
return bool(self.matches)
elif cs:
# Do not provide suggestions inside strings, as one cannot tab
# them so they would be really confusing.
return False
# Check for import completion
e = False
matches = importcompletion.complete(self.s, cw)
if matches is not None and not matches:
self.matches = []
self.matches_iter.update()
return False
if matches is None:
# Nope, no import, continue with normal completion
try:
self.completer.complete(cw, 0)
except Exception:
# This sucks, but it's either that or list all the exceptions that could
# possibly be raised here, so if anyone wants to do that, feel free to send me
# a patch. XXX: Make sure you raise here if you're debugging the completion
# stuff !
e = True
else:
matches = self.completer.matches
if not e and self.argspec:
matches.extend(name + '=' for name in self.argspec[1][0]
if name.startswith(cw))
if e or not matches:
self.matches = []
self.matches_iter.update()
if not self.argspec:
return False
if self.current_func is not None:
self.docstring = pydoc.getdoc(self.current_func)
if not self.docstring:
self.docstring = None
if not e and matches:
# remove duplicates and restore order
self.matches = sorted(set(matches))
if len(self.matches) == 1 and not OPTS.auto_display_list:
self.list_win_visible = True
self.tab()
return False
self.matches_iter.update(cw, self.matches)
try:
self.show_list(self.matches, self.argspec)
except curses.error:
# XXX: This is a massive hack, it will go away when I get
# cusswords into a good enough state that we can start using it.
self.list_win.border()
self.list_win.refresh()
return False
return True
def show_list(self, items, topline=None, current_item=None):
shared = Struct()
shared.cols = 0
shared.rows = 0
shared.wl = 0
y, x = self.scr.getyx()
h, w = self.scr.getmaxyx()
down = (y < h // 2)
if down:
max_h = h - y
else:
max_h = y+1
max_w = int(w * 0.8)
self.list_win.erase()
if items and '.' in items[0]:
items = [x.rsplit('.')[-1] for x in items]
if current_item:
current_item = current_item.rsplit('.')[-1]
if topline:
height_offset = self.mkargspec(topline, down) + 1
else:
height_offset = 0
def lsize():
wl = max(len(i) for i in v_items) + 1
if not wl:
wl = 1
cols = ((max_w - 2) // wl) or 1
rows = len(v_items) // cols
if cols * rows < len(v_items):
rows += 1
if rows + 2 >= max_h:
rows = max_h - 2
return False
shared.rows = rows
shared.cols = cols
shared.wl = wl
return True
if items:
# visible items (we'll append until we can't fit any more in)
v_items = [items[0][:max_w-3]]
lsize()
else:
v_items = []
for i in items[1:]:
v_items.append(i[:max_w-3])
if not lsize():
del v_items[-1]
v_items[-1] = '...'
break
rows = shared.rows
if rows + height_offset < max_h:
rows += height_offset
display_rows = rows
else:
display_rows = rows + height_offset
cols = shared.cols
wl = shared.wl
if topline and not v_items:
w = max_w
elif wl + 3 > max_w:
w = max_w
else:
t = (cols + 1) * wl + 3
if t > max_w:
t = max_w
w = t
if height_offset and display_rows+5 >= max_h:
del v_items[-(cols * (height_offset)):]
if self.docstring is None:
self.list_win.resize(rows + 2, w)
else:
docstring = self.format_docstring(self.docstring, max_w - 2,
max_h - height_offset)
docstring_string = ''.join(docstring)
rows += len(docstring)
self.list_win.resize(rows, max_w)
if down:
self.list_win.mvwin(y + 1, 0)
else:
self.list_win.mvwin(y - rows - 2, 0)
if v_items:
self.list_win.addstr('\n ')
for ix, i in enumerate(v_items):
padding = (wl - len(i)) * ' '
if i == current_item:
color = get_colpair('operator')
else:
color = get_colpair('main')
self.list_win.addstr(i + padding, color)
if ((cols == 1 or (ix and not (ix+1) % cols))
and ix + 1 < len(v_items)):
self.list_win.addstr('\n ')
if self.docstring is not None:
self.list_win.addstr('\n' + docstring_string, get_colpair('comment'))
# XXX: After all the trouble I had with sizing the list box (I'm not very good
# at that type of thing) I decided to do this bit of tidying up here just to
# make sure there's no unnececessary blank lines, it makes things look nicer.
y = self.list_win.getyx()[0]
self.list_win.resize(y + 2, w)
self.statusbar.win.touchwin()
self.statusbar.win.noutrefresh()
self.list_win.attron(get_colpair('main'))
self.list_win.border()
self.scr.touchwin()
self.scr.cursyncup()
self.scr.noutrefresh()
# This looks a little odd, but I can't figure a better way to stick the cursor
# back where it belongs (refreshing the window hides the list_win)
self.scr.move(*self.scr.getyx())
self.list_win.refresh()
def format_docstring(self, docstring, width, height):
"""Take a string and try to format it into a sane list of strings to be
put into the suggestion box."""