UserScript • PB-SyntaxHighlighting for codes in the forum

For everything that's not in any way related to PureBasic. General chat etc...
User avatar
Kwai chang caine
Addict
Addict
Posts: 4968
Joined: Sun Nov 05, 2006 11:42 pm
Location: Lyon - France

Re: UserScript • PB-SyntaxHighlighting for codes in the foru

Post by Kwai chang caine »

Hello tssoft

Me too i have not chrome installed, i use portable version, like for firefox
But i believe only the creator of the code can do that..
Perhaps, i have not understand :oops:
Furthermore if kcc do that, never i can answer at questions if chrome ask something to me...
ImageThe happiness is a road...
Not a destination
DarkDragon
Addict
Addict
Posts: 2124
Joined: Mon Jun 02, 2003 9:16 am
Location: Germany
Contact:

Re: UserScript • PB-SyntaxHighlighting for codes in the foru

Post by DarkDragon »

There is a simple workaround for chrome, but you need to press a button every time you read a purebasic topic:
  1. Copy the source code of the javascript into a javascript minifier (search via google). We'll call the output %js-min% from now on.
  2. Create a new favorite in chrome on your favorite bar with the name "Codeblocks" or similar and the URL is "javascript:%js-min%".
  3. Now whenever you visit a phpbb topic you can press this favorite and it will execute the script.
Another way is writing a chrome extension. I have not the time to do so at the moment, but I may try this in the future. The problem is that Greasemonkey is afaik an NPAPI plugin and NPAPI is not allowed in chrome anymore. But you can write plain javascript plugins, which are sandboxed. You can also compile chromium with NPAPI enabled IIRC.
bye,
Daniel
User avatar
skywalk
Addict
Addict
Posts: 3555
Joined: Wed Dec 23, 2009 10:14 pm
Location: Boston, MA

Re: UserScript • PB-SyntaxHighlighting for codes in the foru

Post by skywalk »

Thanks for the tip 8)
The nice thing about standards is there are so many to choose from. ~ Andrew Tanenbaum
User avatar
Kwai chang caine
Addict
Addict
Posts: 4968
Joined: Sun Nov 05, 2006 11:42 pm
Location: Lyon - France

Re: UserScript • PB-SyntaxHighlighting for codes in the foru

Post by Kwai chang caine »

Incredible !!! :shock:
Justly again today, i say to me, it's sade this tips not working again now, because it's really usefull
Since 2015 no new solution :cry:
And you send your tips ...it's really transmission of mind :lol:

I try to do what you explain
Thanks a lot DarkDragon 8)
ImageThe happiness is a road...
Not a destination
DarkDragon
Addict
Addict
Posts: 2124
Joined: Mon Jun 02, 2003 9:16 am
Location: Germany
Contact:

Re: UserScript • PB-SyntaxHighlighting for codes in the foru

Post by DarkDragon »

Now I automatized it via building a chrome extension:
  1. Create a folder "Codefolding" for the extension
  2. Create a manifest.json inside this folder:

    Code: Select all

    {
      "manifest_version": 2,
    
      "name": "Codefolding",
      "description": "Extension for code folding in phpBBs.",
      "version": "1.0",
    
      "content_scripts": [
        {
          "matches": ["http://*/*viewtopic.php*", "https://*/*viewtopic.php*"],
          "js": ["codefolding.js"]
        }
      ]
    }
  3. Create a codefolding.js file inside this folder with the javascript as content.
  4. Start chrome, go to chrome://extensions
  5. Enable developer mode (checkbox top right)
  6. Click on "Load uncompressed extension" (I'm running German Chrome, that's why I can't tell if this is correct) and choose the folder you've created initially
Now this script will always be executed on phpBBs.
bye,
Daniel
User avatar
Kwai chang caine
Addict
Addict
Posts: 4968
Joined: Sun Nov 05, 2006 11:42 pm
Location: Lyon - France

Re: UserScript • PB-SyntaxHighlighting for codes in the foru

Post by Kwai chang caine »

Whaaaaooouuh !!!! never you believe me !!!!
I have do all what you say with success !!! :mrgreen:

You are a god of the CHROME...
Thanks a lot 8)
ImageThe happiness is a road...
Not a destination
User avatar
Kwai chang caine
Addict
Addict
Posts: 4968
Joined: Sun Nov 05, 2006 11:42 pm
Location: Lyon - France

Re: UserScript • PB-SyntaxHighlighting for codes in the foru

Post by Kwai chang caine »

I have modified the line

Code: Select all

 if (code.innerHTML.split("<br>").length - 1 >= 10)
in

Code: Select all

 if (code.innerHTML.split("<br>").length - 1 >= 1000000)
for remove the scrolling function not really usefull for me

Again a big thanks for your precious tips DarkDragon 8)
ImageThe happiness is a road...
Not a destination
User avatar
STARGÅTE
Addict
Addict
Posts: 1622
Joined: Thu Jan 10, 2008 1:30 pm
Location: Germany, Glienicke
Contact:

Re: UserScript • PB-SyntaxHighlighting for codes in the forum

Post by STARGÅTE »

Here is the new version of my user script for the code section syntax highlighting for the new forum version:

Code: Select all

// ==UserScript==
// @name          Pure Basic Syntax Highlighting
// @description   Pure Basic Syntax Highlighting (V 2.0) (16. Apr 2021)
// @include       https://purebasic.com/german/*
// @include       https://purebasic.fr/german/*
// @include       https://purebasic.fr/english/*
// @include       https://purebasic.fr/french/*
// @include       https://www.purebasic.com/german/*
// @include       https://www.purebasic.fr/german/*
// @include       https://www.purebasic.fr/english/*
// @include       https://www.purebasic.fr/french/*
// @include       https://forums.purebasic.com/german/*
// @include       https://forums.purebasic.com/english/*
// @include       https://forums.purebasic.fr/german/*
// @include       https://forums.purebasic.fr/english/*
// @include       https://forums.purebasic.fr/french/*
// ==/UserScript==



//--------------------------------------------
// Version 2.0 (16. Apr 2021)
//--------------------------------------------



// Farbdefinition für das Syntax Highlighting
// color definition for the syntax highlighting
//===================================================

var PBSH_Highlight = new Object();

// ==PureBasicPreference==

PBSH_Highlight['EnableKeywordBolding'] = 1;
PBSH_Highlight['EditorFontName'] = 'Consolas';
PBSH_Highlight['EditorFontSize'] = '10';
PBSH_Highlight['EditorFontStyle'] = '';
PBSH_Highlight['BackgroundColor'] = '#101010';
PBSH_Highlight['NormalTextColor'] = '#A0A0A0';
PBSH_Highlight['BasicKeywordColor'] = '#5090D0';
PBSH_Highlight['CommentColor'] = '#C04040';
PBSH_Highlight['ConstantColor'] = '#FFD000';
PBSH_Highlight['StringColor'] = '#FFFFFF';
PBSH_Highlight['PureKeywordColor'] = '#80C040';
PBSH_Highlight['ASMKeywordColor'] = '#A0A040';
//PBSH_Highlight['PointerColor'] = '#ADE4B5';
PBSH_Highlight['NumberColor'] = '#C0C0C0';
//PBSH_Highlight['StructureColor'] = '#006090';
PBSH_Highlight['LabelColor'] = '#C080FF';
PBSH_Highlight['ModuleColor'] = '#208000';
PBSH_Highlight['OperatorColor'] = '#FFFFFF';
//PBSH_Highlight['SeparatorColor'] = '#FF0000';
PBSH_Highlight['CustomKeywordColor'] = '#3060E0';

// ==/PureBasicPreference==

//===================================================







// UserScript für die Syntaxhervorhebung
// user script for syntax highlighting
//===================================================

// Regulärer Ausdruck für das SyntaxHighlighting
// regular expressions for the syntax lighting
//                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       ( Structure                                                                    )|( Function                                     )|( ASM                  )|( Pointer                                                       )|( Number                                             )
//                 (Cmnt)|( Constant           )|( String                                )|( CustomKeyword                                                                                                                                      )|( Keyword                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             )|( Structure                                                                    )|( Function                                     )|( ASM                  )|( Pointer                                                       )|( Number                                             )|( Module        )|( Label                   )|( Operator                           )|( Separator   )
var PBSH_Syntax = /(;.*$)|(\#\w*\$?|'.*?(?:'|$))|(~"(?:\\.|[^\\])*?(?:"|$)|"[^"]*?(?:"|$))|((?:^[ \t]+|\b)(?:CompilerCase|CompilerDefault|CompilerElse|CompilerElseIf|CompilerEndIf|CompilerEndSelect|CompilerError|CompilerIf|CompilerSelect)\b)|((?:^[ \t]+|\b)(?:And|Array|As|Break|CallDebugger|Case|CompilerCase|CompilerDefault|CompilerElse|CompilerElseIf|CompilerEndIf|CompilerEndSelect|CompilerError|CompilerIf|CompilerSelect|CompilerWarning|Continue|Data|DataSection|EndDataSection|Debug|DebugLevel|Declare|DeclareC|DeclareCDLL|DeclareDLL|DeclareModule|EndDeclareModule|Default|Define|Dim|DisableASM|DisableDebugger|DisableExplicit|Else|ElseIf|EnableASM|EnableDebugger|EnableExplicit|End|Enumeration|EnumerationBinary|EndEnumeration|FakeReturn|For|ForEach|ForEver|Global|Gosub|Goto|If|EndIf|Import|EndImport|ImportC|IncludeBinary|IncludeFile|IncludePath|Interface|EndInterface|List|Macro|EndMacro|MacroExpandedCount|Map|Module|EndModule|NewList|NewMap|Next|Not|Or|Procedure|EndProcedure|ProcedureC|ProcedureCDLL|ProcedureDLL|ProcedureReturn|Protected|Prototype|PrototypeC|Read|ReDim|Repeat|Restore|Return|Runtime|Select|EndSelect|Shared|Static|Step|Structure|EndStructure|StructureUnion|EndStructureUnion|Swap|Threaded|To|UndefineMacro|Until|UseModule|UnuseModule|Wend|While|With|EndWith|XIncludeFile|XOr)\b|\b[ \t]+(?:Align|Extends)\b)|((?<=\.)[ \t]*(?:[^\Wabcdfilqsuw](?=\b)|\w\w+)|(?<=\\)\w+\$?[ \t]*(?![\w\( \t]))|(\w+\$?(?=(?:[ \t]*\.[ \t]*\w+[ \t]*|[ \t]*)\())|(^[ \t]*!.*?(?:$|(?=;)))|(\@\*?[\w\$]*|(?:(?<![ \t\w$)}\]])|(?<=\5))[ \t]*\*[\w\$]+|\?\w*)|((?:\b\d+\.?\d*(?:e[+\-]?\d+)?|\$[\dabcdef]+|\%[01]+))|(\w+(?=[ \t]*::))|(^[ \t]*\w+\$?[ \t]*:(?!:))|((?:[+*/\-|!%=~]|::|&gt;|&lt;|&amp;)+)|([()\[\]\\,.:])/gim      ;

// Hervorheben einer Zeichenkette
// highlighting a string
function PBSH_Highlighting(str, key)
{
    if (PBSH_Highlight[key])
        return '<font color="'+PBSH_Highlight[key]+'">'+str+'</font>';
    else
        return str;
}
function PBSH_Highlighting_Keyword(str, key)
{
    if (PBSH_Highlight[key])
    {
        if (PBSH_Highlight['EnableKeywordBolding'])
            return '<font color="'+PBSH_Highlight[key]+'"><b>'+str+'</b></font>';
        else
            return '<font color="'+PBSH_Highlight[key]+'">'+str+'</font>';
    }
    else
        if (PBSH_Highlight['EnableKeywordBolding'])
            return '<b>'+str+'</b>';
    else
        return str;
}

// Ersetzen einer Zeichenkette
// replace a string
function PBSH_Replace(str, isComment, isConstant, isString, isCustomKeyword, isKeyword, isStructure, isFunction, isASM, isPointer, isNumber, isModule, isLabel, isOperator, isSeparator)
{
    if (isCustomKeyword)  return PBSH_Highlighting_Keyword(isCustomKeyword, 'CustomKeywordColor');
    else if (isKeyword)   return PBSH_Highlighting_Keyword(isKeyword, 'BasicKeywordColor');
    else if (isComment)   return PBSH_Highlighting(isComment, 'CommentColor');
    else if (isConstant)  return PBSH_Highlighting(isConstant, 'ConstantColor');
    else if (isString)    return PBSH_Highlighting(isString, 'StringColor');
    else if (isFunction)  return PBSH_Highlighting(isFunction, 'PureKeywordColor');
    else if (isASM)       return PBSH_Highlighting(isASM, 'ASMKeywordColor');
    else if (isPointer)   return PBSH_Highlighting(isPointer, 'PointerColor');
    else if (isNumber)    return PBSH_Highlighting(isNumber, 'NumberColor');
    else if (isStructure) return PBSH_Highlighting(isStructure, 'StructureColor');
    else if (isModule)    return PBSH_Highlighting(isModule, 'ModuleColor');
    else if (isLabel)     return PBSH_Highlighting(isLabel, 'LabelColor');
    else if (isOperator)  return PBSH_Highlighting(isOperator, 'OperatorColor');
    else if (isSeparator) return PBSH_Highlighting(isSeparator, 'SeparatorColor');
}

// Durchführen der Syntaxhervorhebung
// carry out the syntax highlighting
function PureBasicSyntaxHighlighting()
{
    // Anwenden der Syntaxhervorhebung auf alle Elemente mit der Klasse codecontent
    // apply the syntax highlighting on all the elements with class codecontent
    var allMyDivs = document.getElementsByTagName('code');
    for(var i = 0; i < allMyDivs.length; i++)
    {
        if (PBSH_Highlight['EditorFontName'])
            allMyDivs[i].style.font = PBSH_Highlight['EditorFontStyle']+" "+PBSH_Highlight['EditorFontSize']+"pt "+PBSH_Highlight['EditorFontName'];
        if (PBSH_Highlight['BackgroundColor'])
            allMyDivs[i].style.backgroundColor = PBSH_Highlight['BackgroundColor'];
        if (PBSH_Highlight['NormalTextColor'])
            allMyDivs[i].style.color           = PBSH_Highlight['NormalTextColor'];
        var code = ''+allMyDivs[i].innerHTML+'';
        code = code.replace(/<br>/gi, '\r\n');
        code = code.replace(/&nbsp;/gi, '\t');
        code = code.replace(/<\/?[^<>]*>/gi, '');
        code = code.replace(PBSH_Syntax, PBSH_Replace);
        code = code.replace(/\t/gi, '&nbsp;');
        code = code.replace(/\r\n/gi, '<br>');
        allMyDivs[i].innerHTML = code;
        allMyDivs[i].style.maxHeight = 'none';
    }
}

PureBasicSyntaxHighlighting();

//===================================================
And here is the tool to receive the pure basic colors of your IDE:

Code: Select all

Procedure.s HTMLColor(Color)
  ProcedureReturn "#"+RSet(Hex(Red(Color)),2,"0")+RSet(Hex(Green(Color)),2,"0")+RSet(Hex(Blue(Color)),2,"0")
EndProcedure

Procedure Export(PreferencesFileName$)
  If OpenPreferences(PreferencesFileName$)
    PreferenceGroup("Global")
    Debug "  PBSH_Highlight['EnableKeywordBolding'] = "+ReadPreferenceString("EnableKeywordBolding", "1")+";"
    PreferenceGroup("Editor")
    Restore PreferenceKeys
    Repeat
      Read.s Keyword$
      If Keyword$
        String$ = ReplaceString(ReadPreferenceString(Keyword$, ""), ",", " ")
        If Right(Keyword$, 5) = "Color" : String$ = HTMLColor(Val(String$)) : EndIf
        If ReadPreferenceInteger(Keyword$+"_Disabled", 0)
          Debug "  //PBSH_Highlight['"+Keyword$+"'] = '"+String$+"';"
        Else
          Debug "  PBSH_Highlight['"+Keyword$+"'] = '"+String$+"';"
        EndIf
      EndIf  
    Until Keyword$ = ""
    ProcedureReturn #True
  EndIf
EndProcedure

If Not Export(GetEnvironmentVariable("APPDATA")+"\PureBasic\PureBasic.prefs")
  PreferencesFileName$ = OpenFileRequester("Preference File", GetHomeDirectory(), "PureBasic.prefs", 0)
  Export(PreferencesFileName$)
EndIf

DataSection
  PreferenceKeys:
  Data.s "EditorFontName", "EditorFontSize", "EditorFontStyle", "BackgroundColor", "NormalTextColor"
  Data.s "BasicKeywordColor", "CommentColor", "ConstantColor", "StringColor", "PureKeywordColor"
  Data.s "ASMKeywordColor", "PointerColor", "NumberColor", "StructureColor", "LabelColor", "ModuleColor"
  Data.s "OperatorColor", "SeparatorColor", "CustomKeywordColor", ""
EndDataSection
PB 5.73 ― Win 10, 20H2 ― Ryzen 9 3900X ― Radeon RX 5600 XT ITX ― Vivaldi 4.0 ― www.unionbytes.de
Lizard - Script language for symbolic calculations and moreTypeface - Sprite-based font include/module
BarryG
Addict
Addict
Posts: 1718
Joined: Thu Apr 18, 2019 8:17 am

Re: UserScript • PB-SyntaxHighlighting for codes in the foru

Post by BarryG »

skywalk wrote: Tue Feb 22, 2011 6:45 pmIs there a way to select the Code portion of a post without having to manually select everything?

Code: Select all

You can't see the "CODE: SELECT ALL" link above every code box, like above this one?
User avatar
Sicro
Enthusiast
Enthusiast
Posts: 455
Joined: Wed Jun 25, 2014 5:25 pm
Location: Germany
Contact:

Re: UserScript • PB-SyntaxHighlighting for codes in the forum

Post by Sicro »

Thank you @STARGÅTE for the new version.

I use Violentmonkey and there I had to additionally specify the namespace so that your script is accepted by this tool, for example:

Code: Select all

// ==UserScript==
// @namespace     STARGÅTE
// @name          Pure Basic Syntax Highlighting
What I still miss is that no monospace font is used.
Image
Why OpenSource should have a license :: DarkColor-Scheme for PureBasic
PureBasic-CodeArchiv-Rebirth: Git-Repository / Download – Any help is welcome!
Manjaro Xfce x64 (Main system) :: Windows 7 x64 (VirtualBox) :: Newest PureBasic version
User avatar
skywalk
Addict
Addict
Posts: 3555
Joined: Wed Dec 23, 2009 10:14 pm
Location: Boston, MA

Re: UserScript • PB-SyntaxHighlighting for codes in the forum

Post by skywalk »

I use consolas for code editors.
The nice thing about standards is there are so many to choose from. ~ Andrew Tanenbaum
User avatar
STARGÅTE
Addict
Addict
Posts: 1622
Joined: Thu Jan 10, 2008 1:30 pm
Location: Germany, Glienicke
Contact:

Re: UserScript • PB-SyntaxHighlighting for codes in the forum

Post by STARGÅTE »

Sicro wrote: Sat Apr 17, 2021 9:33 am What I still miss is that no monospace font is used.
Here you can change the font family:

Code: Select all

PBSH_Highlight['EditorFontName'] = 'Consolas';
PB 5.73 ― Win 10, 20H2 ― Ryzen 9 3900X ― Radeon RX 5600 XT ITX ― Vivaldi 4.0 ― www.unionbytes.de
Lizard - Script language for symbolic calculations and moreTypeface - Sprite-based font include/module
User avatar
Sicro
Enthusiast
Enthusiast
Posts: 455
Joined: Wed Jun 25, 2014 5:25 pm
Location: Germany
Contact:

Re: UserScript • PB-SyntaxHighlighting for codes in the forum

Post by Sicro »

STARGÅTE wrote: Sat Apr 17, 2021 12:23 pm Here you can change the font family:
Yes, I am aware of that. It's more complicated than that. :wink:

I used your code which reads the settings from the purebasic.prefs file and generates appropriate script settings.

Code: Select all

PBSH_Highlight['EditorFontName'] = 'Source Code Pro';
PBSH_Highlight['EditorFontSize'] = '11';
PBSH_Highlight['EditorFontStyle'] = '';
My Firefox settings:
  • Fixed width font: Source Code Pro
  • Serif font family: DejaVu Serif
  • "Allow websites to use custom fonts" option is disabled
The problem is that Firefox does not accept the font family Source Code Pro in my case here:

Code: Select all

<code style="font: 11pt Source Code Pro;
and because Firefox does not consider a monospace font family necessary here, it falls back to a serif font family -- in my case the font family DejaVu Serif.

So now I had the following options:
  • Enable the "Allow websites to use custom fonts" option
  • Comment out the script setting:

    Code: Select all

    // PBSH_Highlight['EditorFontName'] = 'Source Code Pro';
    but then

    Code: Select all

    PBSH_Highlight['EditorFontSize']
    PBSH_Highlight['EditorFontStyle']
    are not observed
  • Customize the script setting to:

    Code: Select all

    PBSH_Highlight['EditorFontName'] = 'Source Code Pro, monospace';
I have chosen the last option.
Image
Why OpenSource should have a license :: DarkColor-Scheme for PureBasic
PureBasic-CodeArchiv-Rebirth: Git-Repository / Download – Any help is welcome!
Manjaro Xfce x64 (Main system) :: Windows 7 x64 (VirtualBox) :: Newest PureBasic version
User avatar
Sicro
Enthusiast
Enthusiast
Posts: 455
Joined: Wed Jun 25, 2014 5:25 pm
Location: Germany
Contact:

Re: UserScript • PB-SyntaxHighlighting for codes in the forum

Post by Sicro »

CustomKeyword should be empty and not contain any native keywords, otherwise some native keywords will be recognized as custom keywords:

Code: Select all

//                 (Cmnt)|( Constant           )|( String                                )|( CustomKeyword )|( Keyword                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             )|( Structure                                                                    )|( Function                                     )|( ASM                  )|( Pointer                                                       )|( Number                                             )|( Module        )|( Label                   )|( Operator                           )|( Separator   )
var PBSH_Syntax = /(;.*$)|(\#\w*\$?|'.*?(?:'|$))|(~"(?:\\.|[^\\])*?(?:"|$)|"[^"]*?(?:"|$))|(               )|((?:^[ \t]+|\b)(?:And|Array|As|Break|CallDebugger|Case|CompilerCase|CompilerDefault|CompilerElse|CompilerElseIf|CompilerEndIf|CompilerEndSelect|CompilerError|CompilerIf|CompilerSelect|CompilerWarning|Continue|Data|DataSection|EndDataSection|Debug|DebugLevel|Declare|DeclareC|DeclareCDLL|DeclareDLL|DeclareModule|EndDeclareModule|Default|Define|Dim|DisableASM|DisableDebugger|DisableExplicit|Else|ElseIf|EnableASM|EnableDebugger|EnableExplicit|End|Enumeration|EnumerationBinary|EndEnumeration|FakeReturn|For|ForEach|ForEver|Global|Gosub|Goto|If|EndIf|Import|EndImport|ImportC|IncludeBinary|IncludeFile|IncludePath|Interface|EndInterface|List|Macro|EndMacro|MacroExpandedCount|Map|Module|EndModule|NewList|NewMap|Next|Not|Or|Procedure|EndProcedure|ProcedureC|ProcedureCDLL|ProcedureDLL|ProcedureReturn|Protected|Prototype|PrototypeC|Read|ReDim|Repeat|Restore|Return|Runtime|Select|EndSelect|Shared|Static|Step|Structure|EndStructure|StructureUnion|EndStructureUnion|Swap|Threaded|To|UndefineMacro|Until|UseModule|UnuseModule|Wend|While|With|EndWith|XIncludeFile|XOr)\b|\b[ \t]+(?:Align|Extends)\b)|((?<=\.)[ \t]*(?:[^\Wabcdfilqsuw](?=\b)|\w\w+)|(?<=\\)\w+\$?[ \t]*(?![\w\( \t]))|(\w+\$?(?=(?:[ \t]*\.[ \t]*\w+[ \t]*|[ \t]*)\())|(^[ \t]*!.*?(?:$|(?=;)))|(\@\*?[\w\$]*|(?:(?<![ \t\w$)}\]])|(?<=\5))[ \t]*\*[\w\$]+|\?\w*)|((?:\b\d+\.?\d*(?:e[+\-]?\d+)?|\$[\dabcdef]+|\%[01]+))|(\w+(?=[ \t]*::))|(^[ \t]*\w+\$?[ \t]*:(?!:))|((?:[+*/\-|!%=~]|::|&gt;|&lt;|&amp;)+)|([()\[\]\\,.:])/gim      ;
Image
Why OpenSource should have a license :: DarkColor-Scheme for PureBasic
PureBasic-CodeArchiv-Rebirth: Git-Repository / Download – Any help is welcome!
Manjaro Xfce x64 (Main system) :: Windows 7 x64 (VirtualBox) :: Newest PureBasic version
User avatar
STARGÅTE
Addict
Addict
Posts: 1622
Joined: Thu Jan 10, 2008 1:30 pm
Location: Germany, Glienicke
Contact:

Re: UserScript • PB-SyntaxHighlighting for codes in the forum

Post by STARGÅTE »

You are right.
Here is a new updated version, also with an easier regex:
PS: I added all the compiler keywords as custom keywords to have a contrast in the IDE.

Code: Select all

// ==UserScript==
// @namespace     STARGÅTE
// @name          Pure Basic Syntax Highlighting
// @description   Pure Basic Syntax Highlighting (V 2.0.2) (20. May 2021)
// @include       https://purebasic.com/german/*
// @include       https://purebasic.fr/german/*
// @include       https://purebasic.fr/english/*
// @include       https://purebasic.fr/french/*
// @include       https://www.purebasic.com/german/*
// @include       https://www.purebasic.fr/german/*
// @include       https://www.purebasic.fr/english/*
// @include       https://www.purebasic.fr/french/*
// @include       https://forums.purebasic.com/german/*
// @include       https://forums.purebasic.com/english/*
// @include       https://forums.purebasic.fr/german/*
// @include       https://forums.purebasic.fr/english/*
// @include       https://forums.purebasic.fr/french/*
// ==/UserScript==



//--------------------------------------------
// Version 2.0.1 (17. Apr 2021)
//--------------------------------------------



// Farbdefinition für das Syntax Highlighting
// color definition for the syntax highlighting
//===================================================

var PBSH_Highlight = new Object();

// ==PureBasicPreference==

PBSH_Highlight.EnableKeywordBolding = 1;
PBSH_Highlight.TabLength = 2;
PBSH_Highlight.CustomKeywords = '';
PBSH_Highlight.EditorFontName = 'Consolas';
PBSH_Highlight.EditorFontSize = '10';
PBSH_Highlight.EditorFontStyle = '';
PBSH_Highlight.BackgroundColor = '#101010';
PBSH_Highlight.NormalTextColor = '#A0A0A0';
PBSH_Highlight.BasicKeywordColor = '#5090D0';
PBSH_Highlight.CommentColor = '#C04040';
PBSH_Highlight.ConstantColor = '#FFD000';
PBSH_Highlight.StringColor = '#FFFFFF';
PBSH_Highlight.PureKeywordColor = '#80C040';
PBSH_Highlight.ASMKeywordColor = '#A0A040';
//PBSH_Highlight.PointerColor = '#ADE4B5';
PBSH_Highlight.NumberColor = '#C0C0C0';
//PBSH_Highlight.StructureColor = '#006090';
PBSH_Highlight.LabelColor = '#C080FF';
PBSH_Highlight.ModuleColor = '#208000';
PBSH_Highlight.OperatorColor = '#FFFFFF';
//PBSH_Highlight.SeparatorColor = '#FFFFFF';
PBSH_Highlight.CustomKeywordColor = '#3060E0';

// ==/PureBasicPreference==

//===================================================





// UserScript für die Syntaxhervorhebung
// user script for syntax highlighting
//===================================================

// Regulärer Ausdruck für das SyntaxHighlighting
// regular expressions for the syntax lighting
if (PBSH_Highlight.CustomKeywords == '') PBSH_Highlight.CustomKeywords = 'NoCustomKeywordsDefined';
var PBSH_Syntax = new RegExp(
    /*Comment*/       '(;.*$)|' +
    /*Constant*/      '(\\#\\w*\\$?|\'.*?(?:\'|$))|' +
    /*String*/        '(~"(?:\\\\.|[^\\\\])*?(?:"|$)|"[^"]*?(?:"|$))|' +
    /*CustomKeyword*/ '((?:^[ \\t]+|\\b)(?:'+PBSH_Highlight.CustomKeywords+')\\b)|' +
    /*Keyword*/       '((?:^[ \\t]+|\\b)(?:And|Array|As|Break|CallDebugger|Case|CompilerCase|CompilerDefault|CompilerElse|CompilerElseIf|CompilerEndIf|CompilerEndSelect|CompilerError|CompilerIf|CompilerSelect|CompilerWarning|Continue|Data|DataSection|EndDataSection|Debug|DebugLevel|Declare|DeclareC|DeclareCDLL|DeclareDLL|DeclareModule|EndDeclareModule|Default|Define|Dim|DisableASM|DisableDebugger|DisableExplicit|Else|ElseIf|EnableASM|EnableDebugger|EnableExplicit|End|Enumeration|EnumerationBinary|EndEnumeration|FakeReturn|For|ForEach|ForEver|Global|Gosub|Goto|If|EndIf|Import|EndImport|ImportC|IncludeBinary|IncludeFile|IncludePath|Interface|EndInterface|List|Macro|EndMacro|MacroExpandedCount|Map|Module|EndModule|NewList|NewMap|Next|Not|Or|Procedure|EndProcedure|ProcedureC|ProcedureCDLL|ProcedureDLL|ProcedureReturn|Protected|Prototype|PrototypeC|Read|ReDim|Repeat|Restore|Return|Runtime|Select|EndSelect|Shared|Static|Step|Structure|EndStructure|StructureUnion|EndStructureUnion|Swap|Threaded|To|UndefineMacro|Until|UseModule|UnuseModule|Wend|While|With|EndWith|XIncludeFile|XOr)\\b|\\b[ \\t]+(?:Align|Extends)\\b)|' +
    /*Structure*/     '((?<=\\.)[ \\t]*(?:[^\\Wabcdfilqsuw](?=\\b)|\\w\\w+)|(?<=\\\\)\\w+\\$?[ \\t]*(?![\\w\\( \\t]))|' +
    /*Function*/      '(\\w+\\$?(?=(?:[ \\t]*\\.[ \\t]*\\w+[ \\t]*|[ \\t]*)\\())|' +
    /*ASM*/           '(^[ \\t]*!.*?(?:$|(?=(?<!&gt|&lt|&amp);)))|' +
    /*Pointer*/       '(\\@\\*?[\\w\\$]*|(?:(?<![ \\t\\w$)}\\]])|(?<=\\5))[ \\t]*\\*[\\w\\$]+|\\?\\w*)|' +
    /*Number*/        '((?:\\b\\d+\\.?\\d*(?:e[+\\-]?\\d+)?|\\$[\\dabcdef]+|\\%[01]+))|' +
    /*Module*/        '(\\w+(?=[ \\t]*::))|' +
    /*Label*/         '(^[ \\t]*\\w+\\$?[ \\t]*:(?!:))|' +
    /*Operator*/      '((?:[+*/\\-|!%=~]|::|&gt;|&lt;|&amp;)+)|' +
    /*Seperator*/     '([()\\[\\]\\\\,.:])',
    'gim');

// Hervorheben einer Zeichenkette
// highlighting a string
function PBSH_Highlighting(str, key)
{
    if (PBSH_Highlight[key])
        return '<font color="'+PBSH_Highlight[key]+'">'+str+'</font>';
    else
        return str;
}
function PBSH_Highlighting_Keyword(str, key)
{
    if (PBSH_Highlight[key])
    {
        if (PBSH_Highlight.EnableKeywordBolding)
            return '<font color="'+PBSH_Highlight[key]+'"><b>'+str+'</b></font>';
        else
            return '<font color="'+PBSH_Highlight[key]+'">'+str+'</font>';
    }
    else
        if (PBSH_Highlight.EnableKeywordBolding)
            return '<b>'+str+'</b>';
    else
        return str;
}

// Ersetzen einer Zeichenkette
// replace a string
function PBSH_Replace(str, isComment, isConstant, isString, isCustomKeyword, isKeyword, isStructure, isFunction, isASM, isPointer, isNumber, isModule, isLabel, isOperator, isSeparator)
{
    if (isCustomKeyword)  return PBSH_Highlighting_Keyword(isCustomKeyword, 'CustomKeywordColor');
    else if (isKeyword)   return PBSH_Highlighting_Keyword(isKeyword, 'BasicKeywordColor');
    else if (isComment)   return PBSH_Highlighting(isComment, 'CommentColor');
    else if (isConstant)  return PBSH_Highlighting(isConstant, 'ConstantColor');
    else if (isString)    return PBSH_Highlighting(isString, 'StringColor');
    else if (isFunction)  return PBSH_Highlighting(isFunction, 'PureKeywordColor');
    else if (isASM)       return PBSH_Highlighting(isASM, 'ASMKeywordColor');
    else if (isPointer)   return PBSH_Highlighting(isPointer, 'PointerColor');
    else if (isNumber)    return PBSH_Highlighting(isNumber, 'NumberColor');
    else if (isStructure) return PBSH_Highlighting(isStructure, 'StructureColor');
    else if (isModule)    return PBSH_Highlighting(isModule, 'ModuleColor');
    else if (isLabel)     return PBSH_Highlighting(isLabel, 'LabelColor');
    else if (isOperator)  return PBSH_Highlighting(isOperator, 'OperatorColor');
    else if (isSeparator) return PBSH_Highlighting(isSeparator, 'SeparatorColor');
}

// Durchführen der Syntaxhervorhebung
// perform the syntax highlighting
function PureBasicSyntaxHighlighting()
{
    // Anwenden der Syntaxhervorhebung auf alle <code>-Elemente
    // apply the syntax highlighting on all the <code>-elements
    var allMyDivs = document.getElementsByTagName('code');
    for(var i = 0; i < allMyDivs.length; i++)
    {
        if (PBSH_Highlight.EditorFontName)
            allMyDivs[i].style.font = PBSH_Highlight.EditorFontStyle + " " + PBSH_Highlight.EditorFontSize + "pt " + PBSH_Highlight.EditorFontName;
        if (PBSH_Highlight.BackgroundColor)
            allMyDivs[i].style.backgroundColor = PBSH_Highlight.BackgroundColor;
        if (PBSH_Highlight.NormalTextColor)
            allMyDivs[i].style.color           = PBSH_Highlight.NormalTextColor;
        allMyDivs[i].style.tabSize = PBSH_Highlight.TabLength;
        var code = ''+allMyDivs[i].innerHTML+'';
        code = code.replace(/<br>/gi, '\r\n');
        //code = code.replace(/&nbsp;/gi, '\t');
        code = code.replace(/<\/?[^<>]*>/gi, '');
        code = code.replace(PBSH_Syntax, PBSH_Replace);
        //code = code.replace(/\t/gi, '&nbsp;');
        //code = code.replace(/\r\n/gi, '<br>');
        allMyDivs[i].innerHTML = code;
    }
}

PureBasicSyntaxHighlighting();

//===================================================
To import the personally syntax highlighting you can run this code, and copy the output into the script:

Code: Select all

EnableExplicit

Procedure.s HTMLColor(Color)
	ProcedureReturn "#"+RSet(Hex(Red(Color)),2,"0")+RSet(Hex(Green(Color)),2,"0")+RSet(Hex(Blue(Color)),2,"0")
EndProcedure

Procedure Export(PreferencesFileName.s)
	Protected Keyword.s, String.s, CustomKeywords.s
	If OpenPreferences(PreferencesFileName)
		PreferenceGroup("Global")
		Debug "PBSH_Highlight.EnableKeywordBolding = "+ReadPreferenceString("EnableKeywordBolding", "1")+";"
		Debug "PBSH_Highlight.TabLength = "+ReadPreferenceString("TabLength", "2")+";"
		PreferenceGroup("CustomKeywords")
		If ExaminePreferenceKeys()
			While NextPreferenceKey() 
				If Left(PreferenceKeyName(), 1) = "W"
					If CustomKeywords : CustomKeywords + "|" : EndIf
					CustomKeywords + PreferenceKeyValue()  
				EndIf
			Wend
		EndIf
		Debug "PBSH_Highlight.CustomKeywords = '"+CustomKeywords+"';"
		PreferenceGroup("Editor")
		Restore PreferenceKeys
		Repeat
			Read.s Keyword
			If Keyword
				String = ReplaceString(ReadPreferenceString(Keyword, ""), ",", " ")
				If Right(Keyword, 5) = "Color" : String = HTMLColor(Val(String)) : EndIf
				If ReadPreferenceInteger(Keyword+"_Disabled", 0)
					Debug "//PBSH_Highlight."+Keyword+" = '"+String+"';"
				Else
					Debug "PBSH_Highlight."+Keyword+" = '"+String+"';"
				EndIf
			EndIf  
		Until Keyword = ""
		ProcedureReturn #True
	EndIf
EndProcedure

Define PreferencesFileName.s

If Not Export(GetUserDirectory(#PB_Directory_ProgramData)+"PureBasic\PureBasic.prefs")
	PreferencesFileName = OpenFileRequester("Preference File", GetHomeDirectory(), "PureBasic.prefs", 0)
	Export(PreferencesFileName)
EndIf

DataSection
	PreferenceKeys:
	Data.s "EditorFontName", "EditorFontSize", "EditorFontStyle", "BackgroundColor", "NormalTextColor"
	Data.s "BasicKeywordColor", "CommentColor", "ConstantColor", "StringColor", "PureKeywordColor"
	Data.s "ASMKeywordColor", "PointerColor", "NumberColor", "StructureColor", "LabelColor", "ModuleColor"
	Data.s "OperatorColor", "SeparatorColor", "CustomKeywordColor", ""
EndDataSection
Last edited by STARGÅTE on Thu May 20, 2021 9:20 pm, edited 2 times in total.
PB 5.73 ― Win 10, 20H2 ― Ryzen 9 3900X ― Radeon RX 5600 XT ITX ― Vivaldi 4.0 ― www.unionbytes.de
Lizard - Script language for symbolic calculations and moreTypeface - Sprite-based font include/module
Post Reply