Domanda

Il codice Visual Basic non viene visualizzato correttamente con prettify.js da Google.

sullo stack overflow:

Partial Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'set page title
        Page.Title = "Something"
    End Sub

End Class

in Visual Studio...

Visual Basic in Visual Studio

Ho trovato questo in LEGGIMI documento:

Come posso specificare in quale lingua si trova il mio codice?

Non è necessario specificare la lingua poiché Prettyprint () indovinerà.È possibile specificare una lingua specificando l'estensione della lingua insieme alla classe Prettyprint come così:

<pre class="prettyprint lang-html">
  The lang-* class specifies the language file extensions.
  Supported file extensions include
    "c", "cc", "cpp", "cs", "cyc", "java", "bsh", "csh", "sh",
    "cv", "py", "perl", "pl", "pm", "rb", "js",
    "html", "html", "xhtml", "xml", "xsl".
</pre>

Non vedo lang-vb O lang-base opzione.Qualcuno sa se ne esiste uno come componente aggiuntivo?


Nota:Questo è legato a Blocchi di codice VB.NET suggerimento per Stack Overflow.

È stato utile?

Soluzione

/MODIFICARE:Ho riscritto tutto il messaggio.

Di seguito è riportata una soluzione abbastanza completa al problema dell'evidenziazione VB.Se SO non ha niente di meglio, Per favore usarlo.L'evidenziazione della sintassi VB è decisamente desiderata.

Ho anche aggiunto un esempio di codice con alcuni valori letterali di codice complessi che vengono evidenziati correttamente.Tuttavia, non ho nemmeno provato a ottenere XLinq correttamente.Potrebbe ancora funzionare, però.IL elenco di parole chiave è preso da MSDN.Le parole chiave contestuali non sono incluse.Conoscevi il GetXmlNamespace operatore?

L'algoritmo conosce i caratteri di tipo letterale.Dovrebbe anche essere in grado di gestire caratteri di tipo identificatore ma non li ho testati.Tieni presente che il codice funziona HTML.Di conseguenza, &, < e > devono essere letti come entità con nome (!), non come singoli caratteri.

Ci scusiamo per la lunga regex.

var highlightVB = function(code) {
    var regex = /("(?:""|[^"])+"c?)|('.*$)|#.+?#|(&amp;[HO])?\d+(\.\d*)?(e[+-]?\d+)?U?([SILDFR%@!#]|&amp;)?|\.\d+[FR!#]?|\s+|\w+|&amp;|&lt;|&gt;|([-+*/\\^$@!#%&<>()\[\]{}.,:=]+)/gi;

    var lines = code.split("\n");
    for (var i = 0; i < lines.length; i++) {
        var line = lines[i];

        var tokens;
        var result = "";

        while (tokens = regex.exec(line)) {
            var tok = getToken(tokens);
            switch (tok.charAt(0)) {
                case '"':
                    if (tok.charAt(tok.length - 1) == "c")
                        result += span("char", tok);
                    else
                        result += span("string", tok);
                    break;
                case "'":
                    result += span("comment", tok);
                    break;
                case '#':
                    result += span("date", tok);
                    break;
                default:
                    var c1 = tok.charAt(0);

                    if (isDigit(c1) ||
                        tok.length > 1 && c1 == '.' && isDigit(tok.charAt(1)) ||
                        tok.length > 5 && (tok.indexOf("&amp;") == 0 &&
                        tok.charAt(5) == 'H' || tok.charAt(5) == 'O')
                    )
                        result += span("number", tok);
                    else if (isKeyword(tok))
                        result += span("keyword", tok);
                    else
                        result += tok;
                    break;
            }
        }

        lines[i] = result;
    }

    return lines.join("\n");
}

var keywords = [
    "addhandler", "addressof", "alias", "and", "andalso", "as", "boolean", "byref",
    "byte", "byval", "call", "case", "catch", "cbool", "cbyte", "cchar", "cdate",
    "cdec", "cdbl", "char", "cint", "class", "clng", "cobj", "const", "continue",
    "csbyte", "cshort", "csng", "cstr", "ctype", "cuint", "culng", "cushort", "date",
    "decimal", "declare", "default", "delegate", "dim", "directcast", "do", "double",
    "each", "else", "elseif", "end", "endif", "enum", "erase", "error", "event",
    "exit", "false", "finally", "for", "friend", "function", "get", "gettype",
    "getxmlnamespace", "global", "gosub", "goto", "handles", "if", "if",
    "implements", "imports", "in", "inherits", "integer", "interface", "is", "isnot",
    "let", "lib", "like", "long", "loop", "me", "mod", "module", "mustinherit",
    "mustoverride", "mybase", "myclass", "namespace", "narrowing", "new", "next",
    "not", "nothing", "notinheritable", "notoverridable", "object", "of", "on",
    "operator", "option", "optional", "or", "orelse", "overloads", "overridable",
    "overrides", "paramarray", "partial", "private", "property", "protected",
    "public", "raiseevent", "readonly", "redim", "rem", "removehandler", "resume",
    "return", "sbyte", "select", "set", "shadows", "shared", "short", "single",
    "static", "step", "stop", "string", "structure", "sub", "synclock", "then",
    "throw", "to", "true", "try", "trycast", "typeof", "variant", "wend", "uinteger",
    "ulong", "ushort", "using", "when", "while", "widening", "with", "withevents",
    "writeonly", "xor", "#const", "#else", "#elseif", "#end", "#if"
]

var isKeyword = function(token) {
    return keywords.indexOf(token.toLowerCase()) != -1;
}

var isDigit = function(c) {
    return c >= '0' && c <= '9';
}

var getToken = function(tokens) {
    for (var i = 0; i < tokens.length; i++)
        if (tokens[i] != undefined)
            return tokens[i];
    return null;
}

var span = function(class, text) {
    return "<span class=\"" + class + "\">" + text + "</span>";
}

Codice per il test:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    'set page title
    Page.Title = "Something"
    Dim r As String = "Say ""Hello"""
    Dim i As Integer = 1234
    Dim d As Double = 1.23
    Dim s As Single = .123F
    Dim l As Long = 123L
    Dim ul As ULong = 123UL
    Dim c As Char = "x"c
    Dim h As Integer = &amp;H0
    Dim t As Date = #5/31/1993 1:15:30 PM#
    Dim f As Single = 1.32e-5F
End Sub

Altri suggerimenti

Prettify supporta i commenti VB dall'8 gennaio 2009.

Per far funzionare correttamente l'evidenziazione della sintassi vb sono necessarie tre cose;

<script type="text/javascript" src="/External/css/prettify/prettify.js"></script>
<script type="text/javascript" src="/External/css/prettify/lang-vb.js"></script>

e un blocco PRE attorno al tuo codice, ad esempio:

<PRE class="prettyprint lang-vb">
 Function SomeVB() as string
   ' do stuff
   i = i + 1
 End Function
</PRE>

Stackoverflow non include l'inclusione di lang-vb.js e la possibilità di specificare quale lingua tramite Markdown, ovvero: class="prettyprint lang-vb" ecco perché qui non funziona.

per dettagli sulla questione:Vedere il registro dei problemi di Prettify

Nel frattempo, puoi inserire un carattere di commento aggiuntivo alla fine dei tuoi commenti per farlo sembrare a posto.Per esempio:

Sub TestMethod()
    'Method body goes here'
End Sub

È inoltre necessario eseguire l'escape dei caratteri dei commenti interni nel normale modo vb:

Sub TestMethod2()
    'Here''s another comment'
End Sub

Prettify lo tratta ancora come una stringa letterale piuttosto che come un commento, ma almeno sembra a posto.

Un altro metodo che ho visto è iniziare i commenti con un extra '//, come questo:

Sub TestMethod3()
    ''// one final comment
End Sub

Quindi viene gestito come un commento, ma devi gestire i marcatori di commento in stile C

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top