-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path.pentadactylrc
16686 lines (14642 loc) · 670 KB
/
.pentadactylrc
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
" ___________________ "
" / \ "
" | ,---------------, | "
" | | PENTADACTYLRC | | "
" | '---------------' | "
" \___________________/ "
" "
" "
group user
runtime! utils.js
js var utils = dactyl.utils.getPlugin("utils");
runtime! personal.js
runtime! js/jquery-3.3.1.min.js
runtime! js/sprintf.js
runtime! js/suncalc.js
runtime! js/simulateHtmlMouseEvent.js
runtime! js/svg-pan-zoom.min.js
set passkeys=
" ----------------------------------------------------------------------------- "
" ,------------------------, "
" | Javascript helper code | "
" '------------------------' "
command! setdactylrc
\ -description "Set dactyl.rc property in the global context"
\ -js window.dactyl.rc = plugins[`${env.get("HOME")}/.pentadactylrc`];
js <<EOF
var env = Components.classes["@mozilla.org/process/environment;1"].getService(Components.interfaces.nsIEnvironment);
window.dactyl.rc = plugins[`${env.get("HOME")}/.pentadactylrc`];
var $$ = function(sel, context) { return Array.from(jQuery(sel, context||content.document)); }
var $1 = function(sel, context) { return A.first($$(sel, context)); }
var $j = function(sel, context) { return jQuery(sel, context||content.document); }
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;
" ----------------------------------------------------------------------------- "
" System ";
var user = dactyl.utils.getPlugin("personal");
var homedir = env.get("HOME");
var rcdir = homedir + "/.pentadactyl";
var musicdir = homedir + "/Music/Music";
var downloadsdir = homedir + "/Downloads";
" ----------------------------------------------------------------------------- "
"imports"
/* Cu.import loads JS code modules (.jsm files). See https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules */
Cu.import("resource://gre/modules/BookmarkHTMLUtils.jsm");
Cu.import("resource://gre/modules/FileUtils.jsm");
Cu.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
" https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/OSFile.jsm/OS.File_for_the_main_thread "
Cu.import("resource://gre/modules/osfile.jsm");
" https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Language_Bindings/Components.utils.importGlobalProperties "
Components.utils.importGlobalProperties(["TextDecoder"]);
var mozIJSSubScriptLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader);
/* mozIJSSubScriptLoader.loadSubScript(url, targetObj=global) */
/* load math.js (as `math`) */
mozIJSSubScriptLoader.loadSubScript(`file://${rcdir}/js/math.min.js`);
" ----------------------------------------------------------------------------- "
"components"
var Cc = Components.classes;
function XpcService(url, ifc) {
try {
var interface = Ci[ifc];
return Cc[url].getService(interface);
} catch(e) {
utils.message("XpcService: Cannot get service " + url + ", " + ifc + "\n" + e);
return null;
}
}
function XpcInstance(url, ifc) {
try {
var interface = Ci[ifc];
return Cc[url].createInstance(interface);
} catch(e) {
utils.message("XpcInstance: Cannot create instance " + url + ", " + ifc + "\n" + e);
return null;
}
}
function XpcQueryInterface(elt, ifc) {
try {
var interface = Ci[ifc];
return elt.QueryInterface(interface);
} catch(e) {
utils.message("XpcQueryInterface: Cannot query interface " + ifc + " of " + elt + "\n" + e);
return null;
}
}
" ----------------------------------------------------------------------------- "
var nsIFilePicker = Ci.nsIFilePicker;
var WebBrowserPersist = Components.Constructor("@mozilla.org/embedding/browser/nsWebBrowserPersist;1",
"nsIWebBrowserPersist");
var nsISessionStore = XpcService("@mozilla.org/browser/sessionstore;1", Components.interfaces.nsISessionStore)
" Firefox current directory ";
function ffWorkingDir() {
var nsIDirServiceP = XpcService("@mozilla.org/file/directory_service;1", Ci.nsIDirectoryServiceProvider);
return nsIDirServiceP.getFile("CurWorkD", {}).path;
}
"Firefox Preferences"
var prefservice = Cc["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
function prefbranch(branch) { return prefservice.getBranch(branch); }
var prefroot = Cc["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
" String Preferences: prefroot.(g|s)etCharPref for ASCII, prefroot.getComplexValue for unicode... "
function getStrPref(pref) { return prefroot.getComplexValue(pref, Components.interfaces.nsISupportsString); }
function setStrPref(pref, value) {
prefroot.setComplexValue(pref, Components.interfaces.nsISupportsString, value);
}
"Bookmarks"
var nsINavBookmarksService = XpcService("@mozilla.org/browser/nav-bookmarks-service;1", Components.interfaces.nsINavBookmarksService);
var bmarksMenuFolder = nsINavBookmarksService.bookmarksMenuFolder;
var nsIIOService = XpcService("@mozilla.org/network/io-service;1", Components.interfaces.nsIIOService);
function createURI(url) { return nsIIOService.newURI(url, null, null); }
function createBmark(url, title, folderId=bmarksMenuFolder) {
return nsINavBookmarksService.insertBookmark(
folderId,
createURI(url),
nsINavBookmarksService.DEFAULT_INDEX,
title);
}
function fetchBmarkUrlByKeyword(kw, callback) {
PlacesUtils.keywords.fetch(kw).then(
entry => { callback(entry.url.href) },
e => { Cu.reportError(`bookmark keyword ${kw} not found.`) });
}
"History"
var nsIHistoryService = Cc["@mozilla.org/browser/nav-history-service;1"].getService(Ci.nsINavHistoryService);
function uri(spec) {
return Cc["@mozilla.org/network/io-service;1"].
getService(Ci.nsIIOService).
newURI(spec, null, null);
}
var nsIBrowserHistory = nsIHistoryService.QueryInterface(Ci.nsIBrowserHistory);
function historyRemoveURI(url=getAddressBarURL()) { nsIBrowserHistory.removePage(uri(url)); }
"Application"
var xulAppInfo = Cc["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);
var isPalemoon = prefs.has("app.vendorURL") && prefroot.getCharPref("app.vendorURL").includes("palemoon");
var isBasilisk = prefs.has("app.vendorURL") && prefroot.getCharPref("app.vendorURL").includes("basilisk");
var isFirefox = prefs.has("app.update.url") && prefroot.getCharPref("app.update.url").includes("mozilla");
var isWaterfox = prefs.has("app.update.url") && prefroot.getCharPref("app.update.url").includes("waterfox");
var browser;
if (isPalemoon) browserExec = "/opt/palemoon/palemoon";
if (isBasilisk) browserExec = "/opt/basilisk/basilisk";
if (isFirefox) browserExec = "/opt/firefox/firefox";
if (isWaterfox) browserExec = "/opt/waterfox/waterfox";
"utility functions"
// Array methods for other collections
A = {
uniq: (coll) => [...new RealSet(coll)],
from: (coll) => Array.from(coll),
create: (n, init=null) => Array.from({length: n}).map(_=>init),
repeat: (coll, n) => (new Array(n)).fill(Array.from(coll)).flatMap(),
slice: (coll, ...rest) => Array.prototype.slice.call(coll, ...rest),
map: (coll, f) => Array.from(coll).map(f),
filter: (coll, f) => Array.from(coll).filter(f),
forEach: (coll, f) => Array.from(coll).forEach(f),
find: (coll, f) => Array.from(coll).find(f),
sorted: (coll) => Array.from(coll).slice().sort(),
every: (coll, f) => Array.from(coll).every(f),
some: (coll, f) => Array.from(coll).some(f),
includes: (coll, f, fromIndex=undefined) => Array.from(coll).includes(f, fromIndex),
indexOf: (coll, f, fromIndex=undefined) => Array.from(coll).indexOf(f, fromIndex),
first: (coll) => {
var elts = Array.from(coll);
if (elts && elts.length>0)
return elts[0];
},
nth: (coll, n=1) => {
var elts = Array.from(coll);
var N = elts.length;
if (elts && N>=n)
return elts[(n-1)%N];
},
last: (coll) => {
var elts = Array.from(coll);
if (elts && elts.length>0)
return elts[elts.length-1];
},
concatMap: (coll, f) => [].concat.apply([], Array.from(coll).map(e=>Array.from(f(e)))),
mapProperty: (coll, p) => Array.from(coll).map(e=>e[p]),
zip2: (coll1, coll2) => Array.from(coll1).map((e,i)=>[e, coll2[i]]),
zip: (...colls) => Array.from(colls[0]).map((_,i)=>colls.map(coll=>coll[i])),
split: (coll, e) => {
var subArrays = [];
var currentSub = [];
for (var i=0; i<coll.length; ++i) {
if (coll[i]==e) {
subArrays.push(currentSub);
currentSub = [];
} else {
currentSub.push(coll[i]);
}
}
subArrays.push(currentSub);
return subArrays;
},
range: function (...args) {
" range([beg=0], end, [step=1]) ";
var beg=0, end, step=1;
var res=[], curr;
if (args.length == 1)
[end] = args;
else
[beg, end, step=1] = args;
if (step > 0) {
if (end > beg) res[0] = curr = beg;
while (curr + step < end) res.push(curr += step);
} else if (step < 0) {
if (end < beg) res[0] = curr = beg;
while (curr + step > end) res.push(curr += step);
}
return res;
},
toLines: (coll) => Array.from(coll).reduce((s,i)=>`${s}\n${i}`),
/* numeric array */
differences: a => a.reduce((acc,c,i,arr) => acc.concat([acc.length && (c-arr[i-1])]), [])
}
// String methods
S = {
// padEnd, padStart: adapted from github.com/uxitten/polyfill
padEnd: function (s, targetLength, padString) {
targetLength = targetLength >> 0; //floor if number or convert non-number to 0;
padString = String((typeof padString !== 'undefined' ? padString : ' '));
if (s.length > targetLength) {
return String(s);
} else {
targetLength = targetLength - s.length;
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length);
}
return String(s) + padString.slice(0, targetLength);
}
},
padStart: function (s, targetLength, padString) {
targetLength = targetLength >> 0; //floor if number or convert non-number to 0;
padString = String((typeof padString !== 'undefined' ? padString : ' '));
if (s.length > targetLength) {
return String(s);
}
else {
targetLength = targetLength - s.length;
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length);
//append to original to ensure we are longer than needed
}
return padString.slice(0, targetLength) + String(s);
}
},
repeat: function (s, n) { return Array(n).fill(s).join(""); },
isLowercase: function(s) {
return s.toLowerCase()===s;
},
isUppercase: function(s) {
return s.toUpperCase()===s;
},
isMixedcase: function(s) {
return !(this.isLowercase(s) || this.isUppercase(s));
},
capitalize: function(s) {
return s.replace(/\b\w/g, function (c) { return c.toUpperCase(); });
},
strip: function (s) {
return s.replace(/^\s+|\s+$/g, "");
},
toLines: function (s, n=160, sep=/([^, ]+[, ]+)/) {
var lines = s.split("\n");
var lines_ = [];
for (var line of lines) {
var parts = line.split(sep);
var line_ = "";
var line_length = 0;
for (var part of parts) {
if (line_length + part.length > n) {
lines_.push(line_);
line_ = part; line_length = part.length;
} else {
line_ += part;
line_length += part.length;
}
}
lines_.push(line_);
}
return lines_;
},
toSmartCase: function (s) {
return (s.toLowerCase()===s) ? S.toStartCase(s) : s;
},
toStartCase: function (s) {
var words = s.split(/\s+/);
return A.map(words, w=>this.capitalize(w)).join(" ");
},
toLength: function (s, n, pad=" ") {
n = parseInt(n);
if (s.length > n) return s.slice(0,n);
else return S.padEnd(s, n, pad);
},
titleCaseExceptionWords: ["a", "an", "the", "and", "or", "but", "nor",
"yet", "so", "for", "in", "to", "of", "at",
"by", "for", "off", "on", "as", "x"],
toTitleCase: function (s, excWords=this.titleCaseExceptionWords) {
var words = s.split(/\s+/);
var tcWords = words.map(w => excWords.includes(w) ? w : this.capitalize(w));
" If first word is capitalized, leave it capitalized even if an exception word "
var initialLetter = s.slice(0, 1);
var hasInitialCap = this.isUppercase(initialLetter);
if (hasInitialCap) tcWords[0] = words[0];
return tcWords.join(" ");
},
isAlphaAt: function (s, i) {
ord = s.charCodeAt(i);
return (ord.inRange(97, 123));
},
firstLineEllipsis: function (s) {
var s = String(s);
var lines = s.split("\n").filter(s=>s.match(/\S/));
if (lines.length > 1)
return lines[0] + "...";
else return lines[0];
},
arrayWithEmptyStringDefault: function(a) {
var arr = Array.from(a);
return arr.map(elem => typeof elem == "undefined" ? "" : String(elem));
},
escapeRegexSymbols: function (s, opts={}) {
var regexSpecialCharRegex;
if (opts.forwardSlashDelimiters) {
regexSpecialCharRegex = /[[(){^$\\*+?.|\/]/g;
return "/" + s.replace(regexSpecialCharRegex, c=>"\\"+c) + "/";
} else {
regexSpecialCharRegex = /[[(){^$\\*+?.|]/g;
return s.replace(regexSpecialCharRegex, c=>"\\"+c);
}
},
/* can be used to check multiple regexes, eg. S.getRegexMatch(re1)||S.getRegexMatch(re2) */
getRegexMatch: function (s, regex, group_num=1) {
var match = s.match(regex);
return match && match[group_num] || "";
}
}
// Object methods
Object.prototype.map = function(f) {
var result = {};
for (var key in this) {
if (this.hasOwnProperty(key))
result[key] = f(this[key]);
}
return result;
}
function runProcess(exec, ...args) {
var executable = XpcInstance("@mozilla.org/file/local;1", Components.interfaces.nsILocalFile);
executable.initWithPath(exec);
var process = XpcInstance("@mozilla.org/process/util;1", Components.interfaces.nsIProcess);
process.init(executable);
process.runAsync(args, args.length);
}
function makeDisplayToggle(selector) {
function displayToggle() {
var elt = content.document.querySelector(selector);
if (elt) {
if (elt.style.display == 'none')
elt.style.display = 'block';
else elt.style.display = 'none';
} else dactyl.echoerr(`no match for selector ${selector}`);
}
return displayToggle;
}
"Patched Classes"
Number.prototype.inRange = function (a, b) {
return (a <= this && this < b);
}
var AUDperUSD = 1.36;
" Eval Functions "
function evalStringOrFunction(s) {
"String s represents either a string (itself) or a function.";
if (s && s.match(/\(.*\)|=>/)) {
return eval(s);
} else { return s || null; }
}
function evalWithScriptTag(code, doc) {
var script = content.document.createElement("script");
try { script.innerText = code; }
catch(e) {
script.appendChild(content.document.createTextNode(code));
}
content.document.head.appendChild(script);
script.parentNode.removeChild(script);
}
function readFromFile(f) {
" Returns a promise. Usage: readFromFile(f).then(s=>doSomething(s)); "
" Code from https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/OSFile.jsm/ "
let decoder = new TextDecoder(); // This decoder can be reused for several reads
let promise = OS.File.read(f); // Read the complete file as an array
promise = promise.then(
function onSuccess(array) {
return decoder.decode(array); // Convert this array to a text
}
);
return promise;
}
EOF
" ,-------------------------------,
" | Pentadactyl Utility Functions |
" '-------------------------------'
js <<EOF
/* readStringOrRegex: converts a string to a regex if possible, else returns */
/* the string. Can be used to accept either a string or regex argument for */
/* a command: `-js doSomething(args.map(readStringOrRegex))` */
function readStringOrRegex(s) {
var matches = s.match(/^\/([^/]*)\/([gimuy]*)$/);
if (matches)
return RegExp(matches[1], matches[2]);
else
return s;
}
function getMappings() { return Array.from(mappings); }
" matchMappingsByKey: key may be a string or regex "
function matchMappingsByKey(key) {
return getMappings().filter(m=>m.keys.map(k=>k.search(key)>=0).reduce((x,y)=>(x||y), false));
}
" matchMappingsByKeyAndMode: mode may be a string, regex or Mode instance "
function matchMappingsByKeyAndMode(key, mode=modes.NORMAL) {
return getMappings().filter(
function(m) {
return m.keys.map(k=>k.search(key)>=0).reduce((x,y)=>(x||y), false) &&
( m.modes.map(md=>md.toString()).join(" ").search(mode)>=0 ||
m.modes.includes(mode)>=0 );
});
}
" matchMappingsByDescription: desc may be a string or regex "
function matchMappingsByDescription(desc) {
return getMappings().filter(m=>m.description.search(desc)>=0);
}
" mappingsByGroup: name is a string matching the name of an active group "
function mappingsByGroup(name) {
return getMappings().filter((m)=>m.hive.name==name);
}
" listGroupMappings: name is a string matching the name of an active group "
function listGroupMappings(name) {
return mappingsByGroup(name).map(m=>[m.name, m.description+': '+m.action]);
}
" listActiveGroupMappings: list mappings and descriptions for active groups "
function listActiveGroupMappings() {
var activegroups = contexts.activeGroups();
var activemappings = activegroups.flatMap(
g => Array.from(g.mappings.iterate([modes.NORMAL])).concat(
Array.from(g.mappings.iterate([modes.INSERT])))
);
return activemappings.map(m=>[m.name, m.description+': '+m.action]);
}
" eg. getHive('jisho', MapHive) "
function getHive(name, type) {
var groupByName = group.children.filter(g=>g.name==name)[0];
var matchesType = (hive) =>
isinstance(hive, type) || hive._class_.toString()==`[class ${type}]`;
return groupByName.hives.filter(matchesType)[0];
}
function searchMappings(...pats) {
var activegroups = contexts.activeGroups();
var activemappings = activegroups.flatMap(
g => Array.from(g.mappings.iterate([modes.NORMAL])).concat(
Array.from(g.mappings.iterate([modes.INSERT]))).concat(
Array.from(g.mappings.iterate([modes.BASE])))
);
var filtered = activemappings.filter(
m => pats.every(
p => {
if (typeof p == "string" && p.toLowerCase()==p) {
return m.name.toLowerCase().search(p)>=0 ||
m.description.toLowerCase().search(p)>=0 ||
m.action.toString().toLowerCase().search(p)>=0
} else {
return m.name.search(p)>=0 ||
m.description.search(p)>=0 ||
m.action.toString().search(p)>=0
}
}) );
var maxlen = filtered.map(m=>m.name.length).reduce((acc,cur)=>Math.max(acc,cur), 0);
var maxlendesc = Math.min(
50,
filtered.map(m=>m.description.length).reduce((acc,cur)=>Math.max(acc,cur), 0));
dactyl.utils.message(
filtered.map(
m=>`${S.padEnd(m.name, maxlen)}\t${S.padEnd(m.description+':', maxlendesc)}\t${m.action}\n`
).join('')
);
return filtered;
}
function searchMappingsDescriptions(...pats) {
var activegroups = contexts.activeGroups();
var activemappings = activegroups.flatMap(
g => Array.from(g.mappings.iterate([modes.NORMAL])).concat(
Array.from(g.mappings.iterate([modes.INSERT]))).concat(
Array.from(g.mappings.iterate([modes.BASE])))
);
var filtered = activemappings.filter(
m => pats.every(
p => {
if (typeof p == "string" && p.toLowerCase()==p) {
return m.name.toLowerCase().search(p)>=0 ||
m.description.toLowerCase().search(p)>=0
} else {
return m.name.search(p)>=0 ||
m.description.search(p)>=0
}
}) );
var maxlen = filtered.map(m=>m.name.length).reduce((acc,cur)=>Math.max(acc,cur), 0);
var maxlendesc = Math.min(
50,
filtered.map(m=>m.description.length).reduce((acc,cur)=>Math.max(acc,cur), 0));
dactyl.utils.message(
filtered.map(
m=>`${S.padEnd(m.name, maxlen)}\t${S.padEnd(m.description+':', maxlendesc)}\t${m.action}\n`
).join('')
);
return filtered;
}
function searchMappingsByMode(mode, ...pats) {
var activegroups = contexts.activeGroups();
var modeInstance = modes[mode.toUpperCase()];
var activemappings = activegroups.flatMap(
g => Array.from(g.mappings.iterate([modeInstance])));
var filtered = activemappings.filter(
m => pats.every(
p => {
if (typeof p == "string" && p.toLowerCase()==p) {
return m.name.toLowerCase().search(p)>=0 ||
m.description.toLowerCase().search(p)>=0 ||
m.action.toString().toLowerCase().search(p)>=0
} else {
return m.name.search(p)>=0 ||
m.description.search(p)>=0 ||
m.action.toString().search(p)>=0
}
}) );
var maxlen = filtered.map(m=>m.name.length).reduce((acc,cur)=>Math.max(acc,cur), 0);
var maxlendesc = Math.min(
50,
filtered.map(m=>m.description.length).reduce((acc,cur)=>Math.max(acc,cur), 0));
dactyl.utils.message(
filtered.map(
m=>`${S.padEnd(m.name, maxlen)}\t${S.padEnd(m.description+':', maxlendesc)}\t${m.action}\n`
).join('')
);
return filtered;
}
function searchCommands1(pats, brief=true, searchAction=true) {
var activegroups = contexts.activeGroups();
var activecommands = Array.from(activegroups.flatMap(g => Array.from(g.commands)));
var filtered = activecommands.filter(
m => pats.every(
p => {
if (typeof p == "string" && p.toLowerCase()==p) {
return m.name.toLowerCase().search(p)>=0 ||
m.unlocalized_description.toLowerCase().search(p)>=0 ||
(searchAction && m.action.toString().toLowerCase().search(p)>=0)
} else {
return m.name.search(p)>=0 ||
m.unlocalized_description.search(p)>=0 ||
(searchAction && m.action.toString().search(p)>=0)
}
}) );
var maxlen = filtered.map(m=>m.name.length).reduce((acc,cur)=>Math.max(acc,cur), 0);
var maxlendesc = Math.min(
50,
filtered.map(m=>m.description.length).reduce((acc,cur)=>Math.max(acc,cur), 0));
dactyl.utils.message(
filtered.map(
m=>`${S.padEnd(m.name, maxlen)}\t${S.padEnd(m.description+':', maxlendesc)}\t${brief ? S.firstLineEllipsis(m.action) : m.action}\n`
).join('')
);
return filtered;
}
function searchCommands(...pats) { searchCommands1(pats, false); }
function searchCommandsBrief(...pats) { searchCommands1(pats, true); }
function allCommands() { return commands.hives.flatMap(h=>h._list); }
function getCommand(name) { return allCommands().find(cmd=>cmd.name==name); }
function getGroups() { return contexts.activeGroups().map(g=>g.name); }
function getAllCommands() { return commands.hives.flatMap(); }
function getCommandsByGroup(g) { return commands.hives.find(h=>h.name==g); }
function getMappingsByGroup(g) {
return Array.from(mappings.hives).find(h=>h.name==g).iterate(modes.NORMAL);
}
function listCommandsByGroup(g, brief=true) {
var cmds = Array.from(commands.hives.find(h=>h.name==g));
var maxlen = cmds.map(m=>m.name.length).reduce((acc,cur)=>Math.max(acc,cur), 0);
var maxlendesc = Math.min(
50,
cmds.map(m=>m.unlocalized_description.length).reduce((acc,cur)=>Math.max(acc,cur), 0));
dactyl.utils.message(
cmds.map(
m=>`${S.padEnd(m.name, maxlen)}\t${S.padEnd(m.unlocalized_description+':', maxlendesc)}\t${brief ? S.firstLineEllipsis(m.action) : m.action}\n`
).join('')
);
return cmds;
}
function listMappingsByGroup(g) {
var mpgs = Array.from(mappings.hives.find(h=>h.name==g).iterate(modes.NORMAL));
var maxlen = mpgs.map(m=>m.name.length).reduce((acc,cur)=>Math.max(acc,cur), 0);
var maxlendesc = Math.min(
50,
mpgs.map(m=>m.unlocalized_description.length).reduce((acc,cur)=>Math.max(acc,cur), 0));
dactyl.utils.message(
mpgs.map(
m=>`${S.padEnd(m.name, maxlen)}\t${S.padEnd(m.unlocalized_description+':', maxlendesc)}\t${m.action}\n`
).join('')
);
return mpgs;
}
function listCommandsByGroupCompletion(g) { return commands.hives.map(h=>[h.name, h]); }
function listMappingsByGroupCompletion(g) { return mappings.hives.map(h=>[h.name, h.name]); }
function getCurrentDomainGroups() { return contexts.activeGroups().filter(g=>g.filter!="*"); }
function getHintModes() {
var result = [];
for (k in hints.modes) result.push([k, hints.modes[k]]);
return result;
}
function getHintModeKeys() {
var result = [];
for (k in hints.modes) result.push(k);
return result;
}
function searchHintModes(...pats) {
var keys = getHintModeKeys();
var filtered = keys.filter(
k => pats.every(
p => {
if (typeof p == "string" && p.toLowerCase()==p) {
return k.search(p)>=0 || hints.modes[k][1].toLowerCase().search(p)>=0
} else {
return k.search(p)>=0 || hints.modes[k][1].search(p)>=0
}
}) );
dactyl.utils.message(filtered.map(k=>`${k}\t${hints.modes[k][1]}\n`).join(''));
return filtered;
}
function searchHintModesVerbose(...pats) {
var keys = getHintModeKeys();
var stringConvert = function(s) { return s ? String(s) : ""; }
var filtered = keys.filter(
k => pats.every(
p => {
if (typeof p == "string" && p.toLowerCase()==p) {
return k.search(p)>=0 ||
hints.modes[k][1].toLowerCase().search(p)>=0 ||
hints.modes[k][2].toString().toLowerCase().search(p)>=0 ||
stringConvert(hints.modes[k][3]).toLowerCase().search(p)>=0
} else {
return k.search(p)>=0 ||
hints.modes[k][1].search(p)>=0 ||
hints.modes[k][2].toString().search(p)>=0 ||
stringConvert(hints.modes[k][3]).search(p)>=0
}
}) );
var maxlendesc = Math.min(
50,
filtered.map(k=>hints.modes[k][1].length).reduce((acc,cur)=>Math.max(acc,cur), 0));
var maxlenact = Math.min(
50,
filtered.map(k=>hints.modes[k][2].length).reduce((acc,cur)=>Math.max(acc,cur), 0));
dactyl.utils.message(
filtered.map(
k=>`${k}\t${S.padEnd(hints.modes[k][1], maxlendesc)}\t${S.padEnd(hints.modes[k][2].toString()+':', maxlenact)}\t${stringConvert(hints.modes[k][3])}\n`
).join('')
);
return filtered;
}
function currentGroup(url=buffer.URL) {
var userGroups = GROUP.instance.children;
return userGroups.filter(g=>g.filter(url)).filter(g=>!["temp","user"].includes(g.name))[0];
}
EOF
" -----------------------------------------------------------------------------
" ,---------,
" | Options |
" '---------'
"
command! toggleoption
\ -description "Toggle boolean option."
\ -nargs=1
\ -complete option
\ -js utils.toggleOption(args[0]);
command! cycleoption
\ -description "Cycle option between several values"
\ -nargs=+
\ -complete option
\ -js utils.cycleOption(args[0], args.slice(1));
command! getoption
\ -description "Show boolean option."
\ -nargs=1
\ -complete option
\ -js var opt=options.get(args[0]); utils.message(`${opt.name}=${opt.value}`);
set runtimepath=~/.pentadactyl
set incfind
set hlfind
set findcase=smart
set showstatuslinks=status
"set wildmode=list:longest,list:full
set wildmode=list:full
set altwildmode=list:longest
set strictfocus=mail.google.com:laissez-faire,'chrome:*':laissez-faire,*:moderate
set scrolltime=0
set scrollsteps=1
set defsearch=g
set complete=search,bookmark,location,file
" nextpattern, previouspattern
" default: '^\s*Next Page\s*$','^\s*Next [>»]','\bnext\b',^>$,'^(>>|»)$','^(>|»)','(>|»)$','\bmore\b',
" default: '^\s*Prev(ious)? Page\s*$','[<«] Prev\s*$','\bprev(ious)?\b',^<$,'^(<<|«)$','^(<|«)',
set nextpattern="\\b[Ff]orward\\b","^\\b[Nn]ext\\b","(>>|»)$","(>|»|▸|►)$","\\b[Mm]ore\\b","\\b[Oo]lder\\b","次","下","后"
set previouspattern="\\b[Bb]ack\\b","\\b[Pp]rev(ious)?\\b","(<|«|◂|◄)$","\\b[Ll]ess\\b","\\b[Nn]ewer\\b","前","上"
set wildignore='~$','^(.*/)?\..*\.sw[m-p]$','^(.*/)?#.+#$'
" Ex commands output in a new tab by default (prefs, addons...)
set newtab=all
" make yanks go to clipboard
js editor.defaultRegister="+"
" If startup (default value of guioptions):"
:if options.get('guioptions').value.toString() == "b,C,r,s"
" add bookmark bar, tab numbers, right scrollbar & permanent separate cmdline "
set guioptions+=cBmNT
:endif
command! guioptionsreset set guioptions=bBcCrmNsT
command! togglecmdline -bang -js dactyl.execute("set guioptions!=c"); bang && dactyl.execute("rc");
js function cmdlineon() { return options.get("guioptions").value.includes("c") }
command! editorvim -description "Set terminal vim as editor"
\ set editor='roxterm --replace -e vim -f +<line> +"sil! call cursor(0, <column>)" +"set ft=markdown" <file>'
command! editorgvim -description "Set gVim as editor"
\ set editor='gvim -f +<line> +"sil! call cursor(0, <column>)" +"set ft=markdown" <file>'
command! editoremacs -description "Set emacs as editor" set editor='emacsclient'
command! editoremacsnewwin -description "Set emacs as editor (new window)" set editor='emacsclient -c'
command! editoremacsnw -description "Set terminal emacs as editor"
\ set editor='roxterm --replace -e emacsclient -tc +<line> <file>'
command! popupstoggle -description "Toggle whether popup windows appear in a new tab"
\ -js if (options.get('popups').value.includes("resized")) options.popups = ["tab"];
\ else options.popups = ["tab", "resized"];
\ utils.message("popups: "+options.popups);
" ,---------------------,
" | Pentadactyl Styling |
" '---------------------'
highlight CmdLine height: 15px
" =============================================================================
" ______________
" | |
" | KEY BINDINGS |
" |______________|
" -------------------------------------------------------------------------------
unmap!
" ,-------------,
" | Prefix Keys |
" '-------------'
command! emacssearchkey
\ -nargs=1
\ -complete custom,' (context) => {context.completions = listActiveGroupMappings()}'
\ -js showPentadactylrc(`map ${args[0]}`);
" Unmap prefix keys
map b <Nop>
" map S <Nop>
" map <C-x><C-h> <Nop>
" map <C-x> <Nop>
" Map concrete prefix keys to prefix pseudokeys
map a -description "Applications prefix" <app>
map b -description "Buffers/tabs prefix" <buffer>
map c -description "Sites/groups prefix" <site>
map e -description "Goto prefix" <goto>
map s -description "Search prefix" <search>
map v -description "Browser prefix" <browser>
map x -description "Extensions prefix" <ext>
map y -description "Yank prefix" <yank>
map , -description "Leader key prefix" <leader>
imap <A-return> <Esc><site>
cmap <A-y> <yank>
imap <A-y> <yank>
" List mappings by prefix (using commandline completion)
map <site> -description "(show bindings)" -js CommandExMode().open("showkeys <site>")
map <leader> -description "(show bindings)" -js CommandExMode().open("showkeys <leader>")
map <goto> -description "(show bindings)" -js CommandExMode().open("showkeys <goto>")
map <ext> -description "(show bindings)" -js CommandExMode().open("showkeys <ext>")
map <app> -description "(show bindings)" -js CommandExMode().open("showkeys <app>")
map <browser> -description "(show bindings)" -js CommandExMode().open("showkeys <browser>")
map <buffer> -description "(show bindings)" -js CommandExMode().open("showkeys <buffer>")
map <yank> -description "(show bindings)" -js CommandExMode().open("showkeys <yank>")
map <C-x> -description "(show bindings)" -js CommandExMode().open("showkeys <C-x>")
map g -description "(show bindings)" -js CommandExMode().open("showkeys g")
map <search> -description "(show bindings)" -js CommandExMode().open("showkeys <search>")
map z -description "(show bindings)" -js CommandExMode().open("showkeys z")
map <leader><f4> -description "(show bindings)" -js CommandExMode().open("emacssearchkey <leader>")
map <goto><f4> -description "(show bindings)" -js CommandExMode().open("emacssearchkey <goto>")
map <ext><f4> -description "(show bindings)" -js CommandExMode().open("emacssearchkey <ext>")
map <app><f4> -description "(show bindings)" -js CommandExMode().open("emacssearchkey <app>")
map <browser><f4> -description "(show bindings)" -js CommandExMode().open("emacssearchkey <browser>")
map <buffer><f4> -description "(show bindings)" -js CommandExMode().open("emacssearchkey <buffer>")
map <yank><f4> -description "(show bindings)" -js CommandExMode().open("emacssearchkey <yank>")
map <C-x><f4> -description "(show bindings)" -js CommandExMode().open("emacssearchkey <C-x>")
map g<f4> -description "(show bindings)" -js CommandExMode().open("emacssearchkey g")
map <search><f4> -description "(show bindings)" -js CommandExMode().open("emacssearchkey <search>")
map z<f4> -description "(show bindings)" -js CommandExMode().open("emacssearchkey z")
" -------------------------------------------------------------------------------
" ,----------------------------,
" | Help Commands and Bindings |
" '----------------------------'
map <C-h> -description "(show bindings: Help)" -js CommandExMode().open("showkeys <C-h>")
map <C-h>a -description "(show bindings: Help/Addons)" -js CommandExMode().open("showkeys <C-h>")
map <C-h>ag -description "Show Greasemonkey scripts" -ex addons -type greasemonkey-user-script
map <C-h>al -description "Show locale" -b :addons -type locale<Space>
map <C-h>ap -description "Show plugin" -ex addons -type plugin
map <C-h>as -description "Show userstyle" -ex addons -type userstyle
map <C-h>at -description "Show theme" -ex addons -type theme
map <C-h>b -description "Search bindings" -b :searchmappings<Space>
map <C-h>B -description "Search bindings description" -b :searchmappingsdescriptions<Space>
map <C-h>c -description "Search commands" -b :searchcommands<Space>
map <C-h>C -description "Search commands description" -js CommandExMode().open("searchcommandsdescriptions" + (count?"! ":" "));
map <C-h>d -description "Pentadactyl help" -ex help
map <C-h>D -description "Pentadactyl help - single page" -ex helpall
map <C-h>e -description "Show extensions" -b :addons -type extension<Space>
map <C-h>g -description "(show bindings: Help/By Group)" -js CommandExMode().open("showkeys <C-h>g")
map <C-h>gc -description "List commands by group" -b :listcommandsbygroup<Space>
map <C-h>gC -description "List commands by group (verbose)" -b :listcommandsbygroup!<Space>
map <C-h>gm -description "List bindings by group" -b :listmappingsbygroup<Space>
map <C-h>h -description "Open Help topic" :help<Space>
map <C-h>i -description "Pentadactyl help - index" -js openOrSelectTab("dactyl://help/index", count?"here":"adjacent");
map <C-h>k -description "Search browser keybindings" -b :searchbrowserkeybindings<Space>
map <C-h>K -description "Search browser keybindings by name" -b :searchbrowserkeybindingsbyname<Space>
map <C-h>m -description "Search bindings by mode" -b :searchmappingsbymode<Space>
map <C-h>r -description "Jump to .pentadactylrc entry" -b :rce<Space>
map <C-h>x -description "Execute key bindings matching prefix" :showkeys<Space>
map <C-h>: -description "Pentadactyl :help..." -b :help<Space>
map <C-h>; -description "(show bindings: Help/Ext Hint Modes)" -js CommandExMode().open("showkeys <C-h>;")
map <C-h>;; -description "Search hint modes/descriptions" -b :searchhintmodes<Space>
map <C-h>;a -description "Search hint modes/descriptions/actions/filters" -b :searchhintmodesverbose<Space>
map <C-h>;k -description "Show hint mode keys" -js utils.cbWrite(Object.keys(hints.modes).sort().join(""));
command! showkeys
\ -nargs=?
\ -complete custom,' (context) => {context.completions = listActiveGroupMappings()}'
\ :feedkeys -mode normal <args>
command! searchmappings -nargs * -js searchMappings.apply(null, args.map(readStringOrRegex));
command! searchmappingsdescriptions -nargs * -js searchMappingsDescriptions.apply(null, args.map(readStringOrRegex));
command! searchmappingsbymode -nargs * -js searchMappingsByMode.apply(null, args.map(readStringOrRegex));
command! searchcommands -description "Show commands matching pattern(s). With ! verbose definitions"
\ -bang
\ -nargs *
\ -js bang ? searchCommands.apply(null, args.map(readStringOrRegex)) : searchCommandsBrief.apply(null, args.map(readStringOrRegex));
command! searchcommandsdescriptions -description "Show commands whose name or description matches pattern(s). With ! verbose definitions"
\ -bang
\ -nargs *
\ -js searchCommands1(args.map(readStringOrRegex), !bang, true);
command! listcommandsbygroup -nargs 1
\ -bang
\ -complete custom," (context) => { context.completions = listCommandsByGroupCompletion(); } "
\ -js bang ? listCommandsByGroup(args[0], false) : listCommandsByGroup(args[0]);;
command! listmappingsbygroup -nargs 1
\ -complete custom," (context) => { context.completions = listMappingsByGroupCompletion(); } "
\ -js listMappingsByGroup(args[0]);
command! searchhintmodes -description "Search hint modes and descriptions"
\ -nargs * -js searchHintModes.apply(null, args.map(readStringOrRegex));
command! searchhintmodesverbose -description "Search hint modes and descriptions, actions and filters"
\ -nargs * -js searchHintModesVerbose.apply(null, args.map(readStringOrRegex));
command! searchbrowserkeybindings -nargs 1 -js utils.cbWriteCollection(searchBrowserKeybindings(readStringOrRegex(args[0])));
command! searchbrowserkeybindingsbyname -nargs 1 -js utils.cbWriteCollection(searchBrowserKeybindingsByName(readStringOrRegex(args[0])));
js <<EOF
function getBrowserKeybindings() {
return $$("key", document).map(e=>{
var id = e.id;
var key = e.getAttribute("key") || e.getAttribute("keycode");
var [modifiers, command, oncommand] = ["modifiers", "command", "oncommand"].map(att=>e.getAttribute(att));
var modArray = modifiers ? modifiers.split(",") : [];
var keystr = modArray.map(k=>{
switch(k) {
case "accel":
case "control": return "C";
case "shift": return "S";
case "alt": return "A";
}
}).concat([key]).join("-");
var name = id || command || oncommand;
return {
"name": name,
"keystr": keystr,
toString: function () { return `${this.keystr}: \t${this.name}`; }
};
});
}
function searchBrowserKeybindings(pat) {
if (typeof pat == "function")
var f = pat;
else if (typeof pat == "string" && pat == pat.toLowerCase())
var f = k=>k.keystr.toLowerCase().match(pat);
else
var f = k=>k.keystr.match(pat);
return getBrowserKeybindings().filter(f);
}
function searchBrowserKeybindingsByName(pat) {
if (typeof pat == "string" && pat == pat.toLowerCase())
var f = k=>k.name.toLowerCase().match(pat);
else
var f = k=>k.name.match(pat);
return getBrowserKeybindings().filter(f);
}
EOF
" -------------------------------------------------------------------------------
" ,------------------,
" | Other Pseudokeys |
" '------------------'
map <link_desc> ;Y