User:Alex brollo bis/PersonalButtons.js

From Wikisource
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
(function (mw, $) {
/* start of PersonalButtonsDeps routines, they could be converted into a ResourceLoader module
   but an interface sysop flag would be needed*/
mw.alex = mw.alex || {};
	if (mw.alex.activeElement===undefined) {
			mw.alex.activeElement=$("#wpTextbox1")[0];
			$("textarea, input[type='text'][name!='wpAntispam']").focusin(function () {
			mw.alex.activeElement=this;
		});
	}
    /** from: 
   * http://www.openjs.com/scripts/events/keyboard_shortcuts/
   * Version : 2.01.B
   * By Binny V A
   * License : BSD
   */
    if (mw.alex.shortcut===undefined) {
    mw.alex.shortcut = {
   
      'all_shortcuts': {}, // All the shortcuts are stored in this array
      'add': function (shortcutCombination, callback, opt) {
        if (mw.alex.shortcut.all_shortcuts[shortcutCombination.toLowerCase()] !== undefined) {
          console.log(shortcutCombination.toLowerCase() + ' già registrata');
          return false;
        }

        // Provide a set of default options
        var defaultOptions = {
          'type': 'keydown',
          'propagate': false,
          'disable_in_input': false,
          'target': document,
          'keycode': false
        };
        if (!opt) opt = defaultOptions;
        else {
          for (var dfo in defaultOptions) {
            if (typeof opt[dfo] === 'undefined') opt[dfo] = defaultOptions[dfo];
          }
        }

        var ele = opt.target
        if (typeof opt.target === 'string') ele = document.getElementById(opt.target)
        // var ths = this
        shortcutCombination = shortcutCombination.toLowerCase()

        // The function to be called at keypress
        var func = function (e) {
          let code = ''
          e = e || window.event

          if (opt.disable_in_input) { // Don't enable shortcut keys in Input, Textarea fields
            var element
            if (e.target) element = e.target
            else if (e.srcElement) element = e.srcElement
            if (element.nodeType === 3) element = element.parentNode

            if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') return
          }

          // Find Which key is pressed
          if (e.keyCode) code = e.keyCode
          else if (e.which) code = e.which
          var character = String.fromCharCode(code).toLowerCase()

          if (code === 188) character = ',' // If the user presses , when the type is onkeydown
          if (code === 190) character = '.' // If the user presses , when the type is onkeydown

          var keys = shortcutCombination.split('+')
          // Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
          var kp = 0

          // Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
          var shiftNums = {
            '`': '~',
            '1': '!',
            '2': '@',
            '3': '#',
            '4': '$',
            '5': '%',
            '6': '^',
            '7': '&',
            '8': '*',
            '9': '(',
            '0': ')',
            '-': '_',
            '=': '+',
            ';': ':',
            "'": '"',
            ',': '<',
            '.': '>',
            '/': '?',
            '\\': '|'
          }
          // Special Keys - and their codes
          var specialKeys = {
            'esc': 27,
            'escape': 27,
            'tab': 9,
            'space': 32,
            'return': 13,
            'enter': 13,
            'backspace': 8,

            'scrolllock': 145,
            'scroll_lock': 145,
            'scroll': 145,
            'capslock': 20,
            'caps_lock': 20,
            'caps': 20,
            'numlock': 144,
            'num_lock': 144,
            'num': 144,

            'pause': 19,
            'break': 19,

            'insert': 45,
            'home': 36,
            'delete': 46,
            'end': 35,

            'pageup': 33,
            'page_up': 33,
            'pu': 33,

            'pagedown': 34,
            'page_down': 34,
            'pd': 34,

            'left': 37,
            'up': 38,
            'right': 39,
            'down': 40,

            'f1': 112,
            'f2': 113,
            'f3': 114,
            'f4': 115,
            'f5': 116,
            'f6': 117,
            'f7': 118,
            'f8': 119,
            'f9': 120,
            'f10': 121,
            'f11': 122,
            'f12': 123
          }

          var modifiers = {
            shift: { wanted: false, pressed: false},
            ctrl: { wanted: false, pressed: false},
            alt: { wanted: false, pressed: false},
            meta: { wanted: false, pressed: false} // Meta is Mac specific
          }

          if (e.ctrlKey) modifiers.ctrl.pressed = true
          if (e.shiftKey) modifiers.shift.pressed = true
          if (e.altKey) modifiers.alt.pressed = true
          if (e.metaKey) modifiers.meta.pressed = true
          let k = ''
          let i = 0
          for (i = 0; k = keys[i], i < keys.length; i++) {
            // Modifiers
            if (k === 'ctrl' || k === 'control') {
              kp++
              modifiers.ctrl.wanted = true
            } else if (k === 'shift') {
              kp++
              modifiers.shift.wanted = true
            } else if (k === 'alt') {
              kp++
              modifiers.alt.wanted = true
            } else if (k === 'meta') {
              kp++
              modifiers.meta.wanted = true
            } else if (k.length > 1) { // If it is a special key
              if (specialKeys[k] === code) kp++
            } else if (opt.keycode) {
              if (opt.keycode === code) kp++
            } else { // The special keys did not match
              if (character === k) kp++
              else {
                if (shiftNums[character] && e.shiftKey) { // Stupid Shift key bug created by using lowercase
                  character = shiftNums[character]
                  if (character === k) kp++
                }
              }
            }
          }

          if (kp === keys.length &&
              modifiers.ctrl.pressed === modifiers.ctrl.wanted &&
              modifiers.shift.pressed === modifiers.shift.wanted &&
              modifiers.alt.pressed === modifiers.alt.wanted &&
              modifiers.meta.pressed === modifiers.meta.wanted) {
            callback(e)

            if (!opt['propagate']) { // Stop the event
              // e.cancelBubble is supported by IE - this will kill the bubbling process.
              e.cancelBubble = true
              e.returnValue = false

              // e.stopPropagation works in Firefox.
              if (e.stopPropagation) {
                e.stopPropagation()
                e.preventDefault()
              }
              return false
            }
          }
        }
        this.all_shortcuts[shortcutCombination] = {
          'callback': func,
          'target': ele,
          'event': opt['type']
        }
        // Attach the function with the event
        if (ele.addEventListener) ele.addEventListener(opt['type'], func, false)
        else if (ele.attachEvent) ele.attachEvent('on' + opt['type'], func)
        else ele['on' + opt['type']] = func
      },

      // Remove the shortcut - just specify the shortcut and I will remove the binding
      'remove': function (shortcutCombination) {
        shortcutCombination = shortcutCombination.toLowerCase()
        var binding = this.all_shortcuts[shortcutCombination]
        delete (this.all_shortcuts[shortcutCombination])
        if (!binding) return
        var type = binding['event']
        var ele = binding['target']
        var callback = binding['callback']

        if (ele.detachEvent) ele.detachEvent('on' + type, callback)
        else if (ele.removeEventListener) ele.removeEventListener(type, callback, false)
        else ele['on' + type] = false
      }
    }	
   }
	
	
	if (mw.alex.count===undefined) {
		/* conta il numero di occorrenze di stringa dentro testo; esce se testo === "" oppure stringa ==="" */

		mw.alex.count = function (testo, stringa) {
			var n = 0;
			if (testo !== "" && stringa !== "") {
				while (testo.indexOf(stringa) > -1) {
					n = n + 1;
					testo = testo.replace(stringa, "");
				}
			}
			return n;
		};
	}
	if (mw.alex.findStringa===undefined) {
		mw.alex.findStringa = function (testo, idi, idf, dc, x) {
			idip = testo.indexOf(idi);
			idfp = testo.indexOf(idf, idip + idi.length) + idf.length;
			if (idip > -1 && idfp > -1) {
				if (x !== "") {
					while (mw.alex.count(testo.slice(idip, idfp), x) > mw.alex.count(testo.slice(idip, idfp), idf)) {
						idfp = testo.indexOf(idf, idfp) + idf.length;
					}
				}
				if (dc === 0) {
					vvalore = testo.slice(idip + idi.length, idfp - idf.length);
				} else {
					vvalore = testo.slice(idip, idfp);
				}
			} else {
				vvalore = "";
			}
			return vvalore;
		};	
	}
	if (mw.alex.scriviBox===undefined) {
		mw.alex.scriviBox = function (testo, area, ss, se) {
			if (area === undefined || area === "") {
				if (mw.config.get('wgCanonicalNamespace') == "Page" || $("#editBox").length===1) {
					area = 1;
				} else {
					area = 0;
				}
			}
			$('textarea')[area].value = testo;
			// console.log("area:", area);
			if (ss !== undefined && se !== undefined) {
				$('textarea')[area].selectionStart = ss;
				$('textarea')[area].selectionEnd = se;
			}
		};
	}
	if (mw.alex.produciLista===undefined) {
		mw.alex.produciLista = function (testo, s1, s2, delim, x) {
			lista = [];
			while (mw.alex.findStringa(testo, s1, s2, true, x) > "") {
				elemento = mw.alex.findStringa(testo, s1, s2, true, x);
				testo = testo.replace(elemento, "");
				if (delim) {
					lista.push(elemento);
				} else {
					lista.push(elemento.slice(s1.length, - s2.length));
				}
			}
			return lista;
		};
	}
	/* ex ss() renamed */
	if (mw.alex.getSelection===undefined) {
		mw.alex.getSelection = function () {
		      var textarea = mw.alex.activeElement; // elemento dom wpTextbox1
		      var txt = $(textarea).val();
		      var s = [];
		      s[0] = txt.substring(0, textarea.selectionStart);
		      s[1] = txt.substring(textarea.selectionStart, textarea.selectionEnd);
		      s[2] = txt.substring(textarea.selectionEnd);
		      return s;
		};
	}
	/* ex sw() renamed */
	if (mw.alex.writeSelection===undefined) {
	    mw.alex.writeSelection = function (t) {
	      var textarea = mw.alex.activeElement; // elemento dom wpTextbox1=$("#wpTextbox1")[0]; // elemento dom wpTextbox1
	      textarea.value = t.join('');
	      textarea.selectionStart = t[0].length;
	      textarea.selectionEnd = t[0].length + t[1].length;
	      textarea.focus();
	    };
	}
	if (mw.alex.selection===undefined) {
		mw.alex.selection = function (area){

			var txt=mw.activeElement.value;
			var s=[];
			s[0]=txt.substring(0,mw.activeElement.selectionStart);
			s[1]=txt.substring(mw.activeElement.selectionStart,mw.activeElement.selectionEnd);
			s[2]=txt.substring(mw.activeElement.selectionEnd);
			return s;
		};
	
	}
	if (mw.alex.scriviSel===undefined) {
		mw.alex.scriviSel = function scriviSel(t) {
			mw.activeElement.value=t.join("");
			mw.activeElement.selectionStart=t[0].length;
			mw.activeElement.selectionEnd= t[0].length + t[1].length;
		    mw.activeElement.focus();
		};
	
	}

/* end of PersonalButtons routines*/
/* start of PersonalButtons routines*/
var alex = {}
 
  function main () {
    function creaBottoniera () {
      $('#' + (mw.user.options.get('skin') === 'modern' ? 'mw_' : '') + 'content')
        .append($('<div>').attr('id', 'newtattoo').attr('align', 'right').attr('style',
          'position:fixed;bottom:0; right:0; background-color:white; border: 1px solid; border-color:#F0F0F0; z-index:1500;'))
    }

    // Syncronous requests are deprecated but very comfortable; I LOVE them :-)
    function leggiPersonalButtons () { // chiamata sincrona da rivedere
      let testo = $.ajax({url: mw.config.get('wgServer') + '/w/index.php?action=raw&title=User:' + mw.config.get('wgUserName') + '/PersonalButtons', async: false})

      if (testo.responseText === '') {
        testo = '<pre>eiv,es,EditInView *Ctrl+Alt+e*,creaBox\n' +
    'diacritici, es, Mostra/nascondi diacritici *Alt+0*,diacriticiToggle\n' +
    'postOCR, es, esegue postOCR *Alt+7*,postOCR\n' +
    'parag,es,Separa i possibili paragrafi con una riga vuota *Alt+8*,aggiustaParagrafi\n' +
    'linee,es,Riunisce le linee di testo di u paragrafo *Alt+6*,unisciLinee\n' +
    "i, es, Applica markup corsivo *Ctrl+Alt+i*, incapsula,'',''\n" +
    'Sc, es,Applica il template SmallCaps (maiuscoletto), incapsula,{{Sc|,}}\n' +
    'c, es,Applica il template Center (centrato) *Ctrl+Alt+c*, incapsula,{{center|,}}\n' +
    "ci, es,Applica il template Center (centrato) + italico, incapsula,{{center|'',''}}\n" +
    'outd, es,Applica il template Outdent (indent inverso) *Ctrl+Alt+o*, incapsula,{{outdent|,}}\n' +
    'larger, es,Applica il template larger, incapsula,{{larger|,}}\n' +
    '----, es,Applica il template Rule (traccia una riga orixzzontale centrata), incapsula,{{Rule|4em}},\n' +
    'Mm, es,Applica maiuscolo/minuscolo alla selezione alternandole *Ctrl+Alt+m*, up_low\n' +
    'Rv,es,Elimina righe vuote,eliminaRigheVuote\n' +
    '→, es,Indenta le righe della selezione (utile per i versi nelle poesie) *Alt+Right*, indentSelection\n' +
    "←, es,Riduce l'indentazione delle righe *Alt+Left*, deIndentSelection\n" +
    "note +,es,Facilita l'inserimento delle annotazioni *Ctrl+Alt+n*, note\n" +
    'note ↑↓,es,Sposta le annotazioni *Ctrl+Alt+t*, toggleNote\n' +
    'sect, es,Inserisce i tag section: posizionare il cursore alla fine della prima sezione *Ctrl+Alt+s*, newSections\n' +
    'tabM, es,Trasforma in tabella wiki  il codice copiaincollato da Excel (separatori di cella: tabulazioni; separatori di righe; a capo), tableMaker\n' +
    'app,es,Taglia e incolla colonne da OCR,append\n' +
    'appr,es,Riunisce elementi consecutivi in una riga *Ctrl+Alt+r*,append2\n' +
    'poem,es,Applica poem alla selezione *Ctrl+Alt+p*,incapsula,<poem>,</poem>\n' +
    'F&R,es,Regex box,mostraTrovaSostituisci\n' +
    'r!!,es,Lancia tutte le regex memorizzate *Alt+9*,memoRegexRun\n' +
    'r↓,es,Salva le regex in Index talk,salvaRegexRemoto\n' +
    'r↑,es,C↑arica le regex in Index talk,caricaRegexRemoto\n' +
    // "r=,es,Carica le regex memorizzate in Index Talk per l'opera corrente,caricaRegexRemoto\n"+
    'TAB,es,inserisce un carattere TAB,incapsula,  ,\n</pre>'
      } else { testo = testo.responseText }

      testo = $.trim(mw.alex.findStringa(testo, '<pre>', '</pre>', 0)).split('\n')
      for (let i = 0; i < testo.length; i += 1) {
        testo[i] = testo[i].split(',')
      }
      return testo
    }

   function buildButtons() {
      var bottoni = leggiPersonalButtons()
      var html = ''
      var sh = null
      $.each(bottoni, function (index, value) {
        sh = null
        html = $('<button>')
          .attr('class', 'baseButton')
          .attr('type', 'button')
          .attr('id', 'button' + index)
          .attr('title', value[2])
          .css('display', 'inline')
          .append($('<small>').text(value[0]))

        if (value[2].match(/\*([^*]+)\*/)) {
          sh = value[2].match(/\*([^*]+)\*/)[1]
        }

        // console.log(value.toString()+" "+value.length)

        if ($.trim(value[3]) !== 'incapsula') {
          html.click(function () {
          /* if (alex[$.trim(value[3])]===undefined) {
          window[$.trim(value[3])]();
        } else {
          alex[$.trim(value[3])]();
        } */
          // chiudo l'accesso all'oggetto window
            alex[$.trim(value[3])]()
          })
        } else {
          html.click(function () {
            alex.incapsula(value[4].replace(/\\n/g, '\n'), value[5].replace(/\\n/g, '\n'))
          })
        }
        if (sh) {
          mw.alex.shortcut.add(sh, function () {
            $('#button' + index).click()
          })
        }

        $('#newtattoo').append(html)
      })
    }
    /* Funzioni per la bottoniera */

    // Sostituisce tutti gli apostrofi dattilografici in tipografici, ma rispetta
    // gli apostrofi di marckup wiki e gli apostrofi
    // contenuti in: math, {{{}}}, {{}}, [[]], [], http:.....
    alex.apostrofi = function () {
      const testo = $('#wpTextbox1').val()
      const testoCod = codifica(testo)
      testoCod[0] = testoCod[0].replace(/'/g, '’').replace(/’’’’’/g, "'''''").replace(/’’’’/g, "''''").replace(/’’’/g, "'''")
        .replace(/’’/g, "''")
      $('#wpTextbox1').val(decodifica(testoCod[0], testoCod[1]))
    }

    function codifica (testo) {
      const l = []
      let res = fss(testo, l, '<math', '</math>', '')
      res = fss(res[0], res[1], '<!--', '-->', '<')
      res = fss(res[0], res[1], '{', '}', '{')
      res = fss(res[0], res[1], '[', ']', '[')
      res = fss(res[0], res[1], '<', '>', '<')
      res = fss(res[0], res[1], 'http://', ' ', '')
      res = fss(res[0], res[1], 'https://', ' ', '')
      return res
    }

    function fss (testo, l, tagi, tagf, x) {
      while (mw.alex.findStringa(testo, tagi, tagf, 1) > '') {
        const el = mw.alex.findStringa(testo, tagi, tagf, 1, tagi)
        testo = testo.replace(el, '###el' + l.length + '###')
        l.push(el)
      }
      return [testo, l]
    }

    // La funzione decodifica() riceve un testo codificato e la lista degli elementi protetti e restituisce un testo
    // con gli elementi protetti risistemati al loro posto; è complementare a codifica()
    function decodifica (testo, l) {
      for (let i = l.length - 1; i > -1; i = i - 1) {
        testo = testo.replace('###el' + i + '###', l[i])
      }
      return testo
    }
/*    alex.autoRi = function () {
      if (mw.config.get('wgServer') === '//it.wikisource.org') {
        const header = mw.alex.findStringa(alex.p_2[1][0], '/>', '</noinclude>', 0)
        mw.alex.scriviBox(alex.newAutoRi(header), '0')
        const footer = mw.alex.findStringa(alex.p_2[1][2], '<noinclude>', '</noinclude>', 0)
        mw.alex.scriviBox(alex.newAutoRi(footer), '2')
      }
    }
    */
    alex.incapsula = function (pre, post) {
      const testo = mw.alex.getSelection()
      while (testo[1].slice(-1) === ' ') {
        testo[1] = testo[1].slice(0, -1)
        testo[2] = ' ' + testo[2]
      }
      testo[0] += pre
      testo[2] = post + testo[2]
      mw.alex.writeSelection(testo)
    }

    alex.diacriticiToggle = function () {
	   if($(".diacritici)").length > 0) {
		   
		   if (!$('.diacritici').hasClass('ui-draggable')) {
		        $('.diacritici').draggable();
		      }
		      $('.diacritici').toggle();
	       } else { 
	       	   alert("Tool diacritici lacking, compare your common.js page with [[:mul:user:Alex brollo bis/common.js]]");
           }
    }
    // Funzioni per gesione maiuscole/minuscole

    function capitalize (testo) {
      testo = testo.split(' ')
      for (let i = 0; i < testo.length; i += 1) {
        testo[i] = testo[i].substring(0, 1).toLocaleUpperCase() + testo[i].substring(1).toLocaleLowerCase()
      }
      return testo.join(' ')
    }

    function changeCase (testo) {
      if (testo === testo.toLocaleUpperCase()) testo = testo.toLocaleLowerCase()
      else testo = testo.toLocaleUpperCase()
      return testo
    }

    alex.capit = function () {
      const t = mw.alex.selection()
      t[1] = capitalize(t[1])
      // mw.alex.scriviBox(t.join(""));
      mw.alex.scriviSel(t)
    }

    alex.up_low = function () {
      const t = mw.alex.getSelection()
      t[1] = changeCase(t[1])
      mw.alex.writeSelection(t)
    // mw.alex.scriviBox(t.join(""), "", t[0].length, t[0].length + t[1].length);
    }

    // Elimina righe vuote.
    alex.eliminaRigheVuote = function () {
      $('#wpTextbox1').val($('#wpTextbox1').val().replace(/\s+$/gm, '').replace(/\n\n/g, '\n'))
    }

    alex.aggiustaParagrafi = function () {
      let testo = $('#wpTextbox1').val()
      const poems = mw.alex.produciLista(testo, '<poem', '</poem>', 1)
      for (let i = 0; i < poems.length; i += 1) {
        testo = testo.replace(poems[i], '[#' + i + '#]')
      }
      testo = testo.replace(/ \n/g, '\n').replace(/([.?!»:]\n)([^\n])/g, '$1\n$2')
      for (let i = 0; i < poems.length; i += 1) {
        testo = testo.replace('[#' + i + '#]', poems[i])
      }
      $('#wpTextbox1').val(testo)
    }

    alex.unisciLinee = function () {
    // eliminazione acapo che esclude sia i testi <poem> che le righe che iniziano con  ";:#*" (liste html)

      let testo = $('#wpTextbox1').val()
      // fase 1: codifica
      const poems = mw.alex.produciLista(testo, '<poem', '</poem>', 1)
      for (let i = 0; i < poems.length; i += 1) {
        testo = testo.replace(poems[i], '[#' + i + '#]')
      }
      // fase2: eliminazione acapo singoli, con conservazione dei multipli
      testo = testo.replace(/([^>}\n])\n([^<\n:;*#|{])/g, '$1 $2') // linux
      testo = testo.replace(/([^>}\r\n])\r\n([^<\r\n:;*#|{])/g, '$1 $2') // windows
      // eliminazione sequenze di spazi, sostituiti da spazio singolo
      testo = testo.replace(/ +/g, ' ')
      // fase 3: decodifica
      for (let i = 0; i < poems.length; i += 1) {
        testo = testo.replace('[#' + i + '#]', poems[i])
      }
      // fase 4: sistemazione a capo attorno a poem
      testo = testo.replace(/ <poem>/g, '\n<poem>').replace(/<\/poem> /g, '</poem>\n')
      $('#wpTextbox1').val(testo)
    }
    // Funzioni per indentaVersi

    alex.indentSelection = function () {
      const t = mw.alex.getSelection()
      var pn
      if (t[0].indexOf('\n') === -1) {
        t[1] = t[0] + t[1]
        t[0] = ''
      } else {
        pn = t[0].lastIndexOf('\n')
        t[1] = t[0].substring(pn + 1) + t[1]
        t[0] = t[0].substring(0, pn + 1)
      }
      const t1 = t[1].split('\n')
      for (let i = 0; i < t1.length; i += 1) {
        t1[i] = '     ' + t1[i]
      }
      t[1] = t1.join('\n')
      // mw.alex.scriviBox(t.join(""), "", t[0].length, t[0].length + t[1].length);
      mw.alex.writeSelection(t)
    }

    alex.deIndentSelection = function () {
      const t = mw.alex.getSelection()
      if (t[0].indexOf('\n') === -1) {
        t[1] = t[0] + t[1]
        t[0] = ''
      } else {
        let pn = t[0].lastIndexOf('\n')
        t[1] = t[0].substring(pn + 1) + t[1]
        t[0] = t[0].substring(0, pn + 1)
      }
      const t1 = t[1].split('\n')
      for (let i = 0; i < t1.length; i += 1) {
        for (let j = 0; j < 5; j += 1) {
          if (t1[i].substring(0, 1) === ' ') t1[i] = t1[i].substring(1)
          else break
        }
      }
      t[1] = t1.join('\n')
      // mw.alex.scriviBox(t.join(""), "", t[0].length, t[0].length + t[1].length);
      mw.alex.writeSelection(t)
    }
    /*
    function autoRi () {
      const r = /({{rh\|)(\d+)(.+}})|({{rh\|.+\|)(\d+)(}})|({{rh\|[^\d]+)(\d+)(.+}})/i
      let prevRi = r.exec(alex.p_2[1][0])

      let newRi = ''
      const header = $('#wpHeaderTextbox').val()

      if (header === '' || localStorage.saveHeader === false) {
        if (prevRi !== undefined) {
          prevRi = prevRi.filter(n => n !== undefined) // "packing" della lista
          newRi = prevRi[1] + (prevRi[2] * 1 + 2) + prevRi[3]
          $('#wpHeaderTextbox').val(newRi)
        }
      }
    }
    */
    // esegue postOCR
    // Gestisce l'inserimento di note
    alex.postOCR = function () {
      const footer = $('#wpFooterTextbox').val()
      let cat = ''
      // testoXml();
      alex.apostrofi()
      dehyphen()
      // autoRi()
      // sezione specifica per progetto
      if (mw.config.get('wgServer') === '//wikisource.org') {
        if (mw.config.get('wgCanonicalNamespace') === 'Page') {
        // aggiunta automatica di Category:Napulitano
          cat = mw.alex.findStringa(alex.p_1[1][2], '[[Category:', ']]', 1)
          if (footer.indexOf(cat) === -1) $('#wpFooterTextbox').val(footer + cat)
        }
      }

    }

    // deifenatore o_O
    function dehyphen () {
      let testo = $('#wpTextbox1').val()
      testo = testo.replace(/[-¬] *\n([^ \n]*)[ ]*[\n]?/g, '$1\n')
      $('#wpTextbox1').val(testo)
    }

    alex.note = function () {
      const t = mw.alex.getSelection()
      if (t[1].length === 0) {
        t[1] = '<sup>nota</sup>'
      } else {
        t[1] = '<ref>' + t[1] + '</ref>'
      }
      // mw.alex.scriviBox(t.join(""));
      mw.alex.writeSelection(t)
    }

    alex.toggleNote = function () {
    // alert("Versione prova su vector.js");
      const editbox = document.getElementsByName('wpTextbox1')[0]
      if (editbox.value.indexOf('<sup>nota</sup>') === -1) { // note in posizione regolare
        let lista = mw.alex.produciLista(editbox.value, '<ref', '</ref>', 1)
        lista = $.grep(lista, (n, i) => (n.indexOf('<ref follow=') === -1))
        for (let i = 0; i < lista.length; i += 1) {
          editbox.value = editbox.value.replace(lista[i], '<sup>nota</sup>')
          editbox.value = editbox.value + '\n' + lista[i]
        }
      } else { // presenza di marcatori
        let marks = mw.alex.count(editbox.value, '<ref>') + mw.alex.count(editbox.value, '<ref name=') + mw.alex.count(editbox.value, '<ref group=')
        let refs = mw.alex.count(editbox.value, '<sup>nota</sup>')
        if (marks !== refs) { // verifica parità
          alert('ATTENZIONE: discordanza fra numero dei <br />segnaposti (' + marks + ') e numero delle note (' + refs + '). Controllare!')
          return
        }
        let lista = mw.alex.produciLista(editbox.value, '<ref', '</ref>', 1)
        lista = $.grep(lista, (n, i) => (n.indexOf('<ref follow=') === -1))
        editbox.value = editbox.value.replace(/\n<ref/g, '<ref')
        for (let i = 0; i < lista.length; i += 1) {
          editbox.value = editbox.value.replace(lista[i], '').replace('<sup>nota</sup>', lista[i])
        }
      }
    }

    alex.newSections = function () {
      const s = mw.alex.getSelection()
      if (s[2].indexOf('<section end=s2 />') === -1) {
        s[0] = '<section begin=s1 />' + s[0] + '<section end=s1 />'
        s[2] = '<section begin=s2 />' + s[2] + '<section end=s2 />'
      } else {
        s[0] += '<section end=s2 />'
        s[2] = '<section begin=s3 />' + s[2].replace('<section end=s2 />', '<section end=s3 />')
      }
      s[0].value = s[0] + s[1] + s[2]
      // mw.alex.scriviBox(s.join(""));
      mw.alex.writeSelection(s)
    }

    alex.tableMaker = function () {
      const t = mw.alex.getSelection()
      let tabella = mw.alex.getSelection()[1]
      tabella = tabella.replace(/\|\|/g, '\t')
      tabella = tabella.split('\n')
      for (let i = 0; i < tabella.length; i += 1) {
        tabella[i] = '|-\n|' + tabella[i].replace(/\t/g, '||')
      }
      t[1] = '{|\n' + tabella.join('\n') + '\n|}\n'
      mw.alex.writeSelection(t)
    }

    // funzione per creare righe da elementi in colonna

    alex.append2 = function () {
      const testo = mw.alex.getSelection()
      testo[1] = testo[1].replace(/\n/g, '||')
      mw.alex.writeSelection(testo)
    }

    // funzione per aggiungere colonne a colonne
    alex.append = function () {
      if (mw.alex.getSelection()[1].length > 0) {
        alex.a = mw.alex.getSelection() // si memorizza in a gli elementi da aggiungere
        mw.alex.writeSelection([alex.a[0], '', alex.a[2]])
      } else {
        alex.b = mw.alex.getSelection()
        alex.a[1] = alex.a[1].split('\n')
        alex.b[2] = alex.b[2].split('\n')
        $.each(alex.a[1], (index, value) => {
          alex.b[2][index] = alex.b[2][index] + '||' + value
        })
        alex.b[2] = alex.b[2].join('\n')
        mw.alex.writeSelection(alex.b)
      }
    }
    alex.diacritici= function () {
    	if ($(".diacritici").length > 0) {
		$(".diacritici").toggle()
    	} else {
    		alert("Diacritici tool not running; please upload (see User:Alex brollo/common.js")
    	} 
    }
    

    alex.mostraTrovaSostituisci=function() {
		$("#findReplace_box").toggle();
	}
	
	
	
    // funzione per attivare/disattivare diacritici
    creaBottoniera()
    buildButtons()
  }
/* end of PersonalButtons routines*/
  main()
   
})(mw, $);