File: aliases.py

package info (click to toggle)
gnat-gps 18-5
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 45,716 kB
  • sloc: ada: 362,679; python: 31,031; xml: 9,597; makefile: 1,030; ansic: 917; sh: 264; java: 17
file content (324 lines) | stat: -rw-r--r-- 9,835 bytes parent folder | download
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
"""
This file provides the core functionality for interactive aliases expansion
in GPS
"""

from GPS import Hook, Alias, EditorBuffer, execute_action
import GPS
from gps_utils import interactive
import six
from collections import defaultdict
from text_utils import goto_word_start
import re
from color_utils import Color

subst_pattern = re.compile("%\(.*?\)|%_")
id_pattern = re.compile(r"[^\w0-9_]")

color_pref_name = "Src-Editor-Ephemeral-Smart"


def get_paragraph_color():
    """
    Get the preference corresponding to paragraph background
    color, and turn it into an hex string
    """
    pref_string = GPS.Preference("Src-Editor-Reference-Style").get()
    c = Color(pref_string.split("@")[2])
    return c.hex, c.shade_or_lighten(0.1).hex


def get_comments_colors():
    """
    Get the preference corresponding to comment color
    """
    _, c1, c2 = GPS.Preference("Src-Editor-Comments-Variant")\
                   .get().split("@")
    if c2 == "white" or c2 == "rgb(255,255,255)":
        c2 = None
    return c1, c2


def get_current_field_bg_color():
    """
    Get the background color that should be used to highlight
    aliases' current fields.
    """
    _, _, bg_color = GPS.Preference(color_pref_name).get().split("@")
    return bg_color


def reset_overlay(editor):
    """
    Reset the aliases overlay completely
    """
    editor.remove_overlay(
        editor.aliases_overlay,
        editor.alias_begin_mark.location(),
        editor.alias_end_mark.location()
    )


def is_in_alias_expansion(editor):
    """
    Returns true if the editor is in the process of alias expansion
    """
    return bool(getattr(editor, "current_alias_mark_index", None))


def exit_alias_expand(editor):
    """
    Exit alias expansion.
    """
    editor.remove_all_slave_cursors()
    reset_overlay(editor)
    editor.remove_overlay(
        editor.aliases_background_overlay,
        editor.alias_begin_mark.location().beginning_of_line(),
        editor.alias_end_mark.location()
    )
    editor.remove_overlay(
        editor.aliases_background_overlay_1,
        editor.beginning_of_buffer(),
        editor.end_of_buffer()
    )
    editor.current_alias_mark_index = None
    editor.alias_marks = None
    editor.alias_end_mark = None
    editor.alias_begin_mark = None
    Hook("character_added").remove(on_edit)
    Hook("location_changed").remove(on_move)


@interactive("Editor", name="Expand alias under cursor")
def expand_alias_action():
    """
    Action to expand the alias under cursor
    the editor
    """
    editor = EditorBuffer.get(open=False, force=False)
    if not editor:
        return

    if is_in_alias_expansion(editor):
        return
    with editor.new_undo_group():
        cursor_loc = editor.current_view().cursor().forward_char(-1)
        start_loc = goto_word_start(cursor_loc)
        alias_name = editor.get_chars(start_loc, cursor_loc)
        editor.delete(start_loc, cursor_loc)
        alias = Alias.get(alias_name)
        if alias:
            expand_alias(editor, alias)


@interactive("Editor", name="Toggle to next alias field")
def toggle_next_field(editor=None):
    """
    When in alias expansion, toggle to next field
    """

    if not editor:
        editor = EditorBuffer.get()

    try:
        reset_overlay(editor)

        editor.apply_overlay(
            editor.aliases_background_overlay_1,
            editor.beginning_of_buffer(),
            editor.end_of_buffer()
        )

        editor.apply_overlay(
            editor.aliases_background_overlay,
            editor.alias_begin_mark.location().beginning_of_line(),
            editor.alias_end_mark.location()
        )

        i = editor.current_alias_mark_index

        if i is None:
            return

        if i >= len(editor.alias_marks):
            if editor.last_alias_mark:
                editor.current_view().goto(
                    editor.last_alias_mark.location()
                )
                exit_alias_expand(editor)
                # ??? Doesn't work every time if executed only once
                execute_action("autoindent selection")
                execute_action("autoindent selection")
            else:
                exit_alias_expand(editor)
            return

        editor.remove_all_slave_cursors()
        marks = editor.alias_marks[i]

        # Delete the placeholder text
        for mark_start, mark_end in marks:
            lstart = mark_start.location()
            lend = mark_end.location().forward_char(-1)
            if lend >= lstart:
                editor.delete(lstart, lend)

        editor.current_view().goto(marks[0][0].location())
        try:
            execute_action("autoindent selection")
        except Exception:
            pass

        reset_overlay(editor)

        # Add multi cursors for every other mark
        if len(marks) > 1:
            for mark_begin, mark_end in marks[1:]:
                editor.add_cursor(mark_begin.location())

        editor.current_alias_mark_index += 1

    except AttributeError:
        return


def apply_overlay(editor, mark_start, mark_end, overlay):
    """
    Apply overlay overlay between mark_start and mark end
    if mark_start - mark_end >= 1 char
    """
    lstart = mark_start.location()
    lend = mark_end.location().forward_char(-1)
    if lend >= lstart:
        editor.apply_overlay(overlay, lstart, lend)


def on_edit(hook_name, file_name):
    """
    Event handler on insert/delete. Mainly ensures that the current field
    in alias expansion is highlighted (via the aliases overlay)
    """
    editor = EditorBuffer.get(file_name)

    # This hook is global: it could happen that we are calling it on another
    # editor than the one where the alias expansion is occurring: simply
    # return in this case.
    if not is_in_alias_expansion(editor):
        return

    if editor.current_alias_mark_index > 0:
        marks_list = editor.alias_marks[
            editor.current_alias_mark_index - 1
        ]
        reset_overlay(editor)
        for mark_start, mark_end in marks_list:
            apply_overlay(editor, mark_start, mark_end,
                          editor.aliases_overlay)


def on_move(hook_name, file_name, line, column):
    """
    Event handler on cursor move. Gets out of alias expansion mode
    when the cursor gets out of the zone.
    """
    editor = EditorBuffer.get(file_name)

    # This hook is global: it could happen that we are calling it on another
    # editor than the one where the alias expansion is occurring: simply
    # return in this case.
    if not is_in_alias_expansion(editor):
        return

    index = editor.current_alias_mark_index - 1
    start_mark, end_mark = editor.alias_marks[index][0]
    start_loc = start_mark.location()
    end_loc = end_mark.location()
    cursor_loc = editor.current_view().cursor()
    if not (start_loc <= cursor_loc <= end_loc):
        exit_alias_expand(editor)


def expand_alias(editor, alias):
    """
    Expand given alias in the given editor buffer at the point where the cursor
    is.
    """
    text_chunks = subst_pattern.split(alias.expansion)
    substs = [s[2:-1] if s != "%_" else s
              for s in subst_pattern.findall(alias.expansion)]
    alias_labels = defaultdict(list)

    editor.aliases_overlay = editor.create_overlay("aliases_overlay")
    editor.aliases_overlay.set_property(
        "background", get_current_field_bg_color()
    )

    color, color1 = get_paragraph_color()
    editor.aliases_background_overlay_1 = editor.create_overlay(
        "aliases_background_overlay_1"
    )
    editor.aliases_background_overlay_1.set_property(
        "paragraph-background", color1
    )
    editor.aliases_background_overlay = editor.create_overlay(
        "aliases_background_overlay"
    )
    editor.aliases_background_overlay.set_property(
        "paragraph-background", color
    )

    editor.aliases_overlay_next = editor.create_overlay(
        "aliases_overlay_next"
    )
    c1, c2 = get_comments_colors()
    editor.aliases_overlay_next.set_property("foreground", c1)
    if c2:
        editor.aliases_overlay_next.set_property("background", "#124")

    # Create a mark with right gravity so it will stay at the end of what we
    # have inserted, giving us the current insert point
    editor.alias_begin_mark = editor.current_view().cursor().create_mark()
    editor.alias_end_mark = editor.current_view().cursor().create_mark(
        left_gravity=False
    )
    insert_mark = editor.alias_end_mark

    for text, subst in six.zip_longest(text_chunks, substs):
        editor.insert(insert_mark.location(), text)
        if subst:
            alias_labels[subst].append(insert_mark.location().create_mark())

    editor.alias_marks = []
    substs_set = set()
    for subst in substs:
        if subst not in substs_set and subst != "%_":
            editor.alias_marks.append(
                [(m, m.location().create_mark(left_gravity=False))
                 for m in alias_labels[subst]]
            )
            for m in alias_labels[subst]:
                editor.insert(m.location(), "<{0}>".format(subst))
            substs_set.add(subst)

    for marks_list in editor.alias_marks:
        for mark_start, mark_end in marks_list:
            apply_overlay(
                editor, mark_start, mark_end, editor.aliases_overlay_next
            )

    if "%_" in alias_labels:
        editor.last_alias_mark = alias_labels["%_"][0]
    else:
        editor.last_alias_mark = None

    editor.current_alias_mark_index = 0
    Hook("character_added").add(on_edit)
    Hook("location_changed").add(on_move)

    editor.indent(editor.alias_begin_mark.location(),
                  editor.alias_end_mark.location())
    toggle_next_field(editor)


EditorBuffer.expand_alias = expand_alias