-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathlang_css.py
More file actions
1622 lines (1463 loc) · 69.9 KB
/
lang_css.py
File metadata and controls
1622 lines (1463 loc) · 69.9 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
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is Komodo code.
#
# The Initial Developer of the Original Code is ActiveState Software Inc.
# Portions created by ActiveState Software Inc are Copyright (C) 2000-2007
# ActiveState Software Inc. All Rights Reserved.
#
# Contributor(s):
# ActiveState Software Inc
# Sergey Kislyakov
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
"""CSS support for CodeIntel"""
from __future__ import absolute_import
from __future__ import print_function
import os
from os.path import isfile, isdir, exists, dirname, abspath, splitext, join
import sys
import stat
import string
from six.moves import cStringIO as StringIO
import logging
import traceback
from pprint import pprint
import operator
import re
import SilverCity
from SilverCity.Lexer import Lexer
from SilverCity import ScintillaConstants
from SilverCity.ScintillaConstants import (
SCE_CSS_DIRECTIVE, SCE_CSS_DOUBLESTRING, SCE_CSS_IDENTIFIER,
SCE_CSS_IDENTIFIER2, SCE_CSS_OPERATOR, SCE_CSS_SINGLESTRING,
SCE_CSS_TAG, SCE_CSS_UNKNOWN_IDENTIFIER, SCE_CSS_VALUE,
SCE_UDL_CSS_COMMENT, SCE_UDL_CSS_DEFAULT, SCE_UDL_CSS_IDENTIFIER,
SCE_UDL_CSS_NUMBER, SCE_UDL_CSS_OPERATOR, SCE_UDL_CSS_STRING,
SCE_UDL_CSS_WORD, SCE_UDL_M_STRING, SCE_UDL_M_ATTRNAME, SCE_UDL_M_OPERATOR,
)
from SilverCity import Keywords
from ciElementTree import SubElement
from codeintel2.citadel import CitadelBuffer, CitadelLangIntel, ImportHandler
from codeintel2.common import *
from codeintel2.buffer import Buffer
from codeintel2.util import (OrdPunctLast, make_short_name_dict,
makePerformantLogger, walk2)
from codeintel2.langintel import ParenStyleCalltipIntelMixin
from codeintel2.gencix_utils import *
from codeintel2.udl import UDLBuffer, is_udl_css_style
from codeintel2.accessor import AccessorCache
from six.moves import range
if _xpcom_:
from xpcom.server import UnwrapObject
try:
string_ascii_lowercase = string.ascii_lowercase
string_ascii_uppercase = string.ascii_uppercase
string_digits = string.digits
except AttributeError:
string_ascii_lowercase = string.lowercase
string_ascii_uppercase = string.uppercase
string_digits = string.digits
#---- globals
lang = "CSS"
log = logging.getLogger("codeintel.css")
makePerformantLogger(log)
WHITESPACE = tuple(" \t\r\n") # care about '\v', '\f'?
#---- language support
# Taken from the Scite version 2.0.2 css.properties file
# Silvercity wants the # of wordlists to be the same as the
# number hardwired in the lexer, so that's why there are 5 empty lists.
raw_word_lists = [
# CSS1 keywords
"""
background background-attachment background-color background-image
background-position background-repeat border border-bottom
border-bottom-width border-color border-left border-left-width
border-right border-right-width border-style border-top
border-top-width border-width
clear color display float font
font-family font-size font-style font-variant font-weight height
letter-spacing line-height list-style list-style-image
list-style-position list-style-type margin margin-bottom margin-left
margin-right margin-top padding padding-bottom padding-left
padding-right padding-top text-align text-decoration text-indent
text-transform vertical-align white-space width word-spacing
""",
# CSS pseudo-classes
"""
active after before first first-child first-letter first-line
focus hover lang left link right visited
""",
# CSS2 keywords
"""
ascent azimuth baseline bbox border-bottom-color
border-bottom-style border-collapse border-color border-left-color
border-left-style border-right-color border-right-style
border-spacing border-style border-top-color border-top-style
bottom cap-height caption-side centerline clip content
counter-increment counter-reset cue cue-after cue-before cursor
definition-src descent direction elevation empty-cells
font-size-adjust font-stretch left marker-offset marks mathline
max-height max-width min-height min-width orphans outline
outline-color outline-style outline-width overflow page
page-break-after page-break-before page-break-inside panose-1
pause pause-after pause-before pitch pitch-range play-during
position quotes richness right size slope speak speak-header
speak-numeral speak-punctuation speech-rate src stemh stemv stress
table-layout text-shadow top topline unicode-bidi unicode-range
units-per-em visibility voice-family volume widows widths x-height
z-index
""",
# CSS3 Properties
"""
border-top-left-radius
border-top-right-radius
border-bottom-left-radius
border-bottom-right-radius
border-radius
""",
# Pseudo-elements
"",
# Browser-Specific CSS Properties
"",
# Browser-Specific Pseudo-classes
"",
# Browser-Specific Pseudo-elements
"",
]
class CSSLexer(Lexer):
lang = "CSS"
def __init__(self):
self._properties = SilverCity.PropertySet()
self._lexer = SilverCity.find_lexer_module_by_id(ScintillaConstants.SCLEX_CSS)
self._keyword_lists = []
for i in range(len(raw_word_lists)):
self._keyword_lists.append(SilverCity.WordList(raw_word_lists[i]))
class _StraightCSSStyleClassifier(object):
def is_css_style(self, style, accessorCacheBack=None):
return True
def is_default(self, style, accessorCacheBack=None):
return style in self.default_styles
def is_comment(self, style, accessorCacheBack=None):
return style in self.comment_styles
def is_string(self, style, accessorCacheBack=None):
return style in self.string_styles
def is_operator(self, style, accessorCacheBack=None):
return style in self.operator_styles or \
style == ScintillaConstants.SCE_CSS_IMPORTANT
def is_identifier(self, style, accessorCacheBack=None):
return style in self.identifier_styles
def is_value(self, style, accessorCacheBack=None):
return style in self.value_styles
def is_tag(self, style, accessorCacheBack=None):
return style in self.tag_styles
def is_class(self, style, accessorCacheBack=None):
return style in self.class_styles
def is_number(self, style, accessorCacheBack=None):
return style in self.number_styles
def is_directive(self, style, accessorCacheBack=None):
return style == ScintillaConstants.SCE_CSS_DIRECTIVE
@property
def default_styles(self):
return (ScintillaConstants.SCE_CSS_DEFAULT, )
@property
def comment_styles(self):
return (ScintillaConstants.SCE_CSS_COMMENT,)
@property
def string_styles(self):
return (ScintillaConstants.SCE_CSS_SINGLESTRING,
ScintillaConstants.SCE_CSS_DOUBLESTRING)
@property
def operator_styles(self):
return (ScintillaConstants.SCE_CSS_OPERATOR, )
@property
def identifier_styles(self):
return (ScintillaConstants.SCE_CSS_IDENTIFIER,
ScintillaConstants.SCE_CSS_IDENTIFIER2,
ScintillaConstants.SCE_CSS_UNKNOWN_IDENTIFIER)
@property
def value_styles(self):
return (ScintillaConstants.SCE_CSS_VALUE,
ScintillaConstants.SCE_CSS_NUMBER)
@property
def tag_styles(self):
return (ScintillaConstants.SCE_CSS_TAG, )
@property
def class_styles(self):
return (ScintillaConstants.SCE_CSS_CLASS, )
@property
def number_styles(self):
return ()
@property
def ignore_styles(self):
return (ScintillaConstants.SCE_CSS_DEFAULT,
ScintillaConstants.SCE_CSS_COMMENT)
DebugStatus = False
class _UDLCSSStyleClassifier(_StraightCSSStyleClassifier):
def is_css_style(self, style, accessorCacheBack=None):
return is_udl_css_style(style)
def _is_html_style_attribute(self, ac, style):
# Check to see if it's a html style attribute
# Note: We are starting from the html string delimiter, i.e.:
# <body style=<|>"abc...
DEBUG = DebugStatus
# We may have already found out this is a style attribute, check it
if getattr(ac, "is_html_style_attribute", False):
return True
p, ch, style = ac.getPrecedingPosCharStyle(style,
ignore_styles=self.ignore_styles)
if DEBUG:
print(" _is_html_style_attribute:: Prev style: %d, ch: %r" % (
style, ch, ))
if style == SCE_UDL_M_OPERATOR:
p, ch, style = ac.getPrecedingPosCharStyle(style,
ignore_styles=self.ignore_styles)
if style == SCE_UDL_M_ATTRNAME:
p, name = ac.getTextBackWithStyle(style)
if DEBUG:
print(" _is_html_style_attribute:: HTML Attribute: %r" % (
name, ))
if name == "style":
# Remember this is a html style attribute
ac.is_html_style_attribute = True
return True
return False
def is_identifier(self, style, accessorCacheBack=None):
if style not in self.identifier_styles:
return False
# Previous style must be operator and one of "{;"
ac = accessorCacheBack
if ac is not None:
DEBUG = DebugStatus
#DEBUG = True
pcs = ac.getCurrentPosCharStyle()
if DEBUG:
print(" is_identifier:: pcs: %r" % (pcs, ))
try:
# Check that the preceding character before the identifier
ppcs = ac.getPrecedingPosCharStyle(pcs[2],
ignore_styles=self.ignore_styles)
if DEBUG:
print(" is_identifier:: ppcs: %r" % (ppcs, ))
if self.is_operator(ppcs[2]) and ppcs[1] in "{;":
return True
elif ppcs[2] == SCE_UDL_M_STRING and \
self._is_html_style_attribute(ac, ppcs[2]):
return True
if DEBUG:
print(" is_identifier:: Not an identifier style")
finally:
# Reset the accessor back to the current position
ac.resetToPosition(pcs[0])
return False
def is_class(self, style, accessorCacheBack=None):
ac = accessorCacheBack
if ac is not None:
pcs = ac.getCurrentPosCharStyle()
print(" is_class:: pcs: %r" % (pcs, ))
if self.is_operator(pcs[2]) and pcs[1] in ">.;}{":
return True
try:
DEBUG = DebugStatus
# Check that the preceding character before the identifier is a "."
ppcs = ac.getPrecedingPosCharStyle(pcs[2],
ignore_styles=self.ignore_styles)
if DEBUG:
print(" is_class:: ppcs: %r" % (ppcs, ))
if ppcs[2] in self.identifier_styles:
ppcs = ac.getPrecedingPosCharStyle(ppcs[2],
ignore_styles=self.ignore_styles)
if self.is_operator(ppcs[2]) and ppcs[1] == ".":
return True
elif not is_udl_css_style(ppcs[2]):
return True
# If there is no identifer, may be operator, which is okay
elif not is_udl_css_style(ppcs[2]) or \
(self.is_operator(ppcs[2]) and ppcs[1] in "};"):
return True
if DEBUG:
print(" is_class:: Not a class style")
finally:
# Reset the accessor back to the current position
ac.resetToPosition(pcs[0])
return False
def is_tag(self, style, accessorCacheBack=None):
ac = accessorCacheBack
if ac is not None:
# Tags follow operators or other tags
# For use, we'll go back until we find an operator in "}>"
if style in self.identifier_styles:
DEBUG = DebugStatus
p, ch, style = ac.getCurrentPosCharStyle()
start_p = p
min_p = max(0, p - 50)
try:
while p > min_p:
# Check that the preceding character before the identifier is a "."
p, ch, style = ac.getPrecedingPosCharStyle(style,
ignore_styles=self.ignore_styles)
if style in self.operator_styles:
# Thats good, we get our decision now
if ch in "}>":
return True
elif ch == ",":
# Might be following another tag, "div, div",
# http://bugs.activestate.com/show_bug.cgi?id=58637
continue
if DEBUG:
print(" is_tag:: Not a tag operator ch: %s" % (ch))
return False
elif not self.is_css_style(style):
if DEBUG:
print(" is_tag:: Not a css style: %d, ch: %r" % (style, ch, ))
if style == SCE_UDL_M_STRING and \
self._is_html_style_attribute(ac, style):
return False
return True
elif style not in self.identifier_styles:
if DEBUG:
print(" is_tag:: Not a tag style, style: %d" % (style))
return False
# else: # Thats okay, we'll keep going
finally:
# Reset the accessor back to the current position
ac.resetToPosition(start_p)
return False
@property
def default_styles(self):
return (ScintillaConstants.SCE_UDL_CSS_DEFAULT, )
@property
def comment_styles(self):
return (ScintillaConstants.SCE_UDL_CSS_COMMENT,)
@property
def string_styles(self):
return (ScintillaConstants.SCE_UDL_CSS_STRING, )
@property
def operator_styles(self):
return (ScintillaConstants.SCE_UDL_CSS_OPERATOR, )
@property
def identifier_styles(self):
return (ScintillaConstants.SCE_UDL_CSS_IDENTIFIER,
ScintillaConstants.SCE_UDL_CSS_WORD)
@property
def value_styles(self):
return (ScintillaConstants.SCE_UDL_CSS_WORD,
ScintillaConstants.SCE_UDL_CSS_IDENTIFIER,
ScintillaConstants.SCE_UDL_CSS_NUMBER)
@property
def tag_styles(self):
return (ScintillaConstants.SCE_CSS_TAG, )
@property
def number_styles(self):
return (ScintillaConstants.SCE_UDL_CSS_NUMBER, )
@property
def ignore_styles(self):
return (ScintillaConstants.SCE_UDL_CSS_DEFAULT,
ScintillaConstants.SCE_UDL_CSS_COMMENT)
StraightCSSStyleClassifier = _StraightCSSStyleClassifier()
UDLCSSStyleClassifier = _UDLCSSStyleClassifier()
class CSSLangIntel(CitadelLangIntel, ParenStyleCalltipIntelMixin):
lang = "CSS"
@LazyClassAttribute
def CSS_ATTRIBUTES(self):
# CSS attributes:
# key (string) is the css property (attribute) name
# value (list) is the possible css property (attribute) values
from codeintel2 import constants_css3 as constants_css
from codeintel2 import constants_css_microsoft_extensions
from codeintel2 import constants_css_moz_extensions
from codeintel2 import constants_css_webkit_extensions
attrs = constants_css.CSS_ATTR_DICT.copy()
attrs.update(constants_css_microsoft_extensions.CSS_MICROSOFT_SPECIFIC_ATTRS_DICT)
attrs.update(constants_css_moz_extensions.CSS_MOZ_SPECIFIC_ATTRS_DICT)
attrs.update(constants_css_webkit_extensions.CSS_WEBKIT_SPECIFIC_ATTRS_DICT)
return attrs
@LazyClassAttribute
def CSS_PROPERTY_NAMES(self):
# Setup the names triggered for "property-names"
return sorted(list(self.CSS_ATTRIBUTES.keys()), key=OrdPunctLast)
@LazyClassAttribute
def CSS_PROPERTY_ATTRIBUTE_CALLTIPS_DICT(self):
# Calltips for css property attributes
from codeintel2 import constants_css3 as constants_css
from codeintel2 import constants_css_microsoft_extensions
from codeintel2 import constants_css_moz_extensions
from codeintel2 import constants_css_webkit_extensions
calltips = constants_css.CSS_PROPERTY_ATTRIBUTE_CALLTIPS_DICT.copy()
calltips.update(constants_css_microsoft_extensions.CSS_MICROSOFT_SPECIFIC_CALLTIP_DICT)
calltips.update(constants_css_moz_extensions.CSS_MOZ_SPECIFIC_CALLTIP_DICT)
calltips.update(constants_css_webkit_extensions.CSS_WEBKIT_SPECIFIC_CALLTIP_DICT)
return calltips
@LazyClassAttribute
def CSS_HTML_TAG_NAMES(self):
# Tag names
return sorted(Keywords.hypertext_elements.split())
@LazyClassAttribute
def CSS_PSEUDO_CLASS_NAMES(self):
# pseudo-class-names
from codeintel2 import constants_css3 as constants_css
return sorted(constants_css.CSS_PSEUDO_CLASS_NAMES, key=OrdPunctLast)
@LazyClassAttribute
def CSS_AT_RULE_NAMES(self):
# at rules
return sorted(["import", "media", "charset", "font-face", "page", "namespace", "keyframes"],
key=OrdPunctLast)
@LazyClassAttribute
def SCSS_AT_RULE_NAMES(self):
return sorted(self.CSS_AT_RULE_NAMES +
["extend", "at-root", "debug", "warn", "error", "if",
"for", "each", "while", "mixin", "include",
"function"], key=OrdPunctLast)
def preceding_trg_from_pos(self, buf, pos, curr_pos):
DEBUG = DebugStatus # not using 'logging' system, because want to be fast
#DEBUG = True # not using 'logging' system, because want to be fast
if DEBUG:
print("\npreceding_trg_from_pos -- pos: %d, curr_pos: %d" % (
pos, curr_pos, ))
if isinstance(buf, UDLBuffer):
styleClassifier = UDLCSSStyleClassifier
else:
styleClassifier = StraightCSSStyleClassifier
ac = AccessorCache(buf.accessor, curr_pos+1, fetchsize=50)
currTrg = self._trg_from_pos(buf, (curr_pos == pos) and pos or pos+1,
implicit=False, DEBUG=DEBUG,
ac=ac, styleClassifier=styleClassifier)
if DEBUG:
print(" currTrg: %r" % (currTrg, ))
# If we're not looking for a previous trigger, or else the current
# trigger position is for a calltip, then do not look any further.
if (pos == curr_pos) or (currTrg and currTrg.form == TRG_FORM_CALLTIP):
return currTrg
# Else, work our way backwards from pos.
ac.resetToPosition(pos+1)
p, ch, style = ac.getPrevPosCharStyle()
if DEBUG:
print(" preceding_trg_from_pos: p: %r, ch: %r, style: %r" % (p, ch, style))
min_p = max(0, p - 200)
ignore_styles = styleClassifier.comment_styles + \
styleClassifier.string_styles + \
styleClassifier.number_styles
while p > min_p and styleClassifier.is_css_style(style):
p, ch, style = ac.getPrecedingPosCharStyle(style, ignore_styles=ignore_styles, max_look_back=100)
if DEBUG:
print(" preceding_trg_from_pos: Trying preceding p: %r, ch: %r, style: %r" % (p, ch, style))
if ch and (isident(ch) or ch in ":( \t"):
trg = self._trg_from_pos(buf, p+1, implicit=False, DEBUG=DEBUG,
ac=ac, styleClassifier=styleClassifier)
if trg is not None:
if DEBUG:
print("trg: %r" % (trg, ))
if currTrg is not None:
if currTrg.type != trg.type:
if DEBUG:
print(" Next trigger is a different type, ending search")
return None
elif currTrg.form != trg.form:
return trg
elif DEBUG:
print(" Found same trigger again, continuing " \
"looking for a different trigger")
else:
return trg
return None
def _trg_from_pos(self, buf, pos, implicit=True, DEBUG=False, ac=None, styleClassifier=None):
#DEBUG = True # not using 'logging' system, because want to be fast
if DEBUG:
print("\n----- CSS _trg_from_pos(pos=%r, implicit=%r) -----"\
% (pos, implicit))
try:
if pos == 0:
return None
if ac is None:
ac = AccessorCache(buf.accessor, pos, fetchsize=50)
else:
ac.resetToPosition(pos)
# Ensure this variable is initialized as False, it is used by UDL
# for checking if the css style is inside of a html tag, example:
# <p style="mycss: value;" />
# When it's found that it is such a case, this value is set True
ac.is_html_style_attribute = False
last_pos, last_char, last_style = ac.getPrevPosCharStyle()
if DEBUG:
print(" _trg_from_pos:: last_pos: %s" % last_pos)
print(" last_char: %r" % last_char)
print(" last_style: %s" % last_style)
# The easy ones are triggering after any of '#.[: '.
# For speed, let's get the common ' ' out of the way. The only
# trigger on space is 'complete-property-values'.
if styleClassifier.is_default(last_style):
if DEBUG:
print(" _trg_from_pos:: Default style: %d, ch: %r" % (last_style, last_char))
# Move backwards resolving ambiguity, default on "property-values"
min_pos = max(0, pos - 200)
while last_pos > min_pos:
last_pos, last_char, last_style = ac.getPrevPosCharStyle()
if styleClassifier.is_operator(last_style, ac) or styleClassifier.is_value(last_style, ac):
if DEBUG:
print(" _trg_from_pos: space => property-values")
return Trigger("CSS", TRG_FORM_CPLN, "property-values",
pos, implicit)
elif styleClassifier.is_tag(last_style, ac):
if DEBUG:
print(" _trg_from_pos: space => tag-names")
return Trigger("CSS", TRG_FORM_CPLN, "tag-names",
pos, implicit)
elif styleClassifier.is_identifier(last_style, ac):
if DEBUG:
print(" _trg_from_pos: space => property-names")
return Trigger("CSS", TRG_FORM_CPLN, "property-names",
pos, implicit)
if DEBUG:
print(" _trg_from_pos: couldn't resolve space, settling on property-names")
return Trigger("CSS", TRG_FORM_CPLN, "property-values",
pos, implicit)
elif styleClassifier.is_operator(last_style, ac):
# anchors
if DEBUG:
print(" _trg_from_pos:: OPERATOR style")
if last_char == '#':
return Trigger("CSS", TRG_FORM_CPLN, "anchors",
pos, implicit)
elif last_char == ':':
try:
p, ch, style = ac.getPrevPosCharStyle(ignore_styles=styleClassifier.ignore_styles)
if DEBUG:
print(" _trg_from_pos:: Looking at p: %d, ch: %r, style: %d" % (p, ch, style))
except IndexError:
style = None
if DEBUG:
print(" _trg_from_pos:: style: %r" % (style))
if style is None or \
not styleClassifier.is_identifier(style, ac):
#if style is None or \
# not styleClassifier.is_css_style(style) or \
# styleClassifier.is_class(style, ac):
# complete for pseudo-class-names
return Trigger("CSS", TRG_FORM_CPLN, "pseudo-class-names",
pos, implicit)
else:
#if styleClassifier.is_identifier(style, ac):
# calltip for property-values
return Trigger("CSS", TRG_FORM_CALLTIP, "property-values",
pos, implicit)
# class-names
elif last_char == '.':
return Trigger("CSS", TRG_FORM_CPLN, "class-names",
pos, implicit)
# at-rule
elif last_char == '@':
#p, ch, style = ac.getPrevPosCharStyle(ignore_styles=styleClassifier.comment_styles)
# XXX - Should check not beyond first rule set
# - Should check not within a rule block.
return Trigger("CSS", TRG_FORM_CPLN, "at-rule",
pos, implicit)
elif last_char == '/':
try:
p, ch, style = ac.getPrevPosCharStyle()
except IndexError:
pass
else:
if ch == "<":
# Looks like start of closing '</style>'
# tag. While typing this the styling will
# still be in the CSS range.
return Trigger(buf.m_lang, TRG_FORM_CPLN,
"end-tag", pos, implicit)
# tag-names
elif styleClassifier.is_tag(last_style, ac):
# We trigger on tag names of specified length >= 1 char
if DEBUG:
print(" _trg_from_pos:: TAG style")
p, ch, style = last_pos, last_char, last_style
try:
while p >= 0:
if DEBUG:
print(" _trg_from_pos:: Looking at p: %d, ch: %r, style: %d" % (p, ch, style))
if not isident(ch):
p += 1
break
elif style != last_style:
if DEBUG:
print(" _trg_from_pos:: Current style is not a tag: %d" % (style))
return None
p, ch, style = ac.getPrevPosCharStyle()
except IndexError:
p = 0
return Trigger("CSS", TRG_FORM_CPLN, "tag-names",
p, implicit)
elif styleClassifier.is_identifier(last_style, ac):
if DEBUG:
print(" _trg_from_pos:: IDENTIFIER style")
# property-names
#print "here", accessor.text_range(0, pos)
# We trigger on identifier names with any length >= 1 char
pos = last_pos
while pos >= 0:
pos, ch, style = ac.getPrevPosCharStyle()
if not isident(ch):
break
elif style != last_style:
return None
extentLength = last_pos - pos
# cover ": " following the identifier if it's there (since we
# add it to the autocomplete in _async_eval_at_trg)
following_text = ac.text_range(last_pos + 1, last_pos + 3)
for idx, char in enumerate(": "):
try:
if following_text[idx] == char:
extentLength += 1
else:
break
except IndexError:
break
return Trigger("CSS", TRG_FORM_CPLN, "property-names",
pos+1, implicit, extentLength=extentLength)
elif styleClassifier.is_value(last_style, ac):
p, ch, style = ac.getPrevPosCharStyle(ignore_styles=styleClassifier.comment_styles)
if DEBUG:
print(" _trg_from_pos:: VALUE style")
print(" _trg_from_pos:: p: %s" % p)
print(" _trg_from_pos:: ch: %r" % ch)
print(" _trg_from_pos:: style: %s" % style)
ac.dump()
# Implicit triggering only happens on a whitespace character
# after any one of these ":,%) " characters
# Note: last_char can be a value style yet also be whitespace
# in straight CSS.
if last_char in WHITESPACE:
return Trigger("CSS", TRG_FORM_CPLN, "property-values",
last_pos+1, implicit)
elif ch in WHITESPACE or ch in ":,%)":
# Check to ensure this is not a pseudo-class! Bug:
# http://bugs.activestate.com/show_bug.cgi?id=71073
if ch == ":":
# Last style must be an identifier then!
pp, pch, pstyle = ac.getPrevPosCharStyle(
ignore_styles=styleClassifier.ignore_styles)
if DEBUG:
print("pp: %d, pch: %r, pstyle: %d" % (pp, pch,
pstyle))
if not styleClassifier.is_identifier(pstyle, ac):
# This is likely a pseudo-class definition then,
# no trigger here.
if DEBUG:
print("pseudo-class style found, no trigger.")
return None
return Trigger("CSS", TRG_FORM_CPLN, "property-values",
p+1, implicit)
# For explicit, we can also be inside a property already
if not implicit and isident(ch):
# If there is already part of a value there, we need to move
# the trigger point "p" to the start of the value.
while isident(ch):
p, ch, style = ac.getPrevPosCharStyle()
return Trigger("CSS", TRG_FORM_CPLN, "property-values",
p+1, implicit)
return None
elif DEBUG:
print(" _trg_from_pos:: Unexpected style: %d, ch: %r" % (last_style, last_char))
# XXX "at-property-names" - Might be used later
#elif last_style == SCE_CSS_DIRECTIVE:
# # property-names
# # We trigger on identifier names with length == 3
# #print "here", accessor.text_range(0, pos)
# if pos >= 4 and accessor.char_at_pos(pos - 4) == ' ' and \
# self._is_ident_of_length(accessor, pos, length=3):
# # We are good for completion
# if DEBUG:
# print "Got a trigger for 'at-property-names'"
# return Trigger("CSS", TRG_FORM_CPLN, "at-property-names",
# pos-3, implicit)
except IndexError:
# Wen't out of range of buffer before we found anything useful
pass
if DEBUG:
print("----- CSS trg_from_pos() -----")
return None
def trg_from_pos(self, buf, pos, implicit=True, ac=None):
DEBUG = DebugStatus # not using 'logging' system, because want to be fast
if isinstance(buf, UDLBuffer):
# This is CSS content in a multi-lang buffer.
return self._trg_from_pos(buf, pos, implicit, DEBUG, ac, UDLCSSStyleClassifier)
else:
return self._trg_from_pos(buf, pos, implicit, DEBUG, ac, StraightCSSStyleClassifier)
def _async_eval_at_trg(self, buf, trg, ctlr, styleClassifier):
# Note: Currently this is NOT asynchronous. I believe that is fine
# as long as evaluation is fast -- because the IDE UI thread could
# be blocked on this. If processing might be slow (e.g. scanning
# a number of project files for appropriate anchors, etc.), then
# this should be made asynchronous.
DEBUG = DebugStatus
#DEBUG = True
if DEBUG:
print("\n----- async_eval_at_trg(trg=%r) -----"\
% (trg))
# Setup the AccessorCache
extra = trg.extra
ac = None
#print "Extra: %r" % (extra)
if isinstance(extra, dict):
extra = extra.get("extra", None)
if isinstance(extra, dict):
ac = extra.get("ac", None)
if ac and DEBUG:
print(" _async_eval_at_trg:: Trigger had existing AC")
ac.dump()
if ac is None:
if DEBUG:
print(" _async_eval_at_trg:: Created new trigger!")
ac = AccessorCache(buf.accessor, trg.pos, fetchsize=20)
ctlr.start(buf, trg)
pos = trg.pos
try:
if trg.id == ("CSS", TRG_FORM_CPLN, "tag-names"):
if DEBUG:
print(" _async_eval_at_trg:: 'tag-names'")
cplns = self.CSS_HTML_TAG_NAMES
if DEBUG:
print(" _async_eval_at_trg:: cplns:", cplns)
if cplns:
ctlr.set_cplns( [ ("element", v) for v in cplns ] )
ctlr.done("success")
elif trg.id == ("CSS", TRG_FORM_CPLN, "anchors") or \
trg.id == ("CSS", TRG_FORM_CPLN, "class-names"):
cplns = set() # prevent duplicates (#foo, #foo:hover, etc.).
ilk = CSSSelector.ID if trg.id[2] == "anchors" else \
CSSSelector.CLASS
# Autocomplete anchors or class names from the current file.
if self.lang in buf.blob_from_lang:
blob = buf.blob_from_lang[self.lang]
for elem in blob:
if elem.get("ilk") == ilk:
cplns.add((ilk, elem.get("target")))
# Autocomplete anchors or class names from all CSS files in the
# project or the current directory and its sub-directories.
cwd = buf.env and buf.env.get_proj_base_dir() or dirname(buf.path)
if cwd != "<Unsaved>":
import_handler = \
self.mgr.citadel.import_handler_from_lang(trg.lang)
importables = import_handler.find_importables_in_dir(cwd)
files = [i[0] for i in importables.values()]
for file in files:
try:
buf = self.mgr.buf_from_path(file, lang=trg.lang)
blob = buf.blob_from_lang[trg.lang]
for elem in blob:
if elem.get("ilk") == ilk:
cplns.add((ilk, elem.get("target")))
except (EnvironmentError, CodeIntelError) as ex:
# This can occur if the path does not exist, such as
# a broken symlink, or we don't have permission to
# read the file, or the file does not contain text.
continue
# Sort and return completions.
if cplns:
ctlr.set_cplns(sorted([v for v in cplns]))
ctlr.done("success")
elif trg.id == ("CSS", TRG_FORM_CPLN, "property-names"):
cplns = self.CSS_PROPERTY_NAMES
if cplns:
# Note: we add the colon as well - see bug 89913.
ctlr.set_cplns( [ ("property", v + ": ") for v in cplns ] )
# We want to show the property values after autocompleting.
trg.retriggerOnCompletion = True
#print " _async_eval_at_trg:: cplns:", cplns
ctlr.done("success")
elif trg.id == ("CSS", TRG_FORM_CALLTIP, "property-values"):
property, v1, v2 \
= self._extract_css_declaration(ac, styleClassifier, trg,
is_for_calltip=True)
if DEBUG:
print(" _async_eval_at_trg:: Property name: %r" % \
(property, ))
try:
calltip = self.CSS_PROPERTY_ATTRIBUTE_CALLTIPS_DICT[property]
if DEBUG:
print(" _async_eval_at_trg:: calltip:", calltip)
ctlr.set_calltips([calltip])
except KeyError:
#print "Unknown CSS property: '%s'" % (property)
pass # Ignore unknown CSS attributes
ctlr.done("success")
elif trg.id == ("CSS", TRG_FORM_CPLN, "property-values"):
property, current_value, values \
= self._extract_css_declaration(ac, styleClassifier, trg)
if DEBUG:
print(" _async_eval_at_trg:: XXX property: %r, " \
" current_value: %r, values: %r" % (property,
current_value,
values))
try:
#print "\ndict:", self.CSS_ATTRIBUTES[property]
property_values = sorted(self.CSS_ATTRIBUTES[property],
key=OrdPunctLast)
# Check if it matches anything, if not, dismiss the list
if current_value:
clen = len(current_value)
for v in property_values:
if clen <= len(v) and current_value == v[:clen]:
# Found a match
break
# Else, return the full list, even though no match made
# XXX - May want to cancel the CC list, any way to do this?
cplns = [("value", v)
for v in property_values
if v not in values or v == current_value]
ctlr.set_cplns(cplns)
except KeyError:
if DEBUG:
print(" _async_eval_at_trg:: Unknown CSS property: "\
"'%s'" % (property))
pass # Ignore unknown CSS attributes
ctlr.done("success")
#XXX Handling for property not in list.
elif trg.id == ("CSS", TRG_FORM_CPLN, "pseudo-class-names"):
cplns = [("pseudo-class", v)
for v in self.CSS_PSEUDO_CLASS_NAMES]
ctlr.set_cplns(cplns)
ctlr.done("success")
elif trg.id == ("CSS", TRG_FORM_CPLN, "at-rule"):
if self.lang != "SCSS" and self.lang != "Sass":
cplns = [("rule", v)
for v in self.CSS_AT_RULE_NAMES]
else:
cplns = [("rule", v)
for v in self.SCSS_AT_RULE_NAMES]
ctlr.set_cplns(cplns)
ctlr.done("success")
# Punt - Lower priority
#elif trg.id == ("CSS", TRG_FORM_CPLN, "units"):
# Punt - Fancy
#elif trg.id == ("CSS", TRG_FORM_CPLN, "import-url"):
# Punt - uncommon
#elif trg.id == ("CSS", TRG_FORM_CPLN, "attr-names"):
#elif trg.id == ("CSS", TRG_FORM_CPLN, "attr-values"):
else:
raise NotImplementedError("not yet implemented: completion for "
"most css triggers: trg.id: %s" % (trg.id,))
except IndexError:
# Tried to go out of range of buffer, nothing appropriate found
if DEBUG:
print(" _async_eval_at_trg:: ** Out of range error **")
ctlr.done("success")
def async_eval_at_trg(self, buf, trg, ctlr):
if isinstance(buf, UDLBuffer):
# This is CSS content in a multi-lang buffer.
return self._async_eval_at_trg(buf, trg, ctlr,
UDLCSSStyleClassifier)
else:
return self._async_eval_at_trg(buf, trg, ctlr,
StraightCSSStyleClassifier)
def _get_all_anchors_names_in_project(self):
#anchors = []
#pos = 0
#LENGTH = accessor.length()
#style = 0
#func_style_at_pos = accessor.style_at_pos
#func_char_at_pos = accessor.char_at_pos
#while pos < LENGTH:
# if func_char_at_pos(pos) == '#' and \
# func_style_at_pos(pos) == SCE_CSS_OPERATOR:
# # Likely an anchor
# pass
# pos += 1
#return anchors
return []
def _is_ident_of_length(self, accessor, pos, length=3):
# Fourth char to left should not be an identifier
if pos > length and isident(accessor.char_at_pos((pos - length) - 1)):
return False
# chars to left should all be identifiers
for i in range(pos - 1, (pos - length) -1, -1):
if not isident(accessor.char_at_pos(i)):
return False
return True
def _extract_css_declaration(self, ac, styleClassifier, trg,
is_for_calltip=False):