UserScript to input Soft tab instead of Hard tab.
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== | |
// @name softtab.user.js | |
// @namespace https://gist.github.com/kawanamiyuu/ | |
// @updateURL https://gist.github.com/kawanamiyuu/db042e2910ab05c105faf5b3ead211ae | |
// @version 1.3 | |
// @description UserScript to input Soft tab instead of Hard tab. | |
// @include * | |
// @exclude https://github.com/*/*/projects* | |
// @require https://code.jquery.com/jquery-3.3.1.min.js | |
// ==/UserScript== | |
(function ($) { | |
const TAB = ' '; | |
const INDENT = 4; | |
// https://qiita.com/laineus/items/12a220d2ab086931232d | |
$(document).on('keydown', 'textarea', function(e) { | |
if (e.keyCode !== 9) { | |
return; | |
} | |
e.preventDefault(); | |
var isShift = e.shiftKey; // Shift押されているか | |
var elm = e.target; | |
var txt = elm.value; | |
var slct = { left: elm.selectionStart, right: elm.selectionEnd }; // テキスト選択の開始・終了位置 | |
if(slct.left === slct.right && !isShift) { | |
// テキスト選択されていない場合はカーソル位置にタブ挿入 | |
// elm.value = txt.substr(0, slct.left) + '\t' + txt.substr(slct.left, txt.length); | |
elm.value = txt.substr(0, slct.left) + TAB + txt.substr(slct.left, txt.length); | |
// タブが挿入された分テキスト選択の位置がズレるので調整 | |
//slct.left++; | |
//slct.right++; | |
slct.left = slct.left + INDENT; | |
slct.right = slct.right + INDENT; | |
} else { | |
// テキスト選択されている場合行頭にタブ追加・Shiftも押してたら行頭のタブを削除 | |
var lineStart = txt.substr(0, slct.left).split('\n').length - 1; // 開始行 | |
var lineEnd = txt.substr(0, slct.right).split('\n').length - 1; // 終了行 | |
var lines = txt.split('\n'); // テキストを行ごとの配列に変換 | |
for(let i = lineStart; i <= lineEnd; i++) { | |
// 一行ごとの処理 | |
if(!isShift) { | |
// 行頭にタブ挿入 | |
// lines[i] = '\t' + lines[i]; | |
lines[i] = TAB + lines[i]; | |
// タブが挿入された分テキスト選択の位置がズレるのでry | |
//if(i == lineStart) slct.left++; | |
if(i == lineStart) slct.left = slct.left + INDENT; | |
//slct.right++; | |
slct.right = slct.right + INDENT; | |
// } else if(lines[i].substr(0, 1) == '\t') { | |
} else if(lines[i].substr(0, INDENT) == TAB) { | |
// 行頭にタブがあるときだけ削除 | |
// lines[i] = lines[i].substr(1); | |
lines[i] = lines[i].substr(INDENT); | |
// タブが挿入された分ry | |
//if(i == lineStart) slct.left--; | |
if(i == lineStart) slct.left = slct.left - INDENT; | |
//slct.right--; | |
slct.right = slct.right - INDENT; | |
} | |
} | |
// 変換後の配列を文字列に戻してtextareaへ | |
elm.value = lines.join('\n'); | |
} | |
// テキスト選択の位置を更新 | |
elm.setSelectionRange(slct.left, slct.right); | |
return false; | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment