Last active
October 4, 2025 23:46
-
-
Save tukkek/afb4f5949fec00c3527fa0ab32a7aba2 to your computer and use it in GitHub Desktop.
Selection-enhancer user-script
This file contains hidden or 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 Selection enhancer. | |
| // @namespace http://tampermonkey.net/ | |
| // @version 1.2 | |
| // @description Control-click selects and extends-selection. | |
| // @author tukkek | |
| // @match *://*/* | |
| // @grant none | |
| // ==/UserScript== | |
| function expand(c){return c&&!/\s/.test(c)} | |
| function select(x,y){ | |
| let position=document.caretPositionFromPoint(x,y) | |
| if(!position) return false | |
| let range=document.createRange() | |
| range.setStart(position.offsetNode,position.offset) | |
| range.collapse(true) | |
| let node=range.startContainer | |
| if(!range||!node||node.nodeType!=Node.TEXT_NODE) return false | |
| let offset=range.startOffset | |
| let text=node.textContent | |
| if(!text) return false | |
| let start=offset | |
| while(start>0&&expand(text[start-1])) start-=1 | |
| let end=offset | |
| while(end<text.length&&expand(text[end])) end+=1 | |
| if(start==end) return false | |
| range.setStart(node,start) | |
| range.setEnd(node,end) | |
| return range | |
| } | |
| function click(event){ | |
| if(!event.ctrlKey) return | |
| if(event.target.tagName=='A') return | |
| let range=select(event.clientX,event.clientY) | |
| if(!range) return | |
| let selection=window.getSelection() | |
| for(let i=0;i<selection.rangeCount;i+=1){ | |
| let previous=selection.getRangeAt(i) | |
| if(!previous.toString().length) continue | |
| let start=previous.compareBoundaryPoints(Range.START_TO_START,range) | |
| if(start<0) range.setStart(previous.startContainer,previous.startOffset) | |
| let end=previous.compareBoundaryPoints(Range.END_TO_END,range) | |
| if(end>0) range.setEnd(previous.endContainer,previous.endOffset) | |
| } | |
| selection.empty() | |
| selection.addRange(range) | |
| } | |
| function press(event){if(event.key=='Escape') document.getSelection().empty()} | |
| document.addEventListener('click',(event)=>click(event)) | |
| document.addEventListener('keyup',(event)=>press(event)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment