summaryrefslogtreecommitdiff
path: root/common/content/mappings.js
blob: 32bf284df4b7a50c12987fdbbdcc4adb9c45384e (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
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
/***** 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.

Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>

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 *****/

/** @scope modules */

/**
 * A class representing key mappings. Instances are created by the
 * {@link Mappings} class.
 *
 * @param {number[]} modes The modes in which this mapping is active.
 * @param {string[]} keys The key sequences which are bound to
 *     <b>action</b>.
 * @param {string} description A short one line description of the key mapping.
 * @param {function} action The action invoked by each key sequence.
 * @param {Object} extraInfo An optional extra configuration hash. The
 *     following properties are supported.
 *         arg     - see {@link Map#arg}
 *         count   - see {@link Map#count}
 *         motion  - see {@link Map#motion}
 *         route   - see {@link Map#route}
 *         noremap - see {@link Map#noremap}
 *         rhs     - see {@link Map#rhs}
 *         silent  - see {@link Map#silent}
 * @optional
 * @private
 */
function Map(modes, keys, description, action, extraInfo) //{{{
{
    modes = Array.concat(modes);

    if (!extraInfo)
        extraInfo = {};

    /** @property {number[]} All of the modes for which this mapping applies. */
    this.modes = modes;
    /** @property {string[]} All of this mapping's names (key sequences). */
    this.names = keys.map(events.canonicalKeys);
    /** @property {function (number)} The function called to execute this mapping. */
    this.action = action;
    /** @property {string} This mapping's description, as shown in :viusage. */
    this.description = description || "";

    /** @property {boolean} Whether this mapping accepts an argument. */
    this.arg = extraInfo.arg || false;
    /** @property {boolean} Whether this mapping accepts a count. */
    this.count = extraInfo.count || false;
    /**
     * @property {boolean} Whether the mapping accepts a motion mapping
     *     as an argument.
     */
    this.motion = extraInfo.motion || false;
    /**
     * @property {boolean} Whether the mapping's key events should be
     *     propagated to the host application.
     */
    // TODO: I'm not sure this is the best name but it reflects that which it replaced. --djk
    this.route = extraInfo.route || false;
    /** @property {boolean} Whether the RHS of the mapping should expand mappings recursively. */
    this.noremap = extraInfo.noremap || false;
    /** @property {boolean} Whether any output from the mapping should be echoed on the command line. */
    this.silent = extraInfo.silent || false;
    /** @property {string} The literal RHS expansion of this mapping. */
    this.rhs = extraInfo.rhs || null;
    /**
     * @property {boolean} Specifies whether this is a user mapping. User
     *     mappings may be created by plugins, or directly by users. Users and
     *     plugin authors should create only user mappings.
     */
    this.user = extraInfo.user || false;
}

Map.prototype = {

    /**
     * Returns whether this mapping can be invoked by a key sequence matching
     * <b>name</b>.
     *
     * @param {string} name The name to query.
     * @returns {boolean}
     */
    hasName: function (name) this.names.indexOf(name) >= 0,

    /**
     * Execute the action for this mapping.
     *
     * @param {string} motion The motion argument if accepted by this mapping.
     *     E.g. "w" for "dw"
     * @param {number} count The associated count. E.g. "5" for "5j"
     * @default -1
     * @param {string} argument The normal argument if accepted by this
     *     mapping. E.g. "a" for "ma"
     */
    execute: function (motion, count, argument)
    {
        let args = [];

        if (this.motion)
            args.push(motion);
        if (this.count)
            args.push(count);
        if (this.arg)
            args.push(argument);

        let self = this;
        // FIXME: Kludge.
        if (this.names[0] != ".")
            mappings.repeat = function () self.action.apply(self, args);

        return this.action.apply(this, args);
    }

}; //}}}

/**
 * @instance mappings
 */
function Mappings() //{{{
{
    ////////////////////////////////////////////////////////////////////////////////
    ////////////////////// PRIVATE SECTION /////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    var main = []; // default mappings
    var user = []; // user created mappings

    for (let mode in modes)
    {
        main[mode] = [];
        user[mode] = [];
    }

    function addMap(map)
    {
        let where = map.user ? user : main;
        map.modes.forEach(function (mode) {
            if (!(mode in where))
                where[mode] = [];
            where[mode].push(map);
        });
    }

    function getMap(mode, cmd, stack)
    {
        let maps = stack[mode] || [];

        for (let [, map] in Iterator(maps))
        {
            if (map.hasName(cmd))
                return map;
        }

        return null;
    }

    function removeMap(mode, cmd)
    {
        let maps = user[mode] || [];
        let names;

        for (let [i, map] in Iterator(maps))
        {
            for (let [j, name] in Iterator(map.names))
            {
                if (name == cmd)
                {
                    map.names.splice(j, 1);
                    if (map.names.length == 0)
                        maps.splice(i, 1);
                    return;
                }
            }
        }
    }

    function expandLeader(keyString) keyString.replace(/<Leader>/i, mappings.getMapLeader())

    // Return all mappings present in all @modes
    function mappingsIterator(modes, stack)
    {
        modes = modes.slice();
        return (map for ([i, map] in Iterator(stack[modes.shift()]))
            if (modes.every(function (mode) stack[mode].some(
                        function (m) m.rhs == map.rhs && m.names[0] == map.names[0]))))
    }

    function addMapCommands(ch, modes, modeDescription)
    {
        // 0 args -> list all maps
        // 1 arg  -> list the maps starting with args
        // 2 args -> map arg1 to arg*
        function map(args, modes, noremap)
        {
            if (!args.length)
            {
                mappings.list(modes);
                return;
            }

            let [lhs, rhs] = args;

            if (!rhs) // list the mapping
                mappings.list(modes, expandLeader(lhs));
            else
            {
                // this matches Vim's behaviour
                if (/^<Nop>$/i.test(rhs))
                    noremap = true;

                mappings.addUserMap(modes, [lhs],
                    "User defined mapping",
                    function (count) { events.feedkeys((count > -1 ? count : "") + this.rhs, this.noremap, this.silent); },
                    {
                        count: true,
                        rhs: events.canonicalKeys(rhs),
                        noremap: !!noremap,
                        silent: "<silent>" in args
                    });
            }
        }

        modeDescription = modeDescription ? " in " + modeDescription + " mode" : "";

        // :map, :noremap => NORMAL + VISUAL modes
        function isMultiMode(map, cmd)
        {
            return map.modes.indexOf(modules.modes.NORMAL) >= 0
                && map.modes.indexOf(modules.modes.VISUAL) >= 0
                && /^[nv](nore)?map$/.test(cmd);
        }

        const opts = {
                completer: function (context, args) completion.userMapping(context, args, modes),
                options: [
                    [["<silent>", "<Silent>"],  commands.OPTION_NOARG]
                ],
                literal: 1,
                serial: function ()
                {
                    let noremap = this.name.indexOf("noremap") > -1;
                    return [
                        {
                            command: this.name,
                            options: map.silent ? { "<silent>": null } : {},
                            arguments: [map.names[0]],
                            literalArg: map.rhs
                        }
                        for (map in mappingsIterator(modes, user))
                        if (map.rhs && map.noremap == noremap && !isMultiMode(map, this.name))
                    ];
                }
        };

        commands.add([ch ? ch + "m[ap]" : "map"],
            "Map a key sequence" + modeDescription,
            function (args) { map(args, modes, false); },
            opts);

        commands.add([ch + "no[remap]"],
            "Map a key sequence without remapping keys" + modeDescription,
            function (args) { map(args, modes, true); },
            opts);

        commands.add([ch + "mapc[lear]"],
            "Remove all mappings" + modeDescription,
            function () { modes.forEach(function (mode) { mappings.removeAll(mode); }); },
            { argCount: "0" });

        commands.add([ch + "unm[ap]"],
            "Remove a mapping" + modeDescription,
            function (args)
            {
                args = args[0];

                let found = false;
                for (let [, mode] in Iterator(modes))
                {
                    if (mappings.hasMap(mode, args))
                    {
                        mappings.remove(mode, args);
                        found = true;
                    }
                }
                if (!found)
                    liberator.echoerr("E31: No such mapping");
            },
            {
                argCount: "1",
                completer: function (context, args) completion.userMapping(context, args, modes)
            });
    }

    /////////////////////////////////////////////////////////////////////////////}}}
    ////////////////////// COMMANDS ////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    addMapCommands("",  [modes.NORMAL, modes.VISUAL], "");

    for (let mode in modes.mainModes)
        if (mode.char && !commands.get(mode.char + "map"))
            addMapCommands(mode.char,
                           [m.mask for (m in modes.mainModes) if (m.char == mode.char)],
                           [mode.disp.toLowerCase()]);

    /////////////////////////////////////////////////////////////////////////////}}}
    ////////////////////// COMPLETIONS /////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    liberator.registerObserver("load_completion", function () {
        completion.setFunctionCompleter(mappings.get,
        [
            null,
            function (context, obj, args)
            {
                let mode = args[0];
                return util.Array.flatten(
                [
                    [[name, map.description] for ([i, name] in Iterator(map.names))]
                    for ([i, map] in Iterator(user[mode].concat(main[mode])))
                ]);
            }
        ]);

        completion.userMapping = function userMapping(context, args, modes) {
            // FIXME: have we decided on a 'standard' way to handle this clash? --djk
            modes = modes || [modules.modes.NORMAL];

            if (args.completeArg == 0)
            {
                let maps = [[m.names[0], ""] for (m in mappings.getUserIterator(modes))];
                context.completions = maps;
            }
        };
    });

    /////////////////////////////////////////////////////////////////////////////}}}
    ////////////////////// PUBLIC SECTION //////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    return {

        // NOTE: just normal mode for now
        /** @property {Iterator(Map)} @private */
        __iterator__: function () mappingsIterator([modes.NORMAL], main),

        // used by :mkvimperatorrc to save mappings
        /**
         * Returns a user-defined mappings iterator for the specified
         * <b>mode</b>.
         *
         * @param {number} mode The mode to return mappings from.
         * @returns {Iterator(Map)}
         */
        getUserIterator: function (mode) mappingsIterator(mode, user),

        /**
         * Adds a new default key mapping.
         *
         * @param {number[]} modes The modes that this mapping applies to.
         * @param {string[]} keys The key sequences which are bound to
         *     <b>action</b>.
         * @param {string} description A description of the key mapping.
         * @param {function} action The action invoked by each key sequence.
         * @param {Object} extra An optional extra configuration hash.
         * @optional
         */
        add: function (modes, keys, description, action, extra)
        {
            addMap(new Map(modes, keys, description, action, extra));
        },

        /**
         * Adds a new user-defined key mapping.
         *
         * @param {number[]} modes The modes that this mapping applies to.
         * @param {string[]} keys The key sequences which are bound to
         *     <b>action</b>.
         * @param {string} description A description of the key mapping.
         * @param {function} action The action invoked by each key sequence.
         * @param {Object} extra An optional extra configuration hash (see
         *     {@link Map#extraInfo}).
         * @optional
         */
        addUserMap: function (modes, keys, description, action, extra)
        {
            keys = keys.map(expandLeader);
            extra = extra || {};
            extra.user = true;
            let map = new Map(modes, keys, description || "User defined mapping", action, extra);

            // remove all old mappings to this key sequence
            for (let [, name] in Iterator(map.names))
            {
                for (let [, mode] in Iterator(map.modes))
                    removeMap(mode, name);
            }

            addMap(map);
        },

        /**
         * Returns the map from <b>mode</b> named <b>cmd</b>.
         *
         * @param {number} mode The mode to search.
         * @param {string} cmd The map name to match.
         * @returns {Map}
         */
        get: function (mode, cmd)
        {
            mode = mode || modes.NORMAL;
            return getMap(mode, cmd, user) || getMap(mode, cmd, main);
        },

        /**
         * Returns the default map from <b>mode</b> named <b>cmd</b>.
         *
         * @param {number} mode The mode to search.
         * @param {string} cmd The map name to match.
         * @returns {Map}
         */
        getDefault: function (mode, cmd)
        {
            mode = mode || modes.NORMAL;
            return getMap(mode, cmd, main);
        },

        /**
         * Returns an array of maps with names starting with but not equal to
         * <b>prefix</b>.
         *
         * @param {number} mode The mode to search.
         * @param {string} prefix The map prefix string to match.
         * @returns {Map[]}
         */
        getCandidates: function (mode, prefix)
        {
            let mappings = user[mode].concat(main[mode]);
            let matches = [];

            for (let [, map] in Iterator(mappings))
            {
                for (let [, name] in Iterator(map.names))
                {
                    if (name.indexOf(prefix) == 0 && name.length > prefix.length)
                    {
                        // for < only return a candidate if it doesn't look like a <c-x> mapping
                        if (prefix != "<" || !/^<.+>/.test(name))
                            matches.push(map);
                    }
                }
            }

            return matches;
        },

        /*
         * Returns the map leader string used to replace the special token
         * "<Leader>" when user mappings are defined.
         *
         * @returns {string}
         */
        // FIXME: property
        getMapLeader: function ()
        {
            let leaderRef = liberator.variableReference("mapleader");
            return leaderRef[0] ? leaderRef[0][leaderRef[1]] : "\\";
        },

        /**
         * Returns whether there is a user-defined mapping <b>cmd</b> for the
         * specified <b>mode</b>.
         *
         * @param {number} mode The mode to search.
         * @param {string} cmd The candidate key mapping.
         * @returns {boolean}
         */
        hasMap: function (mode, cmd) user[mode].some(function (map) map.hasName(cmd)),

        /**
         * Remove the user-defined mapping named <b>cmd</b> for <b>mode</b>.
         *
         * @param {number} mode The mode to search.
         * @param {string} cmd The map name to match.
         */
        remove: function (mode, cmd)
        {
            removeMap(mode, cmd);
        },

        /**
         * Remove all user-defined mappings for <b>mode</b>.
         *
         * @param {number} mode The mode to remove all mappings from.
         */
        removeAll: function (mode)
        {
            user[mode] = [];
        },

        /**
         * Lists all user-defined mappings matching <b>filter</b> for the
         * specified <b>modes</b>.
         *
         * @param {number[]} modes An array of modes to search.
         * @param {string} filter The filter string to match.
         */
        list: function (modes, filter)
        {
            let modeSign = "";

            // TODO: Vim hides "nv" in a :map and "v" and "n" in :vmap and
            //       :nmap respectively if the map is not exclusive.
            modes.forEach(function (mode) {
                for (let m in modules.modes.mainModes)
                    if (mode == m.mask && modeSign.indexOf(m.char) == -1)
                        modeSign += m.char;
            });

            let maps = mappingsIterator(modes, user);
            if (filter)
                maps = [map for (map in maps) if (map.names[0] == filter)];

            let list = <table>
                    {
                        template.map(maps, function (map)
                            template.map(map.names, function (name)
                            <tr>
                                <td>{modeSign} {name}</td>
                                <td>{map.noremap ? "*" : " "}</td>
                                <td>{map.rhs || "function () { ... }"}</td>
                            </tr>))
                    }
                    </table>;

            // TODO: Move this to an ItemList to show this automatically
            if (list.*.length() == list.text().length())
            {
                liberator.echomsg("No mapping found");
                return;
            }
            commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
        }
    };
    //}}}
} //}}}

// vim: set fdm=marker sw=4 ts=4 et: