Last active
January 18, 2025 11:47
-
-
Save Jezda1337/6b7046ccbaa62518c7f48e8dc6b7f338 to your computer and use it in GitHub Desktop.
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 Format comments code for github.com | |
| // @namespace Violentmonkey Scripts | |
| // @match https://github.com/* | |
| // @grant none | |
| // @version 1.0 | |
| // @author - | |
| // @description 11/10/2024, 3:14:13 PM | |
| // ==/UserScript== | |
| // Create a button element | |
| // Function to fix code indentation | |
| function fixIndentation(code) { | |
| // Split the code into lines | |
| const lines = code.split('\n'); | |
| // Find the minimum indentation level (excluding empty lines) | |
| const minIndent = lines | |
| .filter(line => line.trim().length > 0) | |
| .reduce((min, line) => { | |
| const indent = line.match(/^\s*/)[0].length; | |
| return indent < min ? indent : min; | |
| }, Infinity); | |
| // Remove the minimum indentation from all lines | |
| const fixedLines = lines.map(line => { | |
| if (line.trim().length === 0) return ''; | |
| return line.slice(minIndent); | |
| }); | |
| // Join the lines back together | |
| return fixedLines.join('\n'); | |
| } | |
| // Function to handle the paste event | |
| async function handlePaste(e) { | |
| // Prevent the default paste | |
| e.preventDefault(); | |
| try { | |
| // Get the clipboard content | |
| const text = await navigator.clipboard.readText(); | |
| // Fix the indentation | |
| const fixedText = fixIndentation(text); | |
| // Get the target element | |
| const target = e.target; | |
| // Get the current cursor position | |
| const startPos = target.selectionStart; | |
| const endPos = target.selectionEnd; | |
| // Get the current value | |
| const currentValue = target.value; | |
| // Create the new value by combining the parts | |
| const newValue = | |
| currentValue.substring(0, startPos) + | |
| fixedText + | |
| currentValue.substring(endPos); | |
| // Set the new value | |
| target.value = newValue; | |
| // Set the cursor position after the pasted text | |
| target.selectionStart = target.selectionEnd = startPos + fixedText.length; | |
| } catch (error) { | |
| console.error('Failed to access clipboard:', error); | |
| } | |
| } | |
| // Add the paste event listener | |
| document.addEventListener("paste", handlePaste); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment