EcuaMobi / Quote plus

// ==UserScript==
// @name        Quote plus
// @namespace   ecuamobi
// @author      EcuaMobi
// @include     https://bitcointalk.org/index.php?action=post;*quote=*
// @include     https://bitcointalk.org/index.php?action=pm;sa=send;f=inbox;pmsg=*;quote;u=*
// @version     1.1.1
// @license   MIT
// @grant none
// ==/UserScript==

(() => {
  var full_text = document.forms.postmodify.message.value;
  var regex = /\[quote author/gi,
    result, indices = [];
  // Find second [quote]
  var i = 0;
  var start2 = 0;
  var end2 = 0;
  while ((result = regex.exec(full_text))) {
    i++;
    if (2 == i) {
      start2 = result.index;
      break;
    }
  }
  regex = /\[\/quote\]/gi, result, indices = [];
  var last = 0;
  while ((result = regex.exec(full_text))) {
    if (last > 0) {
      end2 = last + 8;
    }
    last = result.index;
  }

  // Are there several quotes?
  if (start2 == 0 || end2 == 0) {
    // Abort
    return;
  }

  // Get text to use for every option
  var latest_quote = full_text.substr(0, start2).trim() + '\n' + full_text.substr(end2).trim() + '\n';
  var snip_quote = full_text.substr(0, start2).trim() + '~snip~[/quote]\n';
  full_text = full_text.trim() + '\n';

  // By default use the latest quote. REPLACE THIS BY snip_quote OR REMOVE IF DESIRED
  document.forms.postmodify.message.value = latest_quote;

  // Add buttons to manually use full text, latest quote or snip
  const $links = "<span style='margin-left:38%'><a id='full_text' href='#'>Full text</a> | <a id='latest_quote' href='#'>Latest quote</a> | <a id='snip_quote' href='#'>~snip~</a></span>"
  document.querySelector("textarea").insertAdjacentHTML('afterend', $links);

  document.querySelector('#full_text').addEventListener('click', function(e){
    e.preventDefault();
    document.forms.postmodify.message.value = full_text;
  });
  document.querySelector('#latest_quote').addEventListener('click', function(e){
    e.preventDefault();
    document.forms.postmodify.message.value = latest_quote;
  });
  document.querySelector('#snip_quote').addEventListener('click', function(e){
    e.preventDefault();
    document.forms.postmodify.message.value = snip_quote;
  });
})();