/
mixins.py
1616 lines (1394 loc) · 63.1 KB
/
mixins.py
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
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""Mix-in classes
These classes were created to be able to provide Spyder's regular text and
console widget features to an independent widget based on QTextEdit for the
IPython console plugin.
"""
# Standard library imports
from __future__ import print_function
import os
import os.path as osp
import re
import sre_constants
import sys
import textwrap
# Third party imports
from qtpy.QtCore import QPoint, QRegularExpression, Qt
from qtpy.QtGui import QCursor, QTextCursor, QTextDocument
from qtpy.QtWidgets import QApplication
from qtpy import QT_VERSION
from spyder_kernels.utils.dochelpers import (getargspecfromtext, getobj,
getsignaturefromtext)
# Local imports
from spyder.config.manager import CONF
from spyder.py3compat import is_text_string, to_text_string
from spyder.utils import encoding, sourcecode
from spyder.utils import syntaxhighlighters as sh
from spyder.utils.misc import get_error_match
from spyder.utils.palette import QStylePalette
from spyder.widgets.arraybuilder import ArrayBuilderDialog
class BaseEditMixin(object):
_PARAMETER_HIGHLIGHT_COLOR = QStylePalette.COLOR_ACCENT_4
_DEFAULT_TITLE_COLOR = QStylePalette.COLOR_ACCENT_4
_CHAR_HIGHLIGHT_COLOR = QStylePalette.COLOR_ACCENT_4
_DEFAULT_TEXT_COLOR = QStylePalette.COLOR_TEXT_2
_DEFAULT_LANGUAGE = 'python'
_DEFAULT_MAX_LINES = 10
_DEFAULT_MAX_WIDTH = 60
_DEFAULT_COMPLETION_HINT_MAX_WIDTH = 52
_DEFAULT_MAX_HINT_LINES = 20
_DEFAULT_MAX_HINT_WIDTH = 85
# The following signals are used to indicate text changes on the editor.
sig_will_insert_text = None
sig_will_remove_selection = None
sig_text_was_inserted = None
_styled_widgets = set()
def __init__(self):
self.eol_chars = None
self.calltip_size = 600
#------Line number area
def get_linenumberarea_width(self):
"""Return line number area width"""
# Implemented in CodeEditor, but needed for calltip/completion widgets
return 0
def calculate_real_position(self, point):
"""
Add offset to a point, to take into account the Editor panels.
This is reimplemented in CodeEditor, in other widgets it returns
the same point.
"""
return point
# --- Tooltips and Calltips
def _calculate_position(self, at_line=None, at_point=None):
"""
Calculate a global point position `QPoint(x, y)`, for a given
line, local cursor position, or local point.
"""
font = self.font()
if at_point is not None:
# Showing tooltip at point position
margin = (self.document().documentMargin() / 2) + 1
cx = int(at_point.x() - margin)
cy = int(at_point.y() - margin)
elif at_line is not None:
# Showing tooltip at line
cx = 5
line = at_line - 1
cursor = QTextCursor(self.document().findBlockByNumber(line))
cy = int(self.cursorRect(cursor).top())
else:
# Showing tooltip at cursor position
cx, cy = self.get_coordinates('cursor')
cx = int(cx)
cy = int(cy - font.pointSize() / 2)
# Calculate vertical delta
# The needed delta changes with font size, so we use a power law
if sys.platform == 'darwin':
delta = int((font.pointSize() * 1.20) ** 0.98 + 4.5)
elif os.name == 'nt':
delta = int((font.pointSize() * 1.20) ** 1.05) + 7
else:
delta = int((font.pointSize() * 1.20) ** 0.98) + 7
# delta = font.pointSize() + 5
# Map to global coordinates
point = self.mapToGlobal(QPoint(cx, cy))
point = self.calculate_real_position(point)
point.setY(point.y() + delta)
return point
def _update_stylesheet(self, widget):
"""Update the background stylesheet to make it lighter."""
# Update the stylesheet for a given widget at most once
# because Qt is slow to repeatedly parse & apply CSS
if id(widget) in self._styled_widgets:
return
self._styled_widgets.add(id(widget))
background = QStylePalette.COLOR_BACKGROUND_4
border = QStylePalette.COLOR_TEXT_4
name = widget.__class__.__name__
widget.setObjectName(name)
css = '''
{0}#{0} {{
background-color:{1};
border: 1px solid {2};
}}'''.format(name, background, border)
widget.setStyleSheet(css)
def _get_inspect_shortcut(self):
"""
Queries the editor's config to get the current "Inspect" shortcut.
"""
value = CONF.get('shortcuts', 'editor/inspect current object')
if value:
if sys.platform == "darwin":
value = value.replace('Ctrl', 'Cmd')
return value
def _format_text(self, title=None, signature=None, text=None,
inspect_word=None, title_color=None, max_lines=None,
max_width=_DEFAULT_MAX_WIDTH, display_link=False,
text_new_line=False, with_html_format=False):
"""
Create HTML template for calltips and tooltips.
This will display title and text as separate sections and add `...`
----------------------------------------
| `title` (with `title_color`) |
----------------------------------------
| `signature` |
| |
| `text` (ellided to `max_lines`) |
| |
----------------------------------------
| Link or shortcut with `inspect_word` |
----------------------------------------
"""
BASE_TEMPLATE = u'''
<div style=\'font-family: "{font_family}";
font-size: {size}pt;
color: {color}\'>
{main_text}
</div>
'''
# Get current font properties
font = self.font()
font_family = font.family()
title_size = font.pointSize()
text_size = title_size - 1 if title_size > 9 else title_size
text_color = self._DEFAULT_TEXT_COLOR
template = ''
if title:
template += BASE_TEMPLATE.format(
font_family=font_family,
size=title_size,
color=title_color,
main_text=title,
)
if text or signature:
template += '<hr>'
if signature:
signature = signature.strip('\r\n')
template += BASE_TEMPLATE.format(
font_family=font_family,
size=text_size,
color=text_color,
main_text=signature,
)
# Documentation/text handling
if (text is None or not text.strip() or
text.strip() == '<no docstring>'):
text = '<i>No documentation available</i>'
else:
text = text.strip()
if not with_html_format:
# All these replacements are need to properly divide the
# text in actual paragraphs and wrap the text on each one
paragraphs = (text
.replace(u"\xa0", u" ")
.replace("\n\n", "<!DOUBLE_ENTER!>")
.replace(".\n", ".<!SINGLE_ENTER!>")
.replace("\n-", "<!SINGLE_ENTER!>-")
.replace("-\n", "-<!SINGLE_ENTER!>")
.replace("\n=", "<!SINGLE_ENTER!>=")
.replace("=\n", "=<!SINGLE_ENTER!>")
.replace("\n*", "<!SINGLE_ENTER!>*")
.replace("*\n", "*<!SINGLE_ENTER!>")
.replace("\n ", "<!SINGLE_ENTER!> ")
.replace(" \n", " <!SINGLE_ENTER!>")
.replace("\n", " ")
.replace("<!DOUBLE_ENTER!>", "\n\n")
.replace("<!SINGLE_ENTER!>", "\n").splitlines())
new_paragraphs = []
for paragraph in paragraphs:
# Wrap text
new_paragraph = textwrap.wrap(paragraph, width=max_width)
# Remove empty lines at the beginning
new_paragraph = [l for l in new_paragraph if l.strip()]
# Merge paragraph text
new_paragraph = '\n'.join(new_paragraph)
# Add new paragraph
new_paragraphs.append(new_paragraph)
# Join paragraphs and split in lines for max_lines check
paragraphs = '\n'.join(new_paragraphs)
paragraphs = paragraphs.strip('\r\n')
lines = paragraphs.splitlines()
# Check that the first line is not empty
if len(lines) > 0 and not lines[0].strip():
lines = lines[1:]
else:
lines = [l for l in text.split('\n') if l.strip()]
# Limit max number of text displayed
if max_lines:
if len(lines) > max_lines:
text = '\n'.join(lines[:max_lines]) + ' ...'
else:
text = '\n'.join(lines)
text = text.replace('\n', '<br>')
if text_new_line and signature:
text = '<br>' + text
template += BASE_TEMPLATE.format(
font_family=font_family,
size=text_size,
color=text_color,
main_text=text,
)
help_text = ''
if inspect_word:
if display_link:
help_text = (
'<span style="font-family: \'{font_family}\';'
'font-size:{font_size}pt;">'
'Click anywhere in this tooltip for additional help'
'</span>'.format(
font_size=text_size,
font_family=font_family,
)
)
else:
shortcut = self._get_inspect_shortcut()
if shortcut:
base_style = (
f'background-color:{QStylePalette.COLOR_BACKGROUND_4};'
f'color:{QStylePalette.COLOR_TEXT_1};'
'font-size:11px;'
)
help_text = ''
# (
# 'Press '
# '<kbd style="{1}">[</kbd>'
# '<kbd style="{1}text-decoration:underline;">'
# '{0}</kbd><kbd style="{1}">]</kbd> for aditional '
# 'help'.format(shortcut, base_style)
# )
if help_text and inspect_word:
if display_link:
template += (
'<hr>'
'<div align="left">'
f'<span style="color: {QStylePalette.COLOR_ACCENT_4};'
'text-decoration:none;'
'font-family:"{font_family}";font-size:{size}pt;><i>'
''.format(font_family=font_family,
size=text_size)
) + help_text + '</i></span></div>'
else:
template += (
'<hr>'
'<div align="left">'
'<span style="color:white;text-decoration:none;">'
'' + help_text + '</span></div>'
)
return template
def _format_signature(self, signatures, parameter=None,
max_width=_DEFAULT_MAX_WIDTH,
parameter_color=_PARAMETER_HIGHLIGHT_COLOR,
char_color=_CHAR_HIGHLIGHT_COLOR,
language=_DEFAULT_LANGUAGE):
"""
Create HTML template for signature.
This template will include indent after the method name, a highlight
color for the active parameter and highlights for special chars.
Special chars depend on the language.
"""
language = getattr(self, 'language', language).lower()
active_parameter_template = (
'<span style=\'font-family:"{font_family}";'
'font-size:{font_size}pt;'
'color:{color}\'>'
'<b>{parameter}</b>'
'</span>'
)
chars_template = (
'<span style="color:{0};'.format(self._CHAR_HIGHLIGHT_COLOR) +
'font-weight:bold">{char}'
'</span>'
)
def handle_sub(matchobj):
"""
Handle substitution of active parameter template.
This ensures the correct highlight of the active parameter.
"""
match = matchobj.group(0)
new = match.replace(parameter, active_parameter_template)
return new
if not isinstance(signatures, list):
signatures = [signatures]
new_signatures = []
for signature in signatures:
# Remove duplicate spaces
signature = ' '.join(signature.split())
# Replace initial spaces
signature = signature.replace('( ', '(')
# Process signature template
if parameter and language == 'python':
# Escape all possible regex characters
# ( ) { } | [ ] . ^ $ * +
escape_regex_chars = ['|', '.', '^', '$', '*', '+']
remove_regex_chars = ['(', ')', '{', '}', '[', ']']
regex_parameter = parameter
for regex_char in escape_regex_chars + remove_regex_chars:
if regex_char in escape_regex_chars:
escape_char = r'\{char}'.format(char=regex_char)
regex_parameter = regex_parameter.replace(regex_char,
escape_char)
else:
regex_parameter = regex_parameter.replace(regex_char,
'')
parameter = parameter.replace(regex_char, '')
pattern = (r'[\*|\(|\[|\s](' + regex_parameter +
r')[,|\)|\]|\s|=]')
formatted_lines = []
name = signature.split('(')[0]
indent = ' ' * (len(name) + 1)
rows = textwrap.wrap(signature, width=max_width,
subsequent_indent=indent)
for row in rows:
if parameter and language == 'python':
# Add template to highlight the active parameter
row = re.sub(pattern, handle_sub, row)
row = row.replace(' ', ' ')
row = row.replace('span ', 'span ')
row = row.replace('{}', '{{}}')
if language and language == 'python':
for char in ['(', ')', ',', '*', '**']:
new_char = chars_template.format(char=char)
row = row.replace(char, new_char)
formatted_lines.append(row)
title_template = '<br>'.join(formatted_lines)
# Get current font properties
font = self.font()
font_size = font.pointSize()
font_family = font.family()
# Format title to display active parameter
if parameter and language == 'python':
title = title_template.format(
font_size=font_size,
font_family=font_family,
color=parameter_color,
parameter=parameter,
)
else:
title = title_template
new_signatures.append(title)
return '<br>'.join(new_signatures)
def _check_signature_and_format(self, signature_or_text, parameter=None,
inspect_word=None,
max_width=_DEFAULT_MAX_WIDTH,
language=_DEFAULT_LANGUAGE):
"""
LSP hints might provide docstrings instead of signatures.
This method will check for multiple signatures (dict, type etc...) and
format the text accordingly.
"""
open_func_char = ''
has_signature = False
has_multisignature = False
language = getattr(self, 'language', language).lower()
signature_or_text = signature_or_text.replace('\\*', '*')
# Remove special symbols that could itefere with ''.format
signature_or_text = signature_or_text.replace('{', '{')
signature_or_text = signature_or_text.replace('}', '}')
# Remove 'ufunc' signature if needed. See spyder-ide/spyder#11821
lines = [line for line in signature_or_text.split('\n')
if 'ufunc' not in line]
signature_or_text = '\n'.join(lines)
if language == 'python':
open_func_char = '('
has_multisignature = False
if inspect_word:
has_signature = signature_or_text.startswith(inspect_word)
else:
idx = signature_or_text.find(open_func_char)
inspect_word = signature_or_text[:idx]
has_signature = True
if has_signature:
name_plus_char = inspect_word + open_func_char
all_lines = []
for line in lines:
if (line.startswith(name_plus_char)
and line.count(name_plus_char) > 1):
sublines = line.split(name_plus_char)
sublines = [name_plus_char + l for l in sublines]
sublines = [l.strip() for l in sublines]
else:
sublines = [line]
all_lines = all_lines + sublines
lines = all_lines
count = 0
for line in lines:
if line.startswith(name_plus_char):
count += 1
# Signature type
has_signature = count == 1
has_multisignature = count > 1 and len(lines) > 1
if has_signature and not has_multisignature:
for i, line in enumerate(lines):
if line.strip() == '':
break
if i == 0:
signature = lines[0]
extra_text = None
else:
signature = '\n'.join(lines[:i])
extra_text = '\n'.join(lines[i:])
if signature:
new_signature = self._format_signature(
signatures=signature,
parameter=parameter,
max_width=max_width
)
elif has_multisignature:
signature = signature_or_text.replace(name_plus_char,
'<br>' + name_plus_char)
signature = signature[4:] # Remove the first line break
signature = signature.replace('\n', ' ')
signature = signature.replace(r'\\*', '*')
signature = signature.replace(r'\*', '*')
signature = signature.replace('<br>', '\n')
signatures = signature.split('\n')
signatures = [sig for sig in signatures if sig] # Remove empty
new_signature = self._format_signature(
signatures=signatures,
parameter=parameter,
max_width=max_width
)
extra_text = None
else:
new_signature = None
extra_text = signature_or_text
return new_signature, extra_text, inspect_word
def show_calltip(self, signature, parameter=None, documentation=None,
language=_DEFAULT_LANGUAGE, max_lines=_DEFAULT_MAX_LINES,
max_width=_DEFAULT_MAX_WIDTH, text_new_line=True):
"""
Show calltip.
Calltips look like tooltips but will not disappear if mouse hovers
them. They are useful for displaying signature information on methods
and functions.
"""
# Find position of calltip
point = self._calculate_position()
signature = signature.strip()
inspect_word = None
language = getattr(self, 'language', language).lower()
if language == 'python' and signature:
inspect_word = signature.split('(')[0]
# Check if documentation is better than signature, sometimes
# signature has \n stripped for functions like print, type etc
check_doc = ' '
if documentation:
check_doc.join(documentation.split()).replace('\\*', '*')
check_sig = ' '.join(signature.split())
if check_doc == check_sig:
signature = documentation
documentation = ''
# Remove duplicate signature inside documentation
if documentation:
documentation = documentation.replace('\\*', '*')
if signature.strip():
documentation = documentation.replace(signature + '\n', '')
# Format
res = self._check_signature_and_format(signature, parameter,
inspect_word=inspect_word,
language=language,
max_width=max_width)
new_signature, text, inspect_word = res
text = self._format_text(
signature=new_signature,
inspect_word=inspect_word,
display_link=False,
text=documentation,
max_lines=max_lines,
max_width=max_width,
text_new_line=text_new_line
)
self._update_stylesheet(self.calltip_widget)
# Show calltip
self.calltip_widget.show_tip(point, text, [])
self.calltip_widget.show()
def show_tooltip(self, title=None, signature=None, text=None,
inspect_word=None, title_color=_DEFAULT_TITLE_COLOR,
at_line=None, at_point=None, display_link=False,
max_lines=_DEFAULT_MAX_LINES,
max_width=_DEFAULT_MAX_WIDTH,
cursor=None,
with_html_format=False,
text_new_line=True,
completion_doc=None):
"""Show tooltip."""
# Find position of calltip
point = self._calculate_position(
at_line=at_line,
at_point=at_point,
)
# Format text
tiptext = self._format_text(
title=title,
signature=signature,
text=text,
title_color=title_color,
inspect_word=inspect_word,
display_link=display_link,
max_lines=max_lines,
max_width=max_width,
with_html_format=with_html_format,
text_new_line=text_new_line
)
self._update_stylesheet(self.tooltip_widget)
# Display tooltip
self.tooltip_widget.show_tip(point, tiptext, cursor=cursor,
completion_doc=completion_doc)
def show_hint(self, text, inspect_word, at_point,
max_lines=_DEFAULT_MAX_HINT_LINES,
max_width=_DEFAULT_MAX_HINT_WIDTH,
text_new_line=True, completion_doc=None):
"""Show code hint and crop text as needed."""
res = self._check_signature_and_format(text, max_width=max_width,
inspect_word=inspect_word)
html_signature, extra_text, _ = res
point = self.get_word_start_pos(at_point)
# Only display hover hint if there is documentation
if extra_text is not None:
# This is needed to get hover hints
cursor = self.cursorForPosition(at_point)
cursor.movePosition(QTextCursor.StartOfWord,
QTextCursor.MoveAnchor)
self._last_hover_cursor = cursor
self.show_tooltip(signature=html_signature, text=extra_text,
at_point=point, inspect_word=inspect_word,
display_link=True, max_lines=max_lines,
max_width=max_width, cursor=cursor,
text_new_line=text_new_line,
completion_doc=completion_doc)
def hide_tooltip(self):
"""
Hide the tooltip widget.
The tooltip widget is a special QLabel that looks like a tooltip,
this method is here so it can be hidden as necessary. For example,
when the user leaves the Linenumber area when hovering over lint
warnings and errors.
"""
self._last_hover_cursor = None
self._last_hover_word = None
self._last_point = None
self.tooltip_widget.hide()
# ----- Required methods for the LSP
def document_did_change(self, text=None):
pass
#------EOL characters
def set_eol_chars(self, text):
"""Set widget end-of-line (EOL) characters from text (analyzes text)"""
if not is_text_string(text): # testing for QString (PyQt API#1)
text = to_text_string(text)
eol_chars = sourcecode.get_eol_chars(text)
is_document_modified = eol_chars is not None and self.eol_chars is not None
self.eol_chars = eol_chars
if is_document_modified:
self.document().setModified(True)
if self.sig_eol_chars_changed is not None:
self.sig_eol_chars_changed.emit(eol_chars)
self.document_did_change(text)
def get_line_separator(self):
"""Return line separator based on current EOL mode"""
if self.eol_chars is not None:
return self.eol_chars
else:
return os.linesep
def get_text_with_eol(self):
"""
Same as 'toPlainText', replacing '\n' by correct end-of-line
characters.
"""
text = self.toPlainText()
lines = text.splitlines()
linesep = self.get_line_separator()
text_with_eol = linesep.join(lines)
if text.endswith('\n'):
text_with_eol += linesep
return text_with_eol
#------Positions, coordinates (cursor, EOF, ...)
def get_position(self, subject):
"""Get offset in character for the given subject from the start of
text edit area"""
cursor = self.textCursor()
if subject == 'cursor':
pass
elif subject == 'sol':
cursor.movePosition(QTextCursor.StartOfBlock)
elif subject == 'eol':
cursor.movePosition(QTextCursor.EndOfBlock)
elif subject == 'eof':
cursor.movePosition(QTextCursor.End)
elif subject == 'sof':
cursor.movePosition(QTextCursor.Start)
else:
# Assuming that input argument was already a position
return subject
return cursor.position()
def get_coordinates(self, position):
position = self.get_position(position)
cursor = self.textCursor()
cursor.setPosition(position)
point = self.cursorRect(cursor).center()
return point.x(), point.y()
def _is_point_inside_word_rect(self, point):
"""
Check if the mouse is within the rect of the cursor current word.
"""
cursor = self.cursorForPosition(point)
cursor.movePosition(QTextCursor.StartOfWord, QTextCursor.MoveAnchor)
start_rect = self.cursorRect(cursor)
cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.MoveAnchor)
end_rect = self.cursorRect(cursor)
bounding_rect = start_rect.united(end_rect)
return bounding_rect.contains(point)
def get_word_start_pos(self, position):
"""
Find start position (lower bottom) of a word being hovered by mouse.
"""
cursor = self.cursorForPosition(position)
cursor.movePosition(QTextCursor.StartOfWord, QTextCursor.MoveAnchor)
rect = self.cursorRect(cursor)
pos = QPoint(rect.left() + 4, rect.top())
return pos
def get_last_hover_word(self):
"""Return the last (or active) hover word."""
return self._last_hover_word
def get_last_hover_cursor(self):
"""Return the last (or active) hover cursor."""
return self._last_hover_cursor
def get_cursor_line_column(self, cursor=None):
"""
Return `cursor` (line, column) numbers.
If no `cursor` is provided, use the current text cursor.
"""
if cursor is None:
cursor = self.textCursor()
return cursor.blockNumber(), cursor.columnNumber()
def get_cursor_line_number(self):
"""Return cursor line number"""
return self.textCursor().blockNumber()+1
def get_position_line_number(self, line, col):
"""Get position offset from (line, col) coordinates."""
block = self.document().findBlockByNumber(line)
cursor = QTextCursor(block)
cursor.movePosition(QTextCursor.StartOfBlock)
cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor,
n=col + 1)
return cursor.position()
def set_cursor_position(self, position):
"""Set cursor position"""
position = self.get_position(position)
cursor = self.textCursor()
cursor.setPosition(position)
self.setTextCursor(cursor)
self.ensureCursorVisible()
def move_cursor(self, chars=0):
"""Move cursor to left or right (unit: characters)"""
direction = QTextCursor.Right if chars > 0 else QTextCursor.Left
for _i in range(abs(chars)):
self.moveCursor(direction, QTextCursor.MoveAnchor)
def is_cursor_on_first_line(self):
"""Return True if cursor is on the first line"""
cursor = self.textCursor()
cursor.movePosition(QTextCursor.StartOfBlock)
return cursor.atStart()
def is_cursor_on_last_line(self):
"""Return True if cursor is on the last line"""
cursor = self.textCursor()
cursor.movePosition(QTextCursor.EndOfBlock)
return cursor.atEnd()
def is_cursor_at_end(self):
"""Return True if cursor is at the end of the text"""
return self.textCursor().atEnd()
def is_cursor_before(self, position, char_offset=0):
"""Return True if cursor is before *position*"""
position = self.get_position(position) + char_offset
cursor = self.textCursor()
cursor.movePosition(QTextCursor.End)
if position < cursor.position():
cursor.setPosition(position)
return self.textCursor() < cursor
def __move_cursor_anchor(self, what, direction, move_mode):
assert what in ('character', 'word', 'line')
if what == 'character':
if direction == 'left':
self.moveCursor(QTextCursor.PreviousCharacter, move_mode)
elif direction == 'right':
self.moveCursor(QTextCursor.NextCharacter, move_mode)
elif what == 'word':
if direction == 'left':
self.moveCursor(QTextCursor.PreviousWord, move_mode)
elif direction == 'right':
self.moveCursor(QTextCursor.NextWord, move_mode)
elif what == 'line':
if direction == 'down':
self.moveCursor(QTextCursor.NextBlock, move_mode)
elif direction == 'up':
self.moveCursor(QTextCursor.PreviousBlock, move_mode)
def move_cursor_to_next(self, what='word', direction='left'):
"""
Move cursor to next *what* ('word' or 'character')
toward *direction* ('left' or 'right')
"""
self.__move_cursor_anchor(what, direction, QTextCursor.MoveAnchor)
#------Selection
def extend_selection_to_next(self, what='word', direction='left'):
"""
Extend selection to next *what* ('word' or 'character')
toward *direction* ('left' or 'right')
"""
self.__move_cursor_anchor(what, direction, QTextCursor.KeepAnchor)
#------Text: get, set, ...
def __select_text(self, position_from, position_to):
position_from = self.get_position(position_from)
position_to = self.get_position(position_to)
cursor = self.textCursor()
cursor.setPosition(position_from)
cursor.setPosition(position_to, QTextCursor.KeepAnchor)
return cursor
def get_text_line(self, line_nb):
"""Return text line at line number *line_nb*"""
block = self.document().findBlockByNumber(line_nb)
cursor = QTextCursor(block)
cursor.movePosition(QTextCursor.StartOfBlock)
cursor.movePosition(QTextCursor.EndOfBlock, mode=QTextCursor.KeepAnchor)
return to_text_string(cursor.selectedText())
def get_text_region(self, start_line, end_line):
"""Return text lines spanned from *start_line* to *end_line*."""
start_block = self.document().findBlockByNumber(start_line)
end_block = self.document().findBlockByNumber(end_line)
start_cursor = QTextCursor(start_block)
start_cursor.movePosition(QTextCursor.StartOfBlock)
end_cursor = QTextCursor(end_block)
end_cursor.movePosition(QTextCursor.EndOfBlock)
end_position = end_cursor.position()
start_cursor.setPosition(end_position, mode=QTextCursor.KeepAnchor)
return self.get_selected_text(start_cursor)
def get_text(self, position_from, position_to, remove_newlines=True):
"""Returns text between *position_from* and *position_to*.
Positions may be integers or 'sol', 'eol', 'sof', 'eof' or 'cursor'.
Unless position_from='sof' and position_to='eof' any trailing newlines
in the string are removed. This was added as a workaround for
spyder-ide/spyder#1546 and later caused spyder-ide/spyder#14374.
The behaviour can be overridden by setting the optional parameter
*remove_newlines* to False.
TODO: Evaluate if this is still a problem and if the workaround can
be moved closer to where the problem occurs.
"""
cursor = self.__select_text(position_from, position_to)
text = to_text_string(cursor.selectedText())
if remove_newlines:
remove_newlines = position_from != 'sof' or position_to != 'eof'
if text and remove_newlines:
while text.endswith("\n"):
text = text[:-1]
while text.endswith(u"\u2029"):
text = text[:-1]
return text
def get_character(self, position, offset=0):
"""Return character at *position* with the given offset."""
position = self.get_position(position) + offset
cursor = self.textCursor()
cursor.movePosition(QTextCursor.End)
if position < cursor.position():
cursor.setPosition(position)
cursor.movePosition(QTextCursor.Right,
QTextCursor.KeepAnchor)
return to_text_string(cursor.selectedText())
else:
return ''
def insert_text(self, text, will_insert_text=True):
"""Insert text at cursor position"""
if not self.isReadOnly():
if will_insert_text and self.sig_will_insert_text is not None:
self.sig_will_insert_text.emit(text)
self.textCursor().insertText(text)
if self.sig_text_was_inserted is not None:
self.sig_text_was_inserted.emit()
self.document_did_change()
def replace_text(self, position_from, position_to, text):
cursor = self.__select_text(position_from, position_to)
if self.sig_will_remove_selection is not None:
start, end = self.get_selection_start_end(cursor)
self.sig_will_remove_selection.emit(start, end)
cursor.removeSelectedText()
if self.sig_will_insert_text is not None:
self.sig_will_insert_text.emit(text)
cursor.insertText(text)
if self.sig_text_was_inserted is not None:
self.sig_text_was_inserted.emit()
self.document_did_change()
def remove_text(self, position_from, position_to):
cursor = self.__select_text(position_from, position_to)
if self.sig_will_remove_selection is not None:
start, end = self.get_selection_start_end(cursor)
self.sig_will_remove_selection.emit(start, end)
cursor.removeSelectedText()
self.document_did_change()
def get_current_object(self):
"""
Return current object under cursor.
Get the text of the current word plus all the characters
to the left until a space is found. Used to get text to inspect
for Help of elements following dot notation for example
np.linalg.norm
"""
cursor = self.textCursor()
cursor_pos = cursor.position()
current_word = self.get_current_word(help_req=True)
# Get max position to the left of cursor until space or no more
# characters are left
cursor.movePosition(QTextCursor.PreviousCharacter)
while self.get_character(cursor.position()).strip():
cursor.movePosition(QTextCursor.PreviousCharacter)
if cursor.atBlockStart():
break
cursor_pos_left = cursor.position()
# Get max position to the right of cursor until space or no more
# characters are left
cursor.setPosition(cursor_pos)
while self.get_character(cursor.position()).strip():
cursor.movePosition(QTextCursor.NextCharacter)
if cursor.atBlockEnd():
break
cursor_pos_right = cursor.position()
# Get text of the object under the cursor
current_text = self.get_text(
cursor_pos_left, cursor_pos_right).strip()
current_object = current_word
if current_text and current_word is not None:
if current_word != current_text and current_word in current_text:
current_object = (
current_text.split(current_word)[0] + current_word)
return current_object
def get_current_word_and_position(self, completion=False, help_req=False,
valid_python_variable=True):
"""
Return current word, i.e. word at cursor position, and the start