双击选中文本时自动去除末尾空格

双击选中文本时,自动去除末尾的空格,使选区更精准。

Ekde 2025/06/28. Vidu La ĝisdata versio.

// ==UserScript==
// @name         双击选中文本时自动去除末尾空格
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  双击选中文本时,自动去除末尾的空格,使选区更精准。
// @author       Devol
// @match        *://*/*
// @grant        none
// ==/UserScript==

/**
 * 优化双击选中的文本范围,自动排除单词后的空格
 * @param {Event} event - 双击事件对象(未直接使用,但保留以备扩展)@license
 */
function handleDoubleClickSelection(event) {
  const selection = window.getSelection();

  // 安全检查:无选中内容或选区不连续时退出
  if (selection.rangeCount === 0 || selection.rangeCount > 1) {
    return;
  }

  const range = selection.getRangeAt(0);
  const selectedText = range.toString();

  // 支持中文、字母、数字及常见标点(可根据需要调整正则)
  const matches = selectedText.match(/^[\w\u4e00-\u9fa5,。!?、;:""'']+(\s+)$/);
  if (!matches || !matches[1]) {
    return;
  }

  // 计算需要排除的空格长度
  const trailingSpaceCount = matches[1].length;

  // 创建新选区(不修改原始 range 对象)
  const newRange = range.cloneRange();
  newRange.setEnd(range.endContainer, range.endOffset - trailingSpaceCount);

  // 应用优化后的选区
  selection.removeAllRanges();
  selection.addRange(newRange);
}

// 添加事件监听(使用 passive 模式提升滚动性能)
document.addEventListener('dblclick', handleDoubleClickSelection, {
  passive: true,
  capture: false
})();