aboutsummaryrefslogtreecommitdiff
path: root/editors/code/src/highlighting.ts
blob: b34e49c173aa2fd62822a7d898098a68265c8ec3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
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
import * as vscode from 'vscode';
import * as lc from 'vscode-languageclient';

import { ColorTheme, TextMateRuleSettings } from './color_theme';

import { Ctx, sendRequestWithRetry } from './ctx';

export function activateHighlighting(ctx: Ctx) {
    const highlighter = new Highlighter(ctx);
    const client = ctx.client;
    if (client != null) {
        client.onNotification(
            'rust-analyzer/publishDecorations',
            (params: PublishDecorationsParams) => {
                if (!ctx.config.highlightingOn) return;

                const targetEditor = vscode.window.visibleTextEditors.find(
                    editor => {
                        const unescapedUri = unescape(
                            editor.document.uri.toString(),
                        );
                        // Unescaped URI looks like:
                        // file:///c:/Workspace/ra-test/src/main.rs
                        return unescapedUri === params.uri;
                    },
                );
                if (!targetEditor) return;

                highlighter.setHighlights(targetEditor, params.decorations);
            },
        );
    }

    vscode.workspace.onDidChangeConfiguration(
        _ => highlighter.removeHighlights(),
        null,
        ctx.subscriptions,
    );

    vscode.window.onDidChangeActiveTextEditor(
        async (editor: vscode.TextEditor | undefined) => {
            if (!editor || editor.document.languageId !== 'rust') return;
            if (!ctx.config.highlightingOn) return;
            const client = ctx.client;
            if (!client) return;

            const params: lc.TextDocumentIdentifier = {
                uri: editor.document.uri.toString(),
            };
            const decorations = await sendRequestWithRetry<Decoration[]>(
                client,
                'rust-analyzer/decorationsRequest',
                params,
            );
            highlighter.setHighlights(editor, decorations);
        },
        null,
        ctx.subscriptions,
    );
}

interface PublishDecorationsParams {
    uri: string;
    decorations: Decoration[];
}

interface Decoration {
    range: lc.Range;
    tag: string;
    bindingHash?: string;
}

// Based on this HSL-based color generator: https://gist.github.com/bendc/76c48ce53299e6078a76
function fancify(seed: string, shade: 'light' | 'dark') {
    const random = randomU32Numbers(hashString(seed));
    const randomInt = (min: number, max: number) => {
        return Math.abs(random()) % (max - min + 1) + min;
    };

    const h = randomInt(0, 360);
    const s = randomInt(42, 98);
    const l = shade === 'light' ? randomInt(15, 40) : randomInt(40, 90);
    return `hsl(${h},${s}%,${l}%)`;
}

class Highlighter {
    private ctx: Ctx;
    private decorations: Map<
        string,
        vscode.TextEditorDecorationType
    > | null = null;

    constructor(ctx: Ctx) {
        this.ctx = ctx;
    }

    public removeHighlights() {
        if (this.decorations == null) {
            return;
        }

        // Decorations are removed when the object is disposed
        for (const decoration of this.decorations.values()) {
            decoration.dispose();
        }

        this.decorations = null;
    }

    public setHighlights(editor: vscode.TextEditor, highlights: Decoration[]) {
        const client = this.ctx.client;
        if (!client) return;
        // Initialize decorations if necessary
        //
        // Note: decoration objects need to be kept around so we can dispose them
        // if the user disables syntax highlighting
        if (this.decorations == null) {
            this.decorations = initDecorations();
        }

        const byTag: Map<string, vscode.Range[]> = new Map();
        const colorfulIdents: Map<
            string,
            [vscode.Range[], boolean]
        > = new Map();
        const rainbowTime = this.ctx.config.rainbowHighlightingOn;

        for (const tag of this.decorations.keys()) {
            byTag.set(tag, []);
        }

        for (const d of highlights) {
            if (!byTag.get(d.tag)) {
                continue;
            }

            if (rainbowTime && d.bindingHash) {
                if (!colorfulIdents.has(d.bindingHash)) {
                    const mut = d.tag.endsWith('.mut');
                    colorfulIdents.set(d.bindingHash, [[], mut]);
                }
                colorfulIdents
                    .get(d.bindingHash)![0]
                    .push(
                        client.protocol2CodeConverter.asRange(d.range),
                    );
            } else {
                byTag
                    .get(d.tag)!
                    .push(
                        client.protocol2CodeConverter.asRange(d.range),
                    );
            }
        }

        for (const tag of byTag.keys()) {
            const dec = this.decorations.get(
                tag,
            ) as vscode.TextEditorDecorationType;
            const ranges = byTag.get(tag)!;
            editor.setDecorations(dec, ranges);
        }

        for (const [hash, [ranges, mut]] of colorfulIdents.entries()) {
            const textDecoration = mut ? 'underline' : undefined;
            const dec = vscode.window.createTextEditorDecorationType({
                light: { color: fancify(hash, 'light'), textDecoration },
                dark: { color: fancify(hash, 'dark'), textDecoration },
            });
            editor.setDecorations(dec, ranges);
        }
    }
}

function initDecorations(): Map<string, vscode.TextEditorDecorationType> {
    const theme = ColorTheme.load();
    const res = new Map();
    TAG_TO_SCOPES.forEach((scopes, tag) => {
        if (!scopes) throw `unmapped tag: ${tag}`;
        const rule = theme.lookup(scopes);
        const decor = createDecorationFromTextmate(rule);
        res.set(tag, decor);
    });
    return res;
}

function createDecorationFromTextmate(
    themeStyle: TextMateRuleSettings,
): vscode.TextEditorDecorationType {
    const decorationOptions: vscode.DecorationRenderOptions = {};
    decorationOptions.rangeBehavior = vscode.DecorationRangeBehavior.OpenOpen;

    if (themeStyle.foreground) {
        decorationOptions.color = themeStyle.foreground;
    }

    if (themeStyle.background) {
        decorationOptions.backgroundColor = themeStyle.background;
    }

    if (themeStyle.fontStyle) {
        const parts: string[] = themeStyle.fontStyle.split(' ');
        parts.forEach(part => {
            switch (part) {
                case 'italic':
                    decorationOptions.fontStyle = 'italic';
                    break;
                case 'bold':
                    decorationOptions.fontWeight = 'bold';
                    break;
                case 'underline':
                    decorationOptions.textDecoration = 'underline';
                    break;
                default:
                    break;
            }
        });
    }
    return vscode.window.createTextEditorDecorationType(decorationOptions);
}

// sync with tags from `syntax_highlighting.rs`.
const TAG_TO_SCOPES = new Map<string, string[]>([
    ["field", ["entity.name.field"]],
    ["function", ["entity.name.function"]],
    ["module", ["entity.name.module"]],
    ["constant", ["entity.name.constant"]],
    ["macro", ["entity.name.macro"]],

    ["variable", ["variable"]],
    ["variable.mut", ["variable", "meta.mutable"]],

    ["type", ["entity.name.type"]],
    ["type.builtin", ["entity.name.type", "support.type.primitive"]],
    ["type.self", ["entity.name.type.parameter.self"]],
    ["type.param", ["entity.name.type.parameter", "entity.name.type.param.rust"]],
    ["type.lifetime", ["entity.name.type.lifetime", "entity.name.lifetime.rust"]],

    ["literal.byte", ["constant.character.byte"]],
    ["literal.char", ["constant.character.rust"]],
    ["literal.numeric", ["constant.numeric"]],

    ["comment", ["comment"]],
    ["string", ["string.quoted"]],
    ["attribute", ["meta.attribute.rust"]],

    ["keyword", ["keyword"]],
    ["keyword.unsafe", ["keyword.other.unsafe"]],
    ["keyword.control", ["keyword.control"]],
]);

function randomU32Numbers(seed: number) {
    let random = seed | 0;
    return () => {
        random ^= random << 13;
        random ^= random >> 17;
        random ^= random << 5;
        random |= 0;
        return random;
    };
}

function hashString(str: string): number {
    let res = 0;
    for (let i = 0; i < str.length; ++i) {
        const c = str.codePointAt(i)!;
        res = (res * 31 + c) & ~0;
    }
    return res;
}