Surrounded

Surrounds selected text on web pages with pairs of characters when typed, keeps selection unchanged.

当前为 2018-12-31 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         Surrounded
// @namespace    cpriest
// @version      0.1
// @description  Surrounds selected text on web pages with pairs of characters when typed, keeps selection unchanged.
// @author       Clint Priest
// @include     *
// @grant        none
// ==/UserScript==

(function() {
	'use strict';

	const CTRL  = 1,
		  ALT   = 2,
		  SHIFT = 4;

	const ActiveKeys = [`'`, `"`, '{', '}', '[', ']', '`', '*', '_', '<', '>', ];

	/**
	 * Returns true if we work with the passed in elem
	 *
	 * @param {Element} elem
	 *
	 * @returns boolean
	 */
	function WeWorkWithThisElement(elem) {
		if(elem.tagName == 'TEXTAREA')
			return true;

		if(elem.tagName == 'INPUT') {
			if('selectionStart' in elem || 'selectionEnd' in elem)
				return true;
		}
		return false;
	}

	function note(...args) {
		console.log(...args);
	}

	/**
	 * Surrounds the given elements selection with the character set
	 *
	 * @param {HTMLInputElement|HTMLTextAreaElement} elem
	 * @param key
	 */
	function Surround(elem, key) {
		let { selectionStart, selectionEnd, selectionDirection } = elem;

		let leftKey = key + '',
			rightKey = key + '',
			leftValue = elem.value.substring(0, elem.selectionStart),
			value = elem.value.substring(elem.selectionStart, elem.selectionEnd),
			rightValue = elem.value.substring(elem.selectionEnd);

		switch(leftKey) {
			case '{':
				rightKey = '}';
				break;
			case '}':
				rightKey = '{';
				[leftKey, rightKey] = [rightKey, leftKey];
				break;
			case '[':
				rightKey = ']';
				break;
			case ']':
				rightKey = '[';
				[leftKey,rightKey] = [rightKey, leftKey];
				break;
			case '<':
				rightKey = '>';
				break;
			case '>':
				rightKey = '<';
				[leftKey, rightKey] = [rightKey, leftKey];
				break;
		}

		// Remove Mode
		if(leftValue.substr(-1) === leftKey && rightValue.substr(0, 1) === rightKey) {
			leftValue = leftValue.substr(0, leftValue.length-1);
			rightValue = rightValue.substr(1);
			leftKey = rightKey = '';
			selectionStart--;
			selectionEnd--;
		} else {
			// Add Mode
			selectionStart++;
			selectionEnd++;
		}

		elem.value = `${leftValue}${leftKey}${value}${rightKey}${rightValue}`;
		elem.selectionStart = selectionStart;
		elem.selectionEnd = selectionEnd;
	}

	window.document.addEventListener('keydown',
		/** @param {KeyboardEvent} e */e => {
			e.mods = (e.ctrlKey) + (e.altKey << 1) + (e.shiftKey << 2);

			if(e.mods > 0 && e.mods !== 4)
				return; // note(`${e.key}: CTRL/ALT active e.mods=${e.mods}`);

			if(ActiveKeys.indexOf(e.key) == -1)
				return; // note(`${e.key}: not a key we care about`);

			if(!document.activeElement)
				return; // note(`${e.key}: no valid activeElement: %o`, document.activeElement);

			let ae = document.activeElement;
			if(!WeWorkWithThisElement(ae))
				return; // note(`${e.key}: We don't work with: %o`, ae);

			if(ae.selectionStart === ae.selectionEnd)
				return; // note(`${e.key}: No characters are selected, start=${ae.selectionStart}, end=${ae.selectionEnd}` );

			Surround(ae, e.key);

			e.preventDefault();
			e.stopPropagation();

		}, true);
})();