MediaWiki/Mes Extensions/SyntaxHighlight

  MediaWiki/Mes_Extensions


MediaWiki/Mes Extensions/SyntaxHighlight
Nom SyntaxHighlight
Lien Extension:SyntaxHighlight
Github  wikimediagerrit:extensions/SyntaxHighlight_GeSHi

Description

Mise en forme de code


L'extension SyntaxHighlight, anciennement connue sous le nom de SyntaxHighlight_GeSHi, fournit un formatage riche du code source à l'aide de la balise ‎<syntaxhighlight>. Il est alimenté par la bibliothèque Pygments et prend en charge des centaines de langages de programmation et de formats de fichiers différents.

Lire la suite ...


Nouvelle version avec pygments

La nouvelle version utilise la librairie Pygments .
Elle permet d'ajouter un langage.
Pour cela il faut modifier la librarie utilisée écrite en python et disponible sur github, voir ici   Comment

J'ai ajouté le langage Clearcase

Je l'utilise au travers du modèle Modèle:Syntaxhighlight

Il est nécessaire aussi de configurer le binaire associé à pigments. Par défaut celui fourni par Mes Extensions/SyntaxHighlight ne fonctionne pas forcément; il a été généré sur une plateforme Linux avec une version de python assez récente.
Pour ma part j'ai configuré ceci dans mon fichier  LocalSettings.php

if ( $isWindows ) {
	$wgPygmentizePath = "$IP/extensions/SyntaxHighlight_GeSHi/pygments/pygments/dist/__main__.exe";
} else {	
	$wgPygmentizePath = "/homez.913/jltryoen/python/pygments/pygmentize";
}


Syntaxe

{{syntaxhighlight | lang=php|wfLoadExtension("SyntaxHighlight_GeSHi" );}}

Résultat

wfLoadExtension("SyntaxHighlight_GeSHi" );


Comment ajouter un "lexer" à l'outil pygments

Voir  https://pygments.org/docs/lexerdevelopment/

  • Cloner la repository de pygments en local
Le site est   pygments/pygments
git clone https://github.com/pygments/pygments.git
  • Ajouter le lexer souhaité sous le répertoire  pygments/lexers en respectant bien les champs à remplir:
example de fichier

"""
    pygments.lexers.clearcase
    ~~~~~~~~~~~~~~~~~~~~~

    Lexers for clearcase

    :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

import re

from pygments.lexer import Lexer, RegexLexer, ExtendedRegexLexer, include, \
    bygroups, default, LexerContext, do_insertions, words, line_re
from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
    Number, Punctuation, Error, Generic, Whitespace
from pygments.util import shebang_matches


__all__ = ['ClearcaseLexer']


class ClearcaseLexer(RegexLexer):
    """
    Lexer for (ba|k|z|)sh shell scripts.
    """

    name = 'Clearcase'
    mimetypes = ['application/text']
    filenames = ['*.clr']
    aliases = ['clearcase']
    url = 'https://en.wikipedia.org/wiki/Unix_shell'
    version_added = '0.6'
    tokens = {
        'root': [
            include('basic'),
            (r'`', String.Backtick, 'backticks'),
            include('data'),
            include('interp'),
        ],
        'interp': [
            (r'\$\(\(', Keyword, 'math'),
            (r'\$\(', Keyword, 'paren'),
            (r'\$\{#?', String.Interpol, 'curly'),
            (r'\$[a-zA-Z_]\w*', Name.Variable),  # user variable
            (r'\$(?:\d+|[#$?!_*@-])', Name.Variable),      # builtin
            (r'\$', Text),
        ],
        'basic': [
            (r'\b(ct|clearcase)(\s*)\b',
             bygroups(Keyword, Whitespace)),
            (r'\b(chtype|rmname|rmelem|find|rmbranch|rmtype|mklbtype|mklabel|mkbrtype|rename|rmlabel,lsvob|lsview|setview|rmview|lsvob|pwv|checkout|checkin|co|ci|lsc)(?=[\s)])',
             Name.Builtin),
            (r'\A#!.+\n', Comment.Hashbang),
            (r'#.*\n', Comment.Single),
            (r'\\[\w\W]', String.Escape),
            (r'(\b\w+)(\s*)(\+?=)', bygroups(Name.Variable, Whitespace, Operator)),
            (r'[\[\]{}()=]', Operator),
            (r'<<<', Operator),  # here-string
            (r'<<-?\s*(\'?)\\?(\w+)[\w\W]+?\2', String),
            (r'&&|\|\|', Operator),
        ],
        'data': [
            (r'(?s)\$?"(\\.|[^"\\$])*"', String.Double),
            (r'"', String.Double, 'string'),
            (r"(?s)\$'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single),
            (r"(?s)'.*?'", String.Single),
            (r';', Punctuation),
            (r'&', Punctuation),
            (r'\|', Punctuation),
            (r'\s+', Whitespace),
            (r'\d+\b', Number),
            (r'[^=\s\[\]{}()$"\'`\\<&|;]+', Text),
            (r'<', Text),
        ],
        'string': [
            (r'"', String.Double, '#pop'),
            (r'(?s)(\\\\|\\[0-7]+|\\.|[^"\\$])+', String.Double),
            include('interp'),
        ],
        'curly': [
            (r'\}', String.Interpol, '#pop'),
            (r':-', Keyword),
            (r'\w+', Name.Variable),
            (r'[^}:"\'`$\\]+', Punctuation),
            (r':', Punctuation),
            include('root'),
        ],
        'paren': [
            (r'\)', Keyword, '#pop'),
            include('root'),
        ],
        'math': [
            (r'\)\)', Keyword, '#pop'),
            (r'\*\*|\|\||<<|>>|[-+*/%^|&<>]', Operator),
            (r'\d+#[\da-zA-Z]+', Number),
            (r'\d+#(?! )', Number),
            (r'0[xX][\da-fA-F]+', Number),
            (r'\d+', Number),
            (r'[a-zA-Z_]\w*', Name.Variable),  # user variable
            include('root'),
        ],
        'backticks': [
            (r'`', String.Backtick, '#pop'),
            include('root'),
        ],
    }
    def analyse_text(text):
        return 1

  • Mettre à jour pygments avec le nouveau "lexer"
    python scripts/gen_mapfiles.py
    
  • On peut ensuite soit générer un executable
    pyinstaller --onefile __main__.py
    
  • On peut aussi utiliser un lanceur python ex:  pygments/pygmentize
    #!/usr/bin/python3
    # -*- coding: utf-8 -*-
    import re
    import sys
    from pygments.cmdline import main
    if __name__ == '__main__':
        sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
        sys.exit(main())
    


Information Information:  ma version de python chez OVH est la
Python 3.7.3 (default, Mar 23 2024, 16:12:05)

Du coup j'ai du revenir en arrière sur la version de pygments, juste avant cette version:

SHA-1: e7f50060fd644b17de8debbd2a5c259c64898d4f
* Drop support for EOL Python 3.7 (#2601)
  • soit la version du 30/11/2023
SHA-1: 276dcf8ae4af6e959e13ea6f63d9f5e7bc80ea48
* Update CHANGES
git reset --hard 276dcf8ae4af6e959e13ea6f63d9f5e7bc80ea48
et rajouter mon fichier clearcase.py, relancer la commande de génération
python scripts/gen_mapfiles.py
et relancer la commande de génération du binaire
pyinstaller --onefile __main__.py