§ Код

Нет времени объяснять, просто внизу код.
tab(selector, event, spaces = 4)
{
    let that = document.querySelector(selector);
    let v = that.value, s = that.selectionStart, e = that.selectionEnd;

    // Список всех строк до текущего момента, извлечь последнюю строку
    let a = v.substring(0, s).split("\n");
    let u = spaces - (a[a.length - 1].length % spaces);

    // Симуляция пробельной табуляции
    that.value = v.substring(0, s) + (' '.repeat(u)) + v.substring(e);
    that.selectionStart = that.selectionEnd = s + u;

    event.preventDefault();
    event.stopPropagation();
}