Format terminal commands on copy

Automatically remove bash comments `#` and prompts `$` on copy by reading the modifying the selected content.

  1. // This program is free software: you can redistribute it and/or modify
  2. // it under the terms of the GNU General Public License as published by
  3. // the Free Software Foundation, either version 3 of the License, or
  4. // (at your option) any later version.
  5. //
  6. // This program is distributed in the hope that it will be useful,
  7. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. // GNU General Public License for more details.
  10. //
  11. // You should have received a copy of the GNU General Public License
  12. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. //
  14.  
  15. // ==UserScript==
  16. // @namespace https://gitlab.com/kekumu
  17. // @name Format terminal commands on copy
  18. // @description Automatically remove bash comments `#` and prompts `$` on copy by reading the modifying the selected content.
  19. // @version 1.0.1
  20. // ==OpenUserJS==
  21. // @author kekumu; https://gitlab.com/kekumu
  22. // ==/OpenUserJS==
  23. // @copyright 2020, kekumu (https://github.com/kekumu)
  24. // @license GPL-3.0-or-later; https://www.gnu.org/licenses/gpl-3.0.html
  25. // @homepage https://github.com/kekumu/userscripts/lib/click2select.js
  26. // @supportURL https://github.com/kekumu/userscripts/labels/click2select.js
  27. // ==/UserLibrary==
  28. // @include *
  29. // @grant none
  30. // ==/UserScript==
  31.  
  32. (() => {
  33. "use strict";
  34.  
  35. function copyHandler(event) {
  36. const selection = document.getSelection();
  37.  
  38. let lines = selection.toString().split('\n').reduce((res, line) => {
  39. if (line[0] !== '#') { // Remove lines that start with '#' (comments)
  40. res.push(line.replace(/^\$ /, '')); // Remove '$ ' prompt
  41. }
  42. return res;
  43. }, []);
  44.  
  45. event.clipboardData.setData('text/plain', lines.join('\n'));
  46. event.preventDefault();
  47. }
  48.  
  49. document.addEventListener('copy', copyHandler);
  50. })();