MediaWiki:Gadget-Typo.js

Wikisource, a biblioteca livre

Nota: Depois de publicar, poderá ter de contornar a cache do seu navegador para ver as alterações.

  • Firefox / Safari: Pressione Shift enquanto clica Recarregar, ou pressione Ctrl-F5 ou Ctrl-R (⌘-R no Mac)
  • Google Chrome: Pressione Ctrl-Shift-R (⌘-Shift-R no Mac)
  • Internet Explorer / Edge: Pressione Ctrl enquanto clica Recarregar, ou pressione Ctrl-F5
  • Opera: Pressione Ctrl-F5.
/*
 * Typo
 *
 * Botão para formatação da tipografia de texto de acordo com as convenções definidas no Wikisource [[Wikisource:Guia de tipografia]].
 * Para adicionar funcionalidades, passe para o método $ .typo.add () uma função tomando como parâmetro o string a ser limpo e retornando o string limpo. Exemplo:
 * $(function() {
 *   $.typo.add(function(str) {
 *     str = str.replace(/(\n\n\n)+/g, "\n");
 *     return str;
 *   });
 * });
 *
 * Auteur : Marc, Tpt
 * Dernière révision : 5 janvier 2018
 */
 
$.typo = {
  todo: [],
  add: function(fonction) {
    $.typo.todo.push(fonction);
  },
  exec: function() {
    var namespace = mw.config.get('wgNamespaceNumber');
    if (namespace % 2 === 1 || $.inArray(namespace, [ 4, 8 ]) !== -1) {
        return;
    }
    var $textbox = $('#wpTextbox1');
    var txt = $textbox.val();
    for (var i = 0; i < $.typo.todo.length; ++i) {
      txt = $.typo.todo[i](txt);
    }
    $textbox.val(txt);
  },
};

$(function() {
  if($.inArray(mw.config.get('wgAction'), ['edit', 'submit']) === -1 ) {
	return;
  }

  //typo
  $.typo.add(function(str) {
    // remove soft hyphen
    str = str.replace(/­/g, "");
    // espaços
    str = str.replace(/ +/g," ");
    str = str.replace(/ +\n/g, "\n");
    str = str.replace(/\n +/g, "\n");
 
    //----- typografia

    // Troca de apóstrofo por acentuação
 
    str = str.replace(/A' /g, "Á ");
    str = str.replace(/E' /g, "É ");
    str = str.replace(/O' /g, "Ó ");
    str = str.replace(/A’ /g, "Á ");
    str = str.replace(/E’ /g, "É ");
    str = str.replace(/O’ /g, "Ó ");

    // espacos inseparáveis substituídos por um espaço.
    str = str.replace(/ ([;:!\?»])/g, ' $1');
    str = str.replace(/« /g, '« ');
    str = str.replace(/ »/g, ' »');

    // hífen e travessão
    str = str.replace(/\n +/g, "\n");
    str = str.replace(/ -/g, " —");
    str = str.replace(/- /g, "— ");
    str = str.replace(/ - /g, " — ");
    str = str.replace(/ -,/g, " —,");
    str = str.replace(/ — ,/g, " —,");
    str = str.replace(/\n-/g, "— ");
    str = str.replace(/-\n(.*?)([\s\.;:!\?»\"”])/g, "$1$2\n");
    str = str.replace(/¬\n(.*?)([\s\.;:!\?»\"”])/g, "$1$2\n");
    str = str.replace(/-\n/g, "");
    str = str.replace(/¬\n/g, "");

    str = str.replace(/[  ]*([;:\!\?])[  ]*/g, "$1 ");
    str = str.replace(/( *),( *)/g, ", ");
    str = str.replace(/(\[\[[^]]*?) :/g, "$1:");
    str = str.replace(/: ([^[]*?\]\])/g, ":$1");
    str = str.replace(/[  ]+\)/g, ")");

    str = str.replace(/([^'])'([^'])/g, "$1’$2");
    str = str.replace(/’ /g, "’");
    str = str.replace(/ ’/g, "’");
    str = str.replace(/ ’ /g, "’");
    str = str.replace(/ '',/g, "'',");
    str = str.replace(/(\f*)’(\f*)/g, "’");
    str = str.replace(/ ''\./g, "''.");    
    str = str.replace(/ \./g, ".");
 
    str = str.replace(/…/g, "...");
    str = str.replace(/\.\.\.\.+/g, "...");
    str = str.replace(/etc\.\.+/g, "etc.");
 
    str = str.replace(/"([^"].*?)"/g, "“$1”");
    str = str.replace(/( *)“( *)/g, " “");
    str = str.replace(/( *)”( *)/g, "” ");
    str = str.replace(/( *)«( *)/g, " «");
    str = str.replace(/( *)»( *)/g, "» ");
    str = str.replace(/» ,/g, "»,");
    str = str.replace(/» \./g, "».");
 
 
    // quebras de linha inoportunas
    str = str.replace(/\n «/g, "\n«");

    // fix catégories
    str = str.replace(/\[\[ ?[Cc]ategory/g, "[[Categoria");
    str = str.replace(/\[\[ ?[Cc]ategoria ?: ?/g, "[[Categoria:");
 
    // réparation liens internes
    str = str.replace(/\[\[ ?([^\]]*?) ?\]\]/g, "[[$1]]");
    str = str.replace(/\[\[([^\]]*?)[ _]#([^\]]*?)\]\]/g, "[[$1#$3]]");
 
    // syntaxe wiki
    str = str.replace(/<i>(.*?)<\/i>/gi, "''$1''");
    str = str.replace(/<b>(.*?)<\/b>/gi, "'''$1'''");
    str = str.replace(/<br\/>/gi, "<br />");
    str = str.replace(/<br>/gi, "<br />");
    str = str.replace(/^<br \/>/g, "<nowiki />"); //pour le saut de ligne entre 2 pages
 
    //* puces
    str = str.replace(/^([\*#]+) /gm, "$1");
    str = str.replace(/^([\*#]+)/gm, "$1 ");
 
    // layout
    //str = str.replace(/\n*(\{\{Titre)/g, "\n$1");
    //str = str.replace(/\n*(\{\{Navigateur)/g, "\n$1");
    str = str.replace(/\[\[(.*?) —/g, "[[$1 -");
    str = str.replace(/\|( *)—( *)/g, "|");

    str = str.replace(/(formatnum\s:\s)+/g, "formatnum:");
    // les balises sont cassées par les regexp formatant les : et les ;
    str = str.replace(/= “([^»"]*)” /g, "=\"$1\" ");
    str = str.replace(/= « ([^»"]*) » /g, "=\"$1\" ");
    // FIXME: répare les balises mais en même temps casse la typo des textes
    // contenant des xxx : yyy ; zzz il faut faire quelque chose de plus fin.
    str = str.replace(/"([^":]*) : ([^:"]*) ; */g, "\"$1:$2; ");
    str = str.replace(/([^ ]); ([^":]*) : ([^:"]*) ; */g, "$1; $2:$3; ");
    str = str.replace(/([^ ]); ([^":]*) : ([^:"]*) ; */g, "$1; $2:$3; ");

    //str = str.replace(/‘/g, "’");
    str = str.replace(/fi/g, "fi"); 
    str = str.replace(/fl/g, "fl");

    // Desfaz algumas alterações, pelo menos para as entidades html usadas com mais frequência. 
    // Este conjunto de modificações deve ser feito após todas as outras modificações.
    str = str.replace(/&(nbsp|ldquo|rdquo) ;/g, "&$1;");
    // éviter l'apparition d'espace en fin de ligne ou avant la fermeture d'un tag
    str = str.replace(/\n »/g, "\n»");
    str = str.replace(/([,;:!?»”]) (\n|<\/)/g, "$1$2");
    // evita o aparecimento de espaços antes do final do itálico
    str = str.replace(/([;:!\?»”]) ''([ \n])/g, "$1''$2");

    str = str.replace(/([0-9])\. ([0-9])/g,"$1.$2");
    str = str.replace(/\n +/g,"\n");
	// Normalise les : en débuts de page
	str = str.replace(/\n : */g, "\n:");
    str = str.replace(/(:+) *: */g, "$1:");
    str = str.replace(/:: /g, "::");
    
    // substituições recorrentes
    str = str.replace(/>>/g, "»");
    str = str.replace(/<</g, "«");
    str = str.replace(/\^a/g, "ª");
    str = str.replace(/\^o/g, "º");
    str.replace(/\^\b/g, "<sup>$1</sup>");

    return $.trim(str);
  });
 
// simplifica alguns links: [[cachorro|cachorro]] para [[cachorro]] e [[Cachorro|cachorros]] para [[cachorro]]s
  $.typo.add(function(str) {
    var m = str.match(/\[\[([^[]*?)\|([^[]*?)\]\]/g);
    if (m) {
      for (var i = 0; i < m.length; i++) {
        var n_arr = m[i].toString().match(/\[\[([^[]*?)\|([^[]*?)\]\]/);
        var n = n_arr[0];
        var a = n_arr[1];
        var b = n_arr[2];
        var temp = $.trim(a).toLowerCase();
        if (b.indexOf(a) === 0 || b.indexOf(temp) === 0) {
          var k = n.replace(/\[\[([^\]\|]*?)\|(\1)([\w]*?)\]\]/i, "[[$2]]$3");
          str = str.replace(n, k);
        }
      }
    }
    str = str.replace(/\[\[([^\]\|]+)\|([^\]\|]+)\]\]([A-Za-z\'][A-Za-z]*)([\.\,\;\:\"\!\?\s\n])/g, "[[$1|$2$3]]$4");
    return str;
  });

  var dependencies = ['ext.wikiEditor'];
  if(mw.config.get('wgCanonicalNamespace') === 'Page') {
    dependencies.push('ext.proofreadpage.page.edit');
  }
  mw.loader.using(dependencies, function() {
    $('#wpTextbox1').wikiEditor('addToToolbar', {
        section: 'main',
		group: 'insert',
        tools: {
          'typo': {
            label: 'Correction de la mise en page et de la typographie',
            type: 'button',
            icon: '//upload.wikimedia.org/wikipedia/commons/8/82/Toolbaricon_regular_T.png',
            action: {
              type: 'callback',
              execute: $.typo.exec
            }
          }
        }
    });
  });
});