Last active
August 15, 2021 18:57
-
-
Save kapilreddy/03465d8f479c1880cb808c1dcc4dc59f to your computer and use it in GitHub Desktop.
Emulate Emacs text editing in browser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
(function () { | |
'use strict'; | |
let nowPlayingClassName = 'now-playing-tracklist-row' | |
let buffer = []; | |
let bindings = [ | |
{binding: ["control", "f"], action: moveForward}, | |
{binding: ["control", "b"], action: moveForward} | |
]; | |
function moveCaret(win, charCount) { | |
var sel, range; | |
if (win.getSelection) { | |
sel = win.getSelection(); | |
if (sel.rangeCount > 0) { | |
var textNode = sel.focusNode; | |
var newOffset = sel.focusOffset + charCount; | |
sel.collapse(textNode, Math.min(textNode.length, newOffset)); | |
} | |
} else if ( (sel = win.document.selection) ) { | |
if (sel.type != "Control") { | |
range = sel.createRange(); | |
range.move("character", charCount); | |
range.select(); | |
} | |
} | |
} | |
function moveForward () { | |
moveCaret(window, 1); | |
} | |
function moveBackward () { | |
moveCaret(window, -1); | |
} | |
Array.prototype.last = function () { | |
return this[this.length - 1]; | |
} | |
function arraysMatch(arr1, arr2) { | |
if (arr1.length !== arr2.length) { | |
return false; | |
} | |
for (let i = 0; i < arr1.length; i++) { | |
if (arr1[i] !== arr2[i]) return false; | |
} | |
return true; | |
} | |
// register handling for keybindings | |
document.getElementById("editable").addEventListener('keydown', event => { | |
let key = event.key.toLowerCase(); | |
if (key == 'control') { | |
buffer = []; | |
} | |
console.log(key); | |
if (buffer.last() != key) { | |
buffer.push(key); | |
} | |
bindings.filter(function (item) { | |
if (arraysMatch(item.binding, buffer)) { | |
item.action(); | |
} | |
}); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment