File: events.js

package info (click to toggle)
vimperator 1.1-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 992 kB
  • ctags: 376
  • sloc: makefile: 35
file content (1499 lines) | stat: -rw-r--r-- 61,140 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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
/***** 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.

(c) 2006-2008: Martin Stubenschrott <stubenschrott@gmx.net>

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

liberator.AutoCommands = function () //{{{
{
    ////////////////////////////////////////////////////////////////////////////////
    ////////////////////// PRIVATE SECTION /////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    var autoCommands = {};

    function autoCommandsIterator()
    {
        for (var item in autoCommands)
            for (var i = 0; i < autoCommands[item].length; i++)
                yield item + " " + autoCommands[item][i][0] + " " + autoCommands[item][i][1];
        throw StopIteration;
    }

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

    liberator.commands.add(["au[tocmd]"],
        "Execute commands automatically on events",
        function (args, special)
        {
            if (!args)
            {
                if (special) // :au!
                    liberator.autocommands.remove(null, null);
                else // :au
                    liberator.autocommands.list(null, null);
            }
            else
            {
                // (?:  ) means don't store; (....)? <-> exclamation marks makes the group optional
                var [all, asterix, auEvent, regex, cmds] = args.match(/^(\*)?(?:\s+)?(\S+)(?:\s+)?(\S+)?(?:\s+)?(.+)?$/);

                if (cmds)
                {
                    liberator.autocommands.add(auEvent, regex, cmds);
                }
                else if (regex) // e.g. no cmds provided
                {
                    if (special)
                        liberator.autocommands.remove(auEvent, regex);
                    else
                        liberator.autocommands.list(auEvent, regex);
                }
                else if (auEvent)
                {
                    if (asterix)
                        if (special)
                            liberator.autocommands.remove(null, auEvent); // ':au! * auEvent'
                        else
                            liberator.autocommands.list(null, auEvent);
                    else
                        if (special)
                            liberator.autocommands.remove(auEvent, null);
                        else
                            liberator.autocommands.list(auEvent, null);
                }
            }
        },
        {
            completer: function (filter) { return liberator.completion.autocommands(filter); }
        });

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

    //TODO: maybe this.function rather than v.autocommands.function...

    return {

        __iterator__: function ()
        {
            return autoCommandsIterator();
        },

        add: function (auEvent, regex, cmds)
        {
            var eventsIter = auEvent.split(",");
            for (var i = 0; i < eventsIter.length; i++)
            {
                if (!autoCommands[eventsIter[i]])
                    autoCommands[eventsIter[i]] = [];

                var flag = true;
                for (var y = 0; y < autoCommands[eventsIter[i]].length; y++)
                {
                    if (autoCommands[eventsIter[i]][y][0] == regex && autoCommands[eventsIter[i]][y][1] == cmds)
                        flag = false;
                }
                if (flag)
                    autoCommands[eventsIter[i]].push([regex, cmds]);
            }
        },

        remove: function (auEvent, regex) // arguments are filters (NULL = all)
        {
            if (!auEvent && !regex)
            {
                autoCommands = {}; // delete all
            }
            else if (!regex) // remove all on this auEvent
            {
                for (var item in autoCommands)
                {
                    if (item == auEvent)
                        delete autoCommands[item];
                }
            }
            else if (!auEvent) // delete all matches to this regex
            {
                for (var item in autoCommands)
                {
                    var i = 0;
                    while (i < autoCommands[item].length)
                    {
                        if (regex == autoCommands[item][i][0])
                        {
                            autoCommands[item].splice(i, 1); // remove array
                            // keep `i' since this is removed, so a possible next one is at this place now
                        }
                        else
                            i++;
                    }
                }
            }
            else // delete matching `auEvent && regex' items
            {
                for (var item in autoCommands)
                {
                    if (item == auEvent)
                    {
                        for (var i = 0; i < autoCommands[item].length; i++)
                        {
                            if (regex == autoCommands[item][i][0])
                                autoCommands[item].splice(i, 1); // remove array
                        }
                    }
                }
            }
        },

        list: function (auEvent, regex) // arguments are filters (NULL = all)
        {
            var flag;
            var list = "<table><tr><td style='font-weight: bold;'  colspan='2'>---- Auto-Commands ----</td></tr>";
            for (var item in autoCommands)
            {
                flag = true;
                if (!auEvent || item == auEvent) // filter event
                {
                    for (var i = 0; i < autoCommands[item].length; i++)
                    {
                        if (!regex || regex == autoCommands[item][i][0]) // filter regex
                        {
                            if (flag == true)
                            {
                                list += "<tr><td style='font-weight: bold;'  colspan='2'>" +
                                        liberator.util.escapeHTML(item) + "</td></tr>";
                                flag = false;
                            }

                            list += "<tr>";
                            list += "<td> &nbsp; " + liberator.util.escapeHTML(autoCommands[item][i][0]) + "</td>";
                            list += "<td>" + liberator.util.escapeHTML(autoCommands[item][i][1]) + "</td>";
                            list += "</tr>";
                        }
                    }
                }
            }

            list += "</table>";
            liberator.commandline.echo(list, liberator.commandline.HL_NORMAL, liberator.commandline.FORCE_MULTILINE);
        },

        trigger: function (auEvent, url)
        {
            if (autoCommands[auEvent])
            {
                for (var i = 0; i < autoCommands[auEvent].length; i++)
                {
                    var regex = new RegExp(autoCommands[auEvent][i][0]);
                    if (regex.test(url))
                        liberator.execute(autoCommands[auEvent][i][1]);
                }
            }
        }
    };
    //}}}
} //}}}

liberator.Events = function () //{{{
{
    ////////////////////////////////////////////////////////////////////////////////
    ////////////////////// PRIVATE SECTION /////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    var inputBufferLength = 0; // count the number of keys in v.input.buffer (can be different from v.input.buffer.length)
    var skipMap = false; // while feeding the keys (stored in v.input.buffer | no map found) - ignore mappings

    var macros = {};
    var currentMacro = "";
    var lastMacro = "";

    try // not every extension has a getBrowser() method
    {
        var tabcontainer = getBrowser().mTabContainer;
        if (tabcontainer) // not every VIM-like extension has a tab container
        {
            tabcontainer.addEventListener("TabMove", function (event)
            {
                liberator.statusline.updateTabCount();
                liberator.buffer.updateBufferList();
            }, false);
            tabcontainer.addEventListener("TabOpen", function (event)
            {
                liberator.statusline.updateTabCount();
                liberator.buffer.updateBufferList();
            }, false);
            tabcontainer.addEventListener("TabClose", function (event)
            {
                liberator.statusline.updateTabCount();
                liberator.buffer.updateBufferList();
            }, false);
            tabcontainer.addEventListener("TabSelect", function (event)
            {
                // TODO: is all of that necessary?
                liberator.modes.reset();
                liberator.commandline.clear();
                liberator.modes.show();
                liberator.statusline.updateTabCount();
                liberator.buffer.updateBufferList();
                liberator.tabs.updateSelectionHistory();

                setTimeout(function () { liberator.focusContent(true); }, 10); // just make sure, that no widget has focus
            }, false);
        }

        // this adds an event which is is called on each page load, even if the
        // page is loaded in a background tab
        getBrowser().addEventListener("load", onPageLoad, true);

        // called when the active document is scrolled
        getBrowser().addEventListener("scroll", function (event)
        {
            liberator.statusline.updateBufferPosition();
            liberator.modes.show();
        }, null);
    }
    catch (e) { }

//    getBrowser().addEventListener("submit", function (event)
//    {
//        // reset buffer loading state as early as possible, important for macros
//        dump("submit\n");
//        liberator.buffer.loaded = 0;
//    }, null);

    /////////////////////////////////////////////////////////
    // track if a popup is open or the menubar is active
    var activeMenubar = false;
    function enterPopupMode(event)
    {
        if (event.originalTarget.localName == "tooltip" || event.originalTarget.id == "liberator-visualbell")
            return;

        liberator.modes.add(liberator.modes.MENU);
    }
    function exitPopupMode()
    {
        // gContextMenu is set to NULL by firefox, when a context menu is closed
        if (!gContextMenu && !activeMenubar)
            liberator.modes.remove(liberator.modes.MENU);
    }
    function enterMenuMode()
    {
        activeMenubar = true;
        liberator.modes.add(liberator.modes.MENU);
    }
    function exitMenuMode()
    {
        activeMenubar = false;
        liberator.modes.remove(liberator.modes.MENU);
    }
    window.addEventListener("popupshown", enterPopupMode, true);
    window.addEventListener("popuphidden", exitPopupMode, true);
    window.addEventListener("DOMMenuBarActive", enterMenuMode, true);
    window.addEventListener("DOMMenuBarInactive", exitMenuMode, true);

    // window.document.addEventListener("DOMTitleChanged", function (event)
    // {
    //     liberator.log("titlechanged");
    // }, null);

    // NOTE: the order of ["Esc", "Escape"] or ["Escape", "Esc"]
    //       matters, so use that string as the first item, that you
    //       want to refer to within liberator's source code for
    //       comparisons like if (key == "<Esc>") { ... }
    var keyTable = [
        [ KeyEvent.DOM_VK_ESCAPE, ["Esc", "Escape"] ],
        [ KeyEvent.DOM_VK_LEFT_SHIFT, ["<"] ],
        [ KeyEvent.DOM_VK_RIGHT_SHIFT, [">"] ],
        [ KeyEvent.DOM_VK_RETURN, ["Return", "CR", "Enter"] ],
        [ KeyEvent.DOM_VK_TAB, ["Tab"] ],
        [ KeyEvent.DOM_VK_DELETE, ["Del"] ],
        [ KeyEvent.DOM_VK_BACK_SPACE, ["BS"] ],
        [ KeyEvent.DOM_VK_HOME, ["Home"] ],
        [ KeyEvent.DOM_VK_INSERT, ["Insert", "Ins"] ],
        [ KeyEvent.DOM_VK_END, ["End"] ],
        [ KeyEvent.DOM_VK_LEFT, ["Left"] ],
        [ KeyEvent.DOM_VK_RIGHT, ["Right"] ],
        [ KeyEvent.DOM_VK_UP, ["Up"] ],
        [ KeyEvent.DOM_VK_DOWN, ["Down"] ],
        [ KeyEvent.DOM_VK_PAGE_UP, ["PageUp"] ],
        [ KeyEvent.DOM_VK_PAGE_DOWN, ["PageDown"] ],
        [ KeyEvent.DOM_VK_F1, ["F1"] ],
        [ KeyEvent.DOM_VK_F2, ["F2"] ],
        [ KeyEvent.DOM_VK_F3, ["F3"] ],
        [ KeyEvent.DOM_VK_F4, ["F4"] ],
        [ KeyEvent.DOM_VK_F5, ["F5"] ],
        [ KeyEvent.DOM_VK_F6, ["F6"] ],
        [ KeyEvent.DOM_VK_F7, ["F7"] ],
        [ KeyEvent.DOM_VK_F8, ["F8"] ],
        [ KeyEvent.DOM_VK_F9, ["F9"] ],
        [ KeyEvent.DOM_VK_F10, ["F10"] ],
        [ KeyEvent.DOM_VK_F11, ["F11"] ],
        [ KeyEvent.DOM_VK_F12, ["F12"] ],
        [ KeyEvent.DOM_VK_F13, ["F13"] ],
        [ KeyEvent.DOM_VK_F14, ["F14"] ],
        [ KeyEvent.DOM_VK_F15, ["F15"] ],
        [ KeyEvent.DOM_VK_F16, ["F16"] ],
        [ KeyEvent.DOM_VK_F17, ["F17"] ],
        [ KeyEvent.DOM_VK_F18, ["F18"] ],
        [ KeyEvent.DOM_VK_F19, ["F19"] ],
        [ KeyEvent.DOM_VK_F20, ["F20"] ],
        [ KeyEvent.DOM_VK_F21, ["F21"] ],
        [ KeyEvent.DOM_VK_F22, ["F22"] ],
        [ KeyEvent.DOM_VK_F23, ["F23"] ],
        [ KeyEvent.DOM_VK_F24, ["F24"] ]
    ];

    function getKeyCode(str)
    {
        str = str.toLowerCase();
        for (var i in keyTable)
        {
            for (var k in keyTable[i][1])
            {
                // we don't store lowercase keys in the keyTable, because we
                // also need to get good looking strings for the reverse action
                if (keyTable[i][1][k].toLowerCase() == str)
                    return keyTable[i][0];
            }
        }
        return 0;
    }

    function isFormElemFocused()
    {
        var elt = window.document.commandDispatcher.focusedElement;
        if (elt == null)
            return false;

        try
        { // sometimes the elt doesn't have .localName
            var tagname = elt.localName.toLowerCase();
            var type = elt.type.toLowerCase();

            if ((tagname == "input" && (type != "image")) ||
                    tagname == "textarea" ||
                    //            tagName == "SELECT" ||
                    //            tagName == "BUTTON" ||
                    tagname == "isindex") // isindex is a deprecated one-line input box
                return true;
        }
        catch (e)
        {
            // FIXME: do nothing?
        }

        return false;
    }

    function onPageLoad(event)
    {
        if (event.originalTarget instanceof HTMLDocument)
        {
            var doc = event.originalTarget;
            // document is part of a frameset
            if (doc.defaultView.frameElement)
            {
                // hacky way to get rid of "Transfering data from ..." on sites with frames
                // when you click on a link inside a frameset, because asyncUpdateUI
                // is not triggered there (firefox bug?)
                setTimeout(liberator.statusline.updateUrl, 10);
                return;
            }

            // code which should happen for all (also background) newly loaded tabs goes here:

            var url = liberator.buffer.URL;
            var title = liberator.buffer.title;

            //update history
            if (url && liberator.history)
                liberator.history.add(url, title);

            liberator.buffer.updateBufferList();
            liberator.autocommands.trigger("PageLoad", url);

            // mark the buffer as loaded, we can't use liberator.buffer.loaded
            // since that always refers to the current buffer, while doc can be
            // any buffer, even in a background tab
            doc.pageIsFullyLoaded = 1;

            // code which is only relevant if the page load is the current tab goes here:
            if (doc == getBrowser().contentDocument)
            {
                // we want to stay in command mode after a page has loaded
                // XXX: Does this still causes window map events which is _very_ annoying
                setTimeout(function () {
                    var focused = document.commandDispatcher.focusedElement;
                    if (focused && (typeof focused.value != "undefined") && focused.value.length == 0)
                        focused.blur();
                }, 100);
            }
        }
    }

    // return true when load successful, or false otherwise
    function waitForPageLoaded()
    {
        dump("start waiting in loaded state: " + liberator.buffer.loaded + "\n");
        var mainThread = Components.classes["@mozilla.org/thread-manager;1"].
                         getService(Components.interfaces.nsIThreadManager).mainThread;
        while (mainThread.hasPendingEvents()) // clear queue
            mainThread.processNextEvent(true);

        if (liberator.buffer.loaded == 1)
            return true;

        var ms = 15000; // maximum time to wait - TODO: add option
        var then = new Date().getTime();
        for (var now = then; now - then < ms; now = new Date().getTime())
        {
            mainThread.processNextEvent(true);
            if ((now - then) % 1000 < 10)
                dump("waited: " + (now - then) + " ms\n");

            if (liberator.buffer.loaded > 0)
            {
                liberator.sleep(250);
                break;
            }
            else
                liberator.echo("Waiting for page to load...");
        }
        liberator.modes.show();

        // TODO: allow macros to be continued when page does not fully load with an option
        var ret = (liberator.buffer.loaded == 1);
        if (!ret)
            liberator.echoerr("Page did not load completely in " + ms + " milliseconds. Macro stopped.");
        dump("done waiting: " + ret + "\n");

        // sometimes the input widget had focus when replaying a macro
        // maybe this call should be moved somewhere else?
        // liberator.focusContent(true);

        return ret;
    }

    // load all macros inside ~/.vimperator/macros/
    // setTimeout needed since liberator.io. is loaded after liberator.events.
    setTimeout (function () {
        try
        {
            var files = liberator.io.readDirectory(liberator.io.getSpecialDirectory("macros"));
            for (var i = 0; i < files.length; i++)
            {
                var file = files[i];
                if (!file.exists() || file.isDirectory() ||
                    !file.isReadable() || !/^[\w_-]+(\.vimp)?$/i.test(file.leafName))
                        continue;

                var name = file.leafName.replace(/\.vimp$/i, "");
                macros[name] = liberator.io.readFile(file).split(/\n/)[0];
                liberator.log("Macro " + name + " added: " + macros[name], 8);
            }
        }
        catch (e)
        {
            liberator.log("macro directory not found or error reading macro file");
        }
    }, 100);

    /////////////////////////////////////////////////////////////////////////////}}}
    ////////////////////// MAPPINGS ////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    liberator.mappings.add(liberator.modes.all,
        ["<Esc>", "<C-[>"], "Focus content",
        function () { liberator.events.onEscape(); });

    // add the ":" mapping in all but insert mode mappings
    liberator.mappings.add([liberator.modes.NORMAL, liberator.modes.VISUAL, liberator.modes.HINTS, liberator.modes.MESSAGE, liberator.modes.COMPOSE, liberator.modes.CARET, liberator.modes.TEXTAREA],
        [":"], "Enter command line mode",
        function () { liberator.commandline.open(":", "", liberator.modes.EX); });

    // focus events
    liberator.mappings.add([liberator.modes.NORMAL, liberator.modes.VISUAL, liberator.modes.CARET],
        ["<Tab>"], "Advance keyboard focus",
        function () { document.commandDispatcher.advanceFocus(); });

    liberator.mappings.add([liberator.modes.NORMAL, liberator.modes.VISUAL, liberator.modes.CARET, liberator.modes.INSERT, liberator.modes.TEXTAREA],
        ["<S-Tab>"], "Rewind keyboard focus",
        function () { document.commandDispatcher.rewindFocus(); });

    liberator.mappings.add(liberator.modes.all,
        ["<C-q>"], "Temporarily ignore all " + liberator.config.name + " key bindings",
        function () { liberator.modes.passAllKeys = true; });

    liberator.mappings.add(liberator.modes.all,
        ["<C-v>"], "Pass through next key",
        function () { liberator.modes.passNextKey = true; });

    liberator.mappings.add(liberator.modes.all,
        ["<Nop>"], "Do nothing",
        function () { return; });

    // macros
    liberator.mappings.add([liberator.modes.NORMAL, liberator.modes.MESSAGE],
        ["q"], "Record a key sequence into a macro",
        function (arg) { liberator.events.startRecording(arg); },
        { flags: liberator.Mappings.flags.ARGUMENT });

    liberator.mappings.add([liberator.modes.NORMAL, liberator.modes.MESSAGE],
        ["@"], "Play a macro",
        function (count, arg)
        {
            if (count < 1) count = 1;
            while (count--)
                liberator.events.playMacro(arg);
        },
        { flags: liberator.Mappings.flags.ARGUMENT | liberator.Mappings.flags.COUNT });

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

    liberator.commands.add(["delmac[ros]"],
        "Delete macros",
        function (arg)
        {
            if (!arg)
                liberator.echoerr("E474: Invalid argument");
            else
                liberator.events.deleteMacros(arg);
        });

    liberator.commands.add(["macros"],
        "List all macros",
        function (arg)
        {
            var str = "<table>";
            var macroRef = liberator.events.getMacros(arg);
            for (var item in macroRef)
               str += "<tr><td> " + item + " &nbsp; </td><td>" +
                      liberator.util.escapeHTML(macroRef[item]) + "</td></tr>";

            str += "</table>";

            liberator.echo(str, liberator.commandline.FORCE_MULTILINE);
        });

    liberator.commands.add(["pl[ay]"],
        "Replay a recorded macro",
        function (arg)
        {
            if (!arg)
                liberator.echoerr("E474: Invalid argument");
            else
                liberator.events.playMacro(arg);
        },
        {
            completer: function (filter) { return liberator.completion.macros(filter); }
        });

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

    var eventManager = {

        wantsModeReset: true, // used in onFocusChange since Firefox is so buggy here

        destroy: function ()
        {
            // removeEventListeners() to avoid mem leaks
            window.dump("TODO: remove all eventlisteners\n");

            getBrowser().removeProgressListener(this.progressListener);

            window.removeEventListener("popupshown", enterPopupMode, true);
            window.removeEventListener("popuphidden", exitPopupMode, true);
            window.removeEventListener("DOMMenuBarActive", enterMenuMode, true);
            window.removeEventListener("DOMMenuBarInactive", exitMenuMode, true);

            window.removeEventListener("keypress", this.onKeyPress, true);
            window.removeEventListener("keydown", this.onKeyDown, true);
        },

        startRecording: function (macro)
        {
            if (!/[a-zA-Z0-9]/.test(macro))
            {
                liberator.echoerr("Register must be [a-zA-z0-9]");
                return false;
            }
            liberator.modes.isRecording = true;

            if (/[A-Z]/.test(macro)) // uppercase (append)
            {
                currentMacro = macro.toLowerCase();
                if (!macros[currentMacro])
                    macros[currentMacro] = ""; // initialize if it does not yet exist
            }
            else
            {
                currentMacro = macro;
                macros[currentMacro] = "";
            }
        },

        playMacro: function (macro)
        {
            if (!/[a-zA-Z0-9@]/.test(macro) && macro.length == 1)
            {
                liberator.echoerr("Register must be [a-z0-9]");
                return false;
            }
            if (macro == "@") // use lastMacro if it's set
            {
                if (!lastMacro)
                {
                    liberator.echoerr("E748: No previously used register");
                    return false;
                }
            }
            else
            {
                if (macro.length == 1)
                    lastMacro = macro.toLowerCase(); // XXX: sets last playerd macro, even if it does not yet exist
                else
                    lastMacro = macro; // e.g. long names are case sensitive
            }

            if (macros[lastMacro])
            {
                liberator.modes.isReplaying = true;

                // make sure the page is stopped before starting to play the macro
                try
                {
                    getWebNavigation().stop(nsIWebNavigation.STOP_ALL);
                } catch (ex) { }

                liberator.buffer.loaded = 1; // even if not a full page load, assume it did load correctly before starting the macro
                liberator.events.feedkeys(macros[lastMacro], true); // true -> noremap
                liberator.modes.isReplaying = false;
            }
            else
                liberator.echoerr("Register " + lastMacro + " not set");
        },

        getMacros: function (filter)
        {
            if (!filter)
                return macros;

            var filtered = {};
            var re = new RegExp(filter);

            for (var item in macros)
            {
                if (re.test(item))
                    filtered[item] = macros[item];
            }
            return filtered; //XXX: returns a real copy, since this is only a 'var ..'?
        },

        deleteMacros: function (filter)
        {
            var re = new RegExp(filter);

            for (var item in macros)
            {
                if (re.test(item))
                    delete macros[item];
            }
        },

        // This method pushes keys into the event queue from liberator
        // it is similar to vim's feedkeys() method, but cannot cope with
        // 2 partially feeded strings, you have to feed one parsable string
        //
        // @param keys: a string like "2<C-f>" to pass
        //              if you want < to be taken literally, prepend it with a \\
        feedkeys: function (keys, noremap)
        {
            var doc = window.document;
            var view = window.document.defaultView;
            var escapeKey = false; // \ to escape some special keys

            noremap = !!noremap;

            for (var i = 0; i < keys.length; i++)
            {
                var charCode = keys.charCodeAt(i);
                var keyCode = 0;
                var shift = false, ctrl = false, alt = false, meta = false;
                //if (charCode == 92) // the '\' key FIXME: support the escape key
                if (charCode == 60 && !escapeKey) // the '<' key starts a complex key
                {
                    var matches = keys.substr(i + 1).match(/([CSMAcsma]-)*([^>]+)/);
                    if (matches && matches[2])
                    {
                        if (matches[1]) // check for modifiers
                        {
                            ctrl  = /[cC]-/.test(matches[1]);
                            alt   = /[aA]-/.test(matches[1]);
                            shift = /[sS]-/.test(matches[1]);
                            meta  = /[mM]-/.test(matches[1]);
                        }
                        if (matches[2].length == 1)
                        {
                            if (!ctrl && !alt && !shift && !meta)
                                return false; // an invalid key like <a>
                            charCode = matches[2].charCodeAt(0);
                        }
                        else if (matches[2].toLowerCase() == "space")
                        {
                            charCode = 32;
                        }
                        else if (keyCode = getKeyCode(matches[2]))
                        {
                            charCode = 0;
                        }
                        else // an invalid key like <A-xxx> was found, stop propagation here (like Vim)
                        {
                            return false;
                        }

                        i += matches[0].length + 1;
                    }
                }
                else // a simple key
                {
                    // FIXME: does not work for non A-Z keys like Ö,Ä,...
                    shift = (keys[i] >= "A" && keys[i] <= "Z");
                }

                var elem = window.document.commandDispatcher.focusedElement;
                if (!elem)
                    elem = window.content;

                var evt = doc.createEvent("KeyEvents");
                evt.initKeyEvent("keypress", true, true, view, ctrl, alt, shift, meta, keyCode, charCode);
                evt.noremap = noremap;
                elem.dispatchEvent(evt);
                // stop feeding keys if page loading failed
                if (liberator.modes.isReplaying)
                {
                    if (!waitForPageLoaded())
                        return;
                    // else // a short break between keys often helps
                    //     liberator.sleep(50);
                }
            }
            return true;
        },

        // this function converts the given event to
        // a keycode which can be used in mappings
        // e.g. pressing ctrl+n would result in the string "<C-n>"
        // null if unknown key
        toString: function (event)
        {
            if (!event)
                return;

            var key = null;
            var modifier = "";

            if (event.ctrlKey)
                modifier += "C-";
            if (event.altKey)
                modifier += "A-";
            if (event.metaKey)
                modifier += "M-";

            if (event.type == "keypress")
            {
                if (event.charCode == 0)
                {
                    if (event.shiftKey)
                        modifier += "S-";

                    for (var i in keyTable)
                    {
                        if (keyTable[i][0] == event.keyCode)
                        {
                            key = keyTable[i][1][0];
                            break;
                        }
                    }
                }
                // special handling of the Space key
                else if (event.charCode == 32)
                {
                    if (event.shiftKey)
                        modifier += "S-";
                    key = "Space";
                }
                // a normal key like a, b, c, 0, etc.
                else if (event.charCode > 0)
                {
                    key = String.fromCharCode(event.charCode);
                    if (modifier.length == 0)
                        return key;
                }
            }
            else if (event.type == "click" || event.type == "dblclick")
            {
                if (event.shiftKey)
                    modifier += "S-";
                if (event.type == "dblclick")
                    modifier += "2-";
                // TODO: triple and quadruple click

                switch (event.button)
                {
                    case 0:
                        key = "LeftMouse";
                        break;
                    case 1:
                        key = "MiddleMouse";
                        break;
                    case 2:
                        key = "RightMouse";
                        break;
                }
            }

            if (key == null)
                return null;

            // a key like F1 is always enclosed in < and >
            return "<" + modifier + key + ">";
        },

        isAcceptKey: function (key)
        {
            return (key == "<Return>" || key == "<C-j>" || key == "<C-m>");
        },

        isCancelKey: function (key)
        {
            return (key == "<Esc>" || key == "<C-[>" || key == "<C-c>");
        },

        getMapLeader: function ()
        {
            var leaderRef = liberator.variableReference("mapleader");
            return leaderRef[0] ? leaderRef[0][leaderRef[1]] : "\\";
        },

        // argument "event" is delibarately not used, as i don't seem to have
        // access to the real focus target
        //
        // the ugly wantsModeReset is needed, because firefox generates a massive
        // amount of focus changes for things like <C-v><C-k> (focusing the search field)
        onFocusChange: function (event)
        {
            // command line has it's own focus change handler
            if (liberator.mode == liberator.modes.COMMAND_LINE)
                return;

            var win  = window.document.commandDispatcher.focusedWindow;
            var elem = window.document.commandDispatcher.focusedElement;
            if (elem && elem.readOnly)
                return;

            // dump("=+++++++++=\n" + liberator.util.objectToString(event.target) + "\n")
            // dump (elem + ": " + win + "\n");//" - target: " + event.target + " - origtarget: " + event.originalTarget + " - expltarget: " + event.explicitOriginalTarget + "\n");

            if (elem && (
                   (elem instanceof HTMLInputElement && (elem.type.toLowerCase() == "text" || elem.type.toLowerCase() == "password")) ||
                   (elem instanceof HTMLSelectElement)
                ))
            {
                this.wantsModeReset = false;
                liberator.mode = liberator.modes.INSERT;
                liberator.buffer.lastInputField = elem;
                return;
            }

            if (elem && elem instanceof HTMLTextAreaElement)
            {
                this.wantsModeReset = false;
                if (liberator.options["insertmode"])
                    liberator.modes.set(liberator.modes.INSERT, liberator.modes.TEXTAREA);
                else if (elem.selectionEnd - elem.selectionStart > 0)
                    liberator.modes.set(liberator.modes.VISUAL, liberator.modes.TEXTAREA);
                else
                    liberator.modes.main = liberator.modes.TEXTAREA;
                liberator.buffer.lastInputField = elem;
                return;
            }

            if (liberator.config.name == "Muttator")
            {
                // we switch to -- MESSAGE -- mode for muttator, when the main HTML widget gets focus
                if ((win && win.document && win.document instanceof HTMLDocument)
                    || elem instanceof HTMLAnchorElement)
                {
                    if (liberator.config.isComposeWindow)
                    {
                        dump("Compose editor got focus\n");
                        liberator.modes.set(liberator.modes.INSERT, liberator.modes.TEXTAREA);
                        //setTimeout(function (){ liberator.editor.editWithExternalEditor(); }, 100);
                        win.blur();
                        //liberator.editor.editWithExternalEditor();
                    }
                    else if (liberator.mode != liberator.modes.MESSAGE)
                        liberator.mode = liberator.modes.MESSAGE;
                    return;
                }
            }

            if (liberator.mode == liberator.modes.INSERT ||
                liberator.mode == liberator.modes.TEXTAREA ||
                liberator.mode == liberator.modes.MESSAGE ||
                liberator.mode == liberator.modes.VISUAL)
            {
               // FIXME: currently this hack is disabled to make macros work
               // this.wantsModeReset = true;
               // setTimeout(function ()
               // {
               //     dump("cur: " + liberator.mode + "\n");
               //     if (liberator.events.wantsModeReset)
               //     {
               //         liberator.events.wantsModeReset = false;
                        liberator.modes.reset();
               //     }
               // }, 0);
            }
        },

        onSelectionChange: function (event)
        {
            var couldCopy = false;
            var controller = document.commandDispatcher.getControllerForCommand("cmd_copy");
            if (controller && controller.isCommandEnabled("cmd_copy"))
                couldCopy = true;

            if (liberator.mode != liberator.modes.VISUAL)
            {
                if (couldCopy)
                {
                    if ((liberator.mode == liberator.modes.TEXTAREA ||
                         (liberator.modes.extended & liberator.modes.TEXTAREA))
                            && !liberator.options["insertmode"])
                        liberator.modes.set(liberator.modes.VISUAL, liberator.modes.TEXTAREA);
                    else if (liberator.mode == liberator.modes.CARET)
                        liberator.modes.set(liberator.modes.VISUAL, liberator.modes.CARET);
                }
            }
            // XXX: disabled, as i think automatically starting visual caret mode does more harm than help
            // else
            // {
            //     if (!couldCopy && liberator.modes.extended & liberator.modes.CARET)
            //         liberator.mode = liberator.modes.CARET;
            // }
        },

        // global escape handler, is called in ALL modes
        onEscape: function ()
        {
            if (!liberator.modes.passNextKey)
            {
                if (liberator.modes.passAllKeys)
                {
                    liberator.modes.passAllKeys = false;
                    return;
                }

                switch (liberator.mode)
                {
                    case liberator.modes.NORMAL:
                        // clear any selection made
                        var selection = window.content.getSelection();
                        try
                        { // a simple if (selection) does not seem to work
                            selection.collapseToStart();
                        }
                        catch (e) { }
                        liberator.commandline.clear();

                        liberator.modes.reset();
                        liberator.focusContent(true);
                        break;

                    case liberator.modes.VISUAL:
                        if (liberator.modes.extended & liberator.modes.TEXTAREA)
                            liberator.mode = liberator.modes.TEXTAREA;
                        else if (liberator.modes.extended & liberator.modes.CARET)
                            liberator.mode = liberator.modes.CARET;
                        break;

                    case liberator.modes.CARET:
                        // setting this option will trigger an observer which will
                        // care about all other details like setting the NORMAL mode
                        liberator.options.setPref("accessibility.browsewithcaret", false);
                        break;

                    case liberator.modes.INSERT:
                        if ((liberator.modes.extended & liberator.modes.TEXTAREA) && !liberator.options["insertmode"])
                        {
                            liberator.mode = liberator.modes.TEXTAREA;
                        }
                        else
                        {
                            liberator.modes.reset();
                            liberator.focusContent(true);
                        }
                        break;

                    default: // HINTS, CUSTOM or COMMAND_LINE
                        liberator.modes.reset();
                        break;
                }
            }
        },

        // this keypress handler gets always called first, even if e.g.
        // the commandline has focus
        onKeyPress: function (event)
        {
            var key = liberator.events.toString(event);
            if (!key)
                 return true;

            // liberator.log(key + " in mode: " + liberator.mode);
            // dump(key + " in mode: " + liberator.mode + "\n");

            if (liberator.modes.isRecording)
            {
                if (key == "q") // TODO: should not be hardcoded
                {
                    liberator.modes.isRecording = false;
                    liberator.log("Recorded " + currentMacro + ": " + macros[currentMacro], 8);
                    event.preventDefault();
                    event.stopPropagation();
                    return true;
                }
                else if (!(liberator.modes.extended & liberator.modes.INACTIVE_HINT) &&
                         !liberator.mappings.hasMap(liberator.mode, liberator.input.buffer + key))
                {
                    macros[currentMacro] += key;
                }
            }

            var stop = true; // set to false if we should NOT consume this event but let also firefox handle it

            var win = document.commandDispatcher.focusedWindow;
            if (win && win.document.designMode == "on" && !liberator.config.isComposeWindow)
                return false;

            // menus have their own command handlers
            if (liberator.modes.extended & liberator.modes.MENU)
                return false;

            // handle Escape-one-key mode (Ctrl-v)
            if (liberator.modes.passNextKey && !liberator.modes.passAllKeys)
            {
                liberator.modes.passNextKey = false;
                return false;
            }
            // handle Escape-all-keys mode (Ctrl-q)
            if (liberator.modes.passAllKeys)
            {
                if (liberator.modes.passNextKey)
                    liberator.modes.passNextKey = false; // and then let flow continue
                else if (key == "<Esc>" || key == "<C-[>" || key == "<C-v>")
                    ; // let flow continue to handle these keys to cancel escape-all-keys mode
                else
                    return false;
            }

            // just forward event without checking any mappings when the MOW is open
            if (liberator.mode == liberator.modes.COMMAND_LINE &&
                (liberator.modes.extended & liberator.modes.OUTPUT_MULTILINE))
            {
                liberator.commandline.onMultilineOutputEvent(event);
                event.preventDefault();
                event.stopPropagation();
                return false;
            }

            // XXX: ugly hack for now pass certain keys to firefox as they are without beeping
            // also fixes key navigation in combo boxes, submitting forms, etc.
            // FIXME: breaks iabbr for now --mst
            if ((liberator.config.name == "Vimperator" && liberator.mode == liberator.modes.NORMAL)
                 || liberator.mode == liberator.modes.INSERT)
            {
                if (key == "<Return>")
                    return false;
                else if (key == "<Space>" || key == "<Up>" || key == "<Down>")
                    return false;
            }

        //  // FIXME: handle middle click in content area {{{
        //  //     alert(event.target.id);
        //  if (/*event.type == 'mousedown' && */event.button == 1 && event.target.id == 'content')
        //  {
        //      //echo("foo " + event.target.id);
        //      //if (document.commandDispatcher.focusedElement == command_line.inputField)
        //      {
        //      //alert(command_line.value.substring(0, command_line.selectionStart));
        //          command_line.value = command_line.value.substring(0, command_line.selectionStart) +
        //                               readFromClipboard() +
        //                               command_line.value.substring(command_line.selectionEnd, command_line.value.length);
        //         alert(command_line.value);
        //      }
        //      //else
        // //       {
        // //           openURLs(readFromClipboard());
        // //       }
        //      return true;
        //  } }}}

            if (key != "<Esc>" && key != "<C-[>")
            {
                // custom mode...
                if (liberator.mode == liberator.modes.CUSTOM)
                {
                    liberator.plugins.onEvent(event);
                    event.preventDefault();
                    event.stopPropagation();
                    return false;
                }
                // if Hit-a-hint mode is on, special handling of keys is required
                if (liberator.mode == liberator.modes.HINTS)
                {
                    liberator.hints.onEvent(event);
                    event.preventDefault();
                    event.stopPropagation();
                    return false;
                }
            }

            // FIXME (maybe): (is an ESC or C-] here): on HINTS mode, it enters
            // into 'if (map && !skipMap) below. With that (or however) it
            // triggers the onEscape part, where it resets mode. Here I just
            // return true, with the effect that it also gets to there (for
            // whatever reason).  if that happens to be correct, well..
            // XXX: why not just do that as well for HINTS mode actually?

            if (liberator.mode == liberator.modes.CUSTOM)
                return true;

            var countStr = liberator.input.buffer.match(/^[0-9]*/)[0];
            var candidateCommand = (liberator.input.buffer + key).replace(countStr, "");
            var map;
            if (event.noremap)
                map = liberator.mappings.getDefault(liberator.mode, candidateCommand);
            else
                map = liberator.mappings.get(liberator.mode, candidateCommand);


            // counts must be at the start of a complete mapping (10j -> go 10 lines down)
            if (/^[1-9][0-9]*$/.test(liberator.input.buffer + key))
            {
                // no count for insert mode mappings
                if (liberator.mode == liberator.modes.INSERT || liberator.mode == liberator.modes.COMMAND_LINE)
                    stop = false;
                else
                {
                    liberator.input.buffer += key;
                    inputBufferLength++;
                }
            }
            else if (liberator.input.pendingArgMap)
            {
                liberator.input.buffer = "";
                inputBufferLength = 0;
                var tmp = liberator.input.pendingArgMap; // must be set to null before .execute; if not
                liberator.input.pendingArgMap = null;    // v.input.pendingArgMap is still 'true' also for new feeded keys
                if (key != "<Esc>" && key != "<C-[>")
                {
                    if (liberator.modes.isReplaying && !waitForPageLoaded())
                        return true;

                    tmp.execute(null, liberator.input.count, key);
                }
            }
            // only follow a map if there isn't a longer possible mapping
            // (allows you to do :map z yy, when zz is a longer mapping than z)
            // TODO: map.rhs is only defined for user defined commands, should add a "isDefault" property
            else if (map && !skipMap && (map.rhs ||
                     liberator.mappings.getCandidates(liberator.mode, candidateCommand).length == 0))
            {
                liberator.input.count = parseInt(countStr, 10);
                if (isNaN(liberator.input.count))
                    liberator.input.count = -1;
                if (map.flags & liberator.Mappings.flags.ARGUMENT)
                {
                    liberator.input.pendingArgMap = map;
                    liberator.input.buffer += key;
                    inputBufferLength++;
                }
                else if (liberator.input.pendingMotionMap)
                {
                    if (key != "<Esc>" && key != "<C-[>")
                    {
                        liberator.input.pendingMotionMap.execute(candidateCommand, liberator.input.count, null);
                    }
                    liberator.input.pendingMotionMap = null;
                    liberator.input.buffer = "";
                    inputBufferLength = 0;
                }
                // no count support for these commands yet
                else if (map.flags & liberator.Mappings.flags.MOTION)
                {
                    liberator.input.pendingMotionMap = map;
                    liberator.input.buffer = "";
                    inputBufferLength = 0;
                }
                else
                {
                    liberator.input.buffer = "";
                    inputBufferLength = 0;

                    if (liberator.modes.isReplaying && !waitForPageLoaded())
                        return true;

                    var ret = map.execute(null, liberator.input.count);
                    if (map.flags & liberator.Mappings.flags.ALLOW_EVENT_ROUTING && ret)
                        stop = false;
                }
            }
            else if (liberator.mappings.getCandidates(liberator.mode, candidateCommand).length > 0 && !skipMap)
            {
                liberator.input.buffer += key;
                inputBufferLength++;
            }
            else // if the key is neither a mapping nor the start of one
            {
                // the mode checking is necessary so that things like g<esc> do not beep
                if (liberator.input.buffer != "" && !skipMap && (liberator.mode == liberator.modes.INSERT ||
                    liberator.mode == liberator.modes.COMMAND_LINE || liberator.mode == liberator.modes.TEXTAREA))
                {
                    // no map found -> refeed stuff in v.input.buffer (only while in INSERT, CO... modes)
                    skipMap = true; // ignore maps while doing so
                    liberator.events.feedkeys(liberator.input.buffer, true);
                }
                if (skipMap)
                {
                    if (--inputBufferLength == 0) // inputBufferLength == 0. v.input.buffer refeeded...
                        skipMap = false; // done...
                }

                liberator.input.buffer = "";
                liberator.input.pendingArgMap = null;
                liberator.input.pendingMotionMap = null;

                if (key != "<Esc>" && key != "<C-[>")
                {
                    // allow key to be passed to firefox if we can't handle it
                    stop = false;

                    if (liberator.mode == liberator.modes.COMMAND_LINE)
                    {
                        if (!(liberator.modes.extended & liberator.modes.INPUT_MULTILINE))
                            stop = !liberator.commandline.onEvent(event); // reroute event in command line mode
                    }
                    else if (liberator.mode != liberator.modes.INSERT)
                        liberator.beep();
                }
            }

            if (stop)
            {
                event.preventDefault();
                event.stopPropagation();
            }

            var motionMap = (liberator.input.pendingMotionMap && liberator.input.pendingMotionMap.names[0]) || "";
            liberator.statusline.updateInputBuffer(motionMap + liberator.input.buffer);
            return false;
        },

        // this is need for sites like msn.com which focus the input field on keydown
        onKeyUpOrDown: function (event)
        {
            if (liberator.modes.passNextKey ^ liberator.modes.passAllKeys || isFormElemFocused())
                return true;

            event.stopPropagation();
            return false;
        },

        // TODO: move to buffer.js?
        progressListener: {
            QueryInterface: function (aIID)
            {
                if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
                        aIID.equals(Components.interfaces.nsIXULBrowserWindow) || // for setOverLink();
                        aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
                        aIID.equals(Components.interfaces.nsISupports))
                    return this;
                throw Components.results.NS_NOINTERFACE;
            },

            // XXX: function may later be needed to detect a canceled synchronous openURL()
            onStateChange: function (webProgress, request, flags, status)
            {
                // STATE_IS_DOCUMENT | STATE_IS_WINDOW is important, because we also
                // receive statechange events for loading images and other parts of the web page
                if (flags & (Components.interfaces.nsIWebProgressListener.STATE_IS_DOCUMENT |
                            Components.interfaces.nsIWebProgressListener.STATE_IS_WINDOW))
                {
                    // This fires when the load event is initiated
                    // only thrown for the current tab, not when another tab changes
                    if (flags & Components.interfaces.nsIWebProgressListener.STATE_START)
                    {
                        liberator.buffer.loaded = 0;
                        liberator.statusline.updateProgress(0);
                        setTimeout (function () { liberator.modes.reset(false); },
                            liberator.mode == liberator.modes.HINTS ? 500 : 0);
                    }
                    else if (flags & Components.interfaces.nsIWebProgressListener.STATE_STOP)
                    {
                        liberator.buffer.loaded = (status == 0 ? 1 : 2);
                        liberator.statusline.updateUrl();
                    }
                }
            },
            // for notifying the user about secure web pages
            onSecurityChange: function (webProgress, aRequest, aState)
            {
                const nsIWebProgressListener = Components.interfaces.nsIWebProgressListener;
                if (aState & nsIWebProgressListener.STATE_IS_INSECURE)
                    liberator.statusline.setClass("insecure");
                else if (aState & nsIWebProgressListener.STATE_IS_BROKEN)
                    liberator.statusline.setClass("broken");
                else if (aState & nsIWebProgressListener.STATE_IS_SECURE)
                    liberator.statusline.setClass("secure");
            },
            onStatusChange: function (webProgress, request, status, message)
            {
                liberator.statusline.updateUrl(message);
            },
            onProgressChange: function (webProgress, request, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress)
            {
                liberator.statusline.updateProgress(curTotalProgress/maxTotalProgress);
            },
            // happens when the users switches tabs
            onLocationChange: function ()
            {
                liberator.statusline.updateUrl();
                liberator.statusline.updateProgress();

                // if this is not delayed we get the position of the old buffer
                setTimeout(function () { liberator.statusline.updateBufferPosition(); }, 100);
            },
            // called at the very end of a page load
            asyncUpdateUI: function ()
            {
                setTimeout(liberator.statusline.updateUrl, 100);
            },
            setOverLink : function (link, b)
            {
                var ssli = liberator.options["showstatuslinks"];
                if (link && ssli)
                {
                    if (ssli == 1)
                        liberator.statusline.updateUrl("Link: " + link);
                    else if (ssli == 2)
                        liberator.echo("Link: " + link, liberator.commandline.DISALLOW_MULTILINE);
                }

                if (link == "")
                {
                    if (ssli == 1)
                        liberator.statusline.updateUrl();
                    else if (ssli == 2)
                        liberator.modes.show();
                }
            },

            // stub functions for the interfaces
            setJSStatus: function (status) { ; },
            setJSDefaultStatus: function (status) { ; },
            setDefaultStatus: function (status) { ; },
            onLinkIconAvailable: function () { ; }
        },

        // TODO: move to options.js?
        prefObserver: {
            register: function ()
            {
                var prefService = Components.classes["@mozilla.org/preferences-service;1"]
                      .getService(Components.interfaces.nsIPrefService);
                  this._branch = prefService.getBranch(""); // better way to monitor all changes?
                  this._branch.QueryInterface(Components.interfaces.nsIPrefBranch2);
                  this._branch.addObserver("", this, false);
            },

            unregister: function ()
            {
                if (!this._branch) return;
                this._branch.removeObserver("", this);
            },

            observe: function (aSubject, aTopic, aData)
            {
                if (aTopic != "nsPref:changed")
                    return;

                // aSubject is the nsIPrefBranch we're observing (after appropriate QI)
                // aData is the name of the pref that's been changed (relative to aSubject)
                switch (aData)
                {
                    case "accessibility.browsewithcaret":
                        var value = liberator.options.getPref("accessibility.browsewithcaret", false);
                        liberator.mode = value ? liberator.modes.CARET : liberator.modes.NORMAL;
                        break;
                }
             }
        }
    };

    window.XULBrowserWindow = eventManager.progressListener;
    window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
        .getInterface(Components.interfaces.nsIWebNavigation)
        .QueryInterface(Components.interfaces.nsIDocShellTreeItem).treeOwner
        .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
        .getInterface(Components.interfaces.nsIXULWindow)
        .XULBrowserWindow = window.XULBrowserWindow;
    try
    {
        getBrowser().addProgressListener(eventManager.progressListener, Components.interfaces.nsIWebProgress.NOTIFY_ALL);
    }
    catch(e) { }

    eventManager.prefObserver.register();

    window.addEventListener("keypress", eventManager.onKeyPress,    true);
    window.addEventListener("keydown",  eventManager.onKeyUpOrDown, true);
    window.addEventListener("keyup",    eventManager.onKeyUpOrDown, true);

    return eventManager;
    //}}}
}; //}}}

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