public static void ApplyTheme(string source, SyntaxHighlighter highlighter, FastColoredTextBox tb)
        {
            source = Path.Combine(GlobalSettings.SettingsDir, source);
            using (var reader = XmlReader.Create(source))
            {
                while (reader.Read())
                    // Only detect start elements.
                    if (reader.IsStartElement())
                    {
                        // Get element name and switch on it.
                        switch (reader.Name)
                        {
                            case "Style":
                                // Search for the attribute name on this current node.
                                var name = reader["Name"];
                                var fontstyle = (FontStyle) Enum.Parse(typeof (FontStyle), reader["Font"]);
                                var color = reader["Color"];
                                InitStyle(name, fontstyle, GetColorFromHexVal(color), highlighter);
                                // if (reader.Read())
                                //     InitStyle(name, fontstyle, GetColorFromHexVal(color), highlighter);
                                break;

                            case "Key":
                                // Search for the attribute name on this current node.
                                InitKey(tb, reader["Name"], reader["Value"]);
                                // if (reader.Read())
                                //     KeyInit(tb, reader["Name"], reader["Value"]);
                                break;
                        }
                    }
            }
        }
        public void Highlights_csharp_code()
        {
            var code = "class Foo { int Bar() { } }";

            var highlighter = new SyntaxHighlighter();
            var result = highlighter.Highlight(code, "csharp");
            Console.WriteLine(result);

            StringAssert.StartsWith("<pre class=\"csharp\" style=\"font-family:monospace;\"><span style=\"color: #FF0000;\">class</span>", result);
        }
Beispiel #3
0
        public MainWindow()
        {
            InitializeComponent();

            CheckForIllegalCrossThreadCalls = false;

            SyntaxHighlighter highlighter = new SyntaxHighlighter(tbCode);

            highlighter.AddPattern(new PatternDefinition(new string[] { "int", "float", "String", "double", "void", "HIGH", "LOW", "INPUT", "OUTPUT" }), new SyntaxStyle(Color.LightBlue));

            highlighter.AddPattern(new PatternDefinition(new string[] { "digitalRead", "digitalWrite", "pinMode", "analogRead", "analogReference", "analogWrite", "analogReadResolution", "analogWriteResolution", "noTone", "pulseIn", "pulseInLong", "shiftIn", "shiftOut", "tone", "delay", "delayMicroseconds", "micros", "millis", "abs", "constrain", "map", "max", "min", "pow", "sq", "sqrt", "cos", "sin", "tan", "isAlpha", "isAlphaNumeric", "isAscii", "isControl", "isDigit", "isGraph", "isHexadecimalDigit", "isLowerCase", "isPrintable", "isPunct", "isSpace", "isUpperCase", "isWhitespace", "random", "randomSeed", "bit", "bitClear", "bitRead", "bitSet", "bitWrite", "highByte", "lowByte", "attachInterrupt", "detachInterrupt", "interrupts", "noInterrupts", "Serial", "Stream" }), new SyntaxStyle(Color.Orange));

            highlighter.AddPattern(new PatternDefinition(new string[] { "#include", "#define" }), new SyntaxStyle(Color.DarkOliveGreen));
        }
Beispiel #4
0
        private static void TestScenario(string grammar, HighlightRuleCollection <Token> rules, string subject, IEnumerable <HighlightedSegment <Token> > result)
        {
            var compiled = PegCompiler.Compile(new PegParser().Parse(grammar));
            var parser   = CodeCompiler.Compile <string>(compiled);

            parser.Parse(subject, null, out var lexicalElements);

            var highlighter = new SyntaxHighlighter <Token>(rules);
            var tokens      = highlighter.GetTokens(lexicalElements);

            tokens = highlighter.AddDefaultTokens(tokens, subject.Length, Token.Unknown);
            tokens = highlighter.SplitOnWhiteSpace(tokens, subject);

            Assert.That(ToAssertString(tokens), Is.EqualTo(ToAssertString(result)));
        }
Beispiel #5
0
        protected override async Task <IEnumerable <RtfItem> > GetItems()
        {
            Title     = Path;
            Thumbnail = ShellNative.GetLargeBitmapSource(Path);
            PathName  = System.IO.Path.GetFileName(Path);
            var extension = System.IO.Path.GetExtension(Path);
            var encoding  = GetEncoding();

            _syntaxHighlighter = new SyntaxHighlighter(encoding);
            if (encoding == null)
            {
                return(await Task.Run(() => _syntaxHighlighter.InitBinary(Path)));
            }
            return(await _syntaxHighlighter.Init(Path, extension));
        }
Beispiel #6
0
        public void ValidateSyntaxHighlighter_ThrowsOptionsExceptionIfSyntaxHighlighterIsInvalid()
        {
            // Arrange
            FlexiCodeBlockFactory   testSubject            = CreateFlexiCodeBlockFactory();
            const SyntaxHighlighter dummySyntaxHighlighter = (SyntaxHighlighter)9;

            // Act and assert
            OptionsException result = Assert.Throws <OptionsException>(() => testSubject.ValidateSyntaxHighlighter(dummySyntaxHighlighter));

            Assert.Equal(string.Format(Strings.OptionsException_OptionsException_InvalidOption,
                                       nameof(IFlexiCodeBlockOptions.SyntaxHighlighter),
                                       string.Format(Strings.OptionsException_Shared_ValueMustBeAValidEnumValue, dummySyntaxHighlighter,
                                                     nameof(SyntaxHighlighter))),
                         result.Message);
        }
Beispiel #7
0
        public void AfterParse_Should_Remove_Ignore_Tokens()
        {
            // Arrange
            string expectedHtml = "here is some code that mimics our beautiful C#: \n \n" +
                                  "<pre class=\"brush: java\">\npublic static void main(String args)\n{\n/* do something */\n}\n</pre>\n\n";                                       // extra \n for the tokens

            string            markup      = "here is some code that mimics our beautiful C#: [[[code lang=java|\npublic static void main(String args)\n{\n/* do something */\n}\n]]]";
            SyntaxHighlighter highlighter = new SyntaxHighlighter();

            // Act
            string html       = highlighter.BeforeParse(markup);
            string parsedHtml = highlighter.AfterParse(html);

            // Assert
            Assert.That(parsedHtml, Is.EqualTo(expectedHtml), parsedHtml);
        }
Beispiel #8
0
    /// <summary>
    /// Instantiates a prompt object. This object can be re-used for multiple invocations of <see cref="ReadLineAsync()"/>.
    /// </summary>
    /// <param name="persistentHistoryFilepath">The filepath of where to store history entries. If null, persistent history is disabled.</param>
    /// <param name="callbacks">A collection of callbacks for modifying and intercepting the prompt's behavior</param>
    /// <param name="console">The implementation of the console to use. This is mainly for ease of unit testing</param>
    /// <param name="configuration">If null, default configuration is used.</param>
    public Prompt(
        string?persistentHistoryFilepath = null,
        PromptCallbacks?callbacks        = null,
        IConsole?console = null,
        PromptConfiguration?configuration = null)
    {
        this.console = console ?? new SystemConsole();
        this.console.InitVirtualTerminalProcessing();

        this.configuration       = configuration ?? new PromptConfiguration();
        this.history             = new HistoryLog(persistentHistoryFilepath, this.configuration.KeyBindings);
        this.cancellationManager = new CancellationManager(this.console);
        this.clipboard           = (console is IConsoleWithClipboard consoleWithClipboard) ? consoleWithClipboard.Clipboard : new Clipboard();

        promptCallbacks  = callbacks ?? new PromptCallbacks();
        this.highlighter = new SyntaxHighlighter(promptCallbacks, PromptConfiguration.HasUserOptedOutFromColor);
    }
Beispiel #9
0
        public void BeforeParse_Should_Replace_Token_With_Html_Pre_Tag_And_Surround_With_Ignore_Tokens()
        {
            // Arrange
            string expectedParsedMarkup = "here is some code that mimics our beautiful C#: \n" +
                                          SyntaxHighlighter.PARSER_IGNORE_STARTTOKEN + " \n" +
                                          "<pre class=\"brush: java\">\npublic static void main(String args)\n{\n/* do something */\n}\n</pre>\n" +
                                          SyntaxHighlighter.PARSER_IGNORE_ENDTOKEN + "\n";

            string            markup      = "here is some code that mimics our beautiful C#: [[[code lang=java|\npublic static void main(String args)\n{\n/* do something */\n}\n]]]";
            SyntaxHighlighter highlighter = new SyntaxHighlighter();

            // Act
            string actualMarkup = highlighter.BeforeParse(markup);

            // Assert
            Assert.That(actualMarkup, Is.EqualTo(expectedParsedMarkup), actualMarkup);
        }
Beispiel #10
0
        /// <summary>
        /// Clears and updates the contents.
        /// </summary>
        public void Reparse()
        {
            // if no property has changed since the last parse, don't bother to reparse it.
            if (!_propertyChanged)
            {
                return;
            }

            SyntaxHighlighter.Highlight(
                SourceCode,
                Document,
                CreateLanguageInstance(SourceLanguage),
                "Loading and parsing content...");

            ScrollToHome();
            _propertyChanged = false;
        }
Beispiel #11
0
        private GeometryDrawing GetCoverageHighlightDrawing(LineResult lineResult, Geometry geometry)
        {
            switch (lineResult.Result)
            {
            case LineResult.CoverageResultType.Covered:
                return(SyntaxHighlighter.CreateCoveredHighlight(geometry));

            case LineResult.CoverageResultType.PartCovered:
                return(SyntaxHighlighter.CreatePartCoveredHighlight(geometry));

            case LineResult.CoverageResultType.UnCovered:
                return(SyntaxHighlighter.CreateUnCoveredHighlight(geometry));

            default:
                throw new NotSupportedException("Coverage result type is not one of the supported values");
            }
        }
Beispiel #12
0
 /// <summary>
 ///     Default Constructor
 /// </summary>
 public Editor()
 {
     InitializeComponent();
     InitEvents();
     codebox.Dock = DockStyle.Fill;
     Highlighter = new SyntaxHighlighter();
     InitSettings();
     var snipthread = new Thread(LoadSnippets);
     if (Globals.Snippets == null)
     {
         snipthread.SetApartmentState(ApartmentState.STA);
         snipthread.Start();
         snipthread.Join();
     }
     ThreadPool.QueueUserWorkItem(delegate { Shortcuts = GetDictionary(); });
     if (SyntaxHighlighter.LoadedSyntaxes.Any()) return;
     Highlighter.LoadAllSyntaxes();
 }
Beispiel #13
0
    private void Update()
    {
        if (codeToDisplay.IsActive() == true) // If input console is active
        {
            if (remainingTimeBtwInputs <= 0)  // If players are allowed to input
            {
                TextInput();
                SpecialKeysInput();
            }
            else
            {
                remainingTimeBtwInputs -= Time.deltaTime;
            }

            HandleCaret(codeString); // Blink caret
        }

        codeToDisplay.text = SyntaxHighlighter.HighlightCode(codeString, codeTheme); // Highlight code
    }
Beispiel #14
0
 private FlexiCodeBlock CreateFlexiCodeBlock(string blockName  = default,
                                             string title      = default,
                                             string copyIcon   = default,
                                             bool renderHeader = true,
                                             string language   = default,
                                             string code       = default,
                                             int codeNumLines  = default,
                                             SyntaxHighlighter syntaxHighlighter = default,
                                             ReadOnlyCollection <NumberedLineRange> lineNumbers = default,
                                             string omittedLinesIcon = default,
                                             ReadOnlyCollection <LineRange> highlightedLines = default,
                                             ReadOnlyCollection <Phrase> highlightedPhrases  = default,
                                             FlexiCodeBlockRenderingMode renderingMode       = default,
                                             ReadOnlyDictionary <string, string> attributes  = default,
                                             BlockParser blockParser = default)
 {
     return(new FlexiCodeBlock(blockName, title, copyIcon, renderHeader, language, code, codeNumLines, syntaxHighlighter, lineNumbers,
                               omittedLinesIcon, highlightedLines, highlightedPhrases, renderingMode, attributes, blockParser));
 }
Beispiel #15
0
        /// <summary>
        /// Tells the instance that the <see cref="IContentAssistTextBox.ContentSyntaxValidator"/> property has been changed.
        /// </summary>
        /// <param name="validator">New validator</param>
        protected virtual void OnContentSyntaxValidatorChanged(IContentSyntaxValidator validator)
        {
            if (validator == null)
            {
                return;
            }

            // Lazy initialize resources
            if (iErrorLineStyle == null)
            {
                SyntaxHighlighter.AddResilientStyle(iErrorLineStyle   = new WavyLineStyle(255, Color.Red));
                SyntaxHighlighter.AddResilientStyle(iWarningLineStyle = new WavyLineStyle(255, Color.Yellow));
                SyntaxHighlighter.AddResilientStyle(iInfoLineStyle    = new WavyLineStyle(255, Color.Green));

                iErrorBitmap   = LoadBitmap("Error-32.png");
                iWarningBitmap = LoadBitmap("Warning-32.png");
                iInfoBitmap    = LoadBitmap("Info-32.png");
            }
        }
Beispiel #16
0
        private void generateObjects()
        {
            //generate syntax highlighter
            syntaxHighlighter = new SyntaxHighlighter(htmlBox);
            syntaxHighlighter.AddPattern(new PatternDefinition("<html>", "<html", "<link", "<head>", "<body>", "<a href", "<title>", "<meta", "<div", "<header", "<li>", "<ul", "<ul>", "<nav", "<section", "<article>", "<img", "<h1>", "<h2>", "<h3>", "<b>", "<u>", "<p>", "<i>", "<button", "<button>", "</html>", "</head>", "</body>", "</title>", "</div>", "</header>", "</li>", "</ul>", "</nav>", "</section>", "</article>", "</h1>", "</h2>", "</h3>", "</b>", "</u>", "</i>", "</p>", "/>", "</a>", "</button>", ">"),
                                         new SyntaxStyle(Color.Blue));//Objects

            syntaxHighlighter.AddPattern(new PatternDefinition(new Regex(@"<!--(.|[\r\n])*?\-->?", RegexOptions.Multiline | RegexOptions.Compiled)),
                                         new SyntaxStyle(Color.Green));//Comments

            syntaxHighlighter.AddPattern(new PatternDefinition("href", "onclick", "id", "class", "src", "rel", "charset", "lang", "href"),
                                         new SyntaxStyle(Color.Red));//atributes

            //Generate Preview
            browser          = new webControl();
            browser.Location = new Point(527, 49);
            browser.Size     = new Size(474, 669);
            browser.Anchor   = (AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right);
            this.Controls.Add(browser);
            browser.Navigate("about:blank");

            //Generate File Save Dialog
            saveDialog                  = new SaveFileDialog();
            saveDialog.DefaultExt       = ".html";
            saveDialog.Filter           = "HTML Files|*.html;*.htm|CSS Files|*.css|PHP Files|*.php|JavaScript Files|*.js|All Files|*.*";
            saveDialog.InitialDirectory = initialDirectory;
            saveDialog.FileName         = "";

            //Generate File Open Dialog
            openDialog                  = new OpenFileDialog();
            openDialog.DefaultExt       = ".html";
            openDialog.Filter           = "HTML Files|*.html;*.htm|CSS Files|*.css|PHP Files|*.php|JavaScript Files|*.js|All Files|*.*";
            openDialog.InitialDirectory = initialDirectory;
            openDialog.FileName         = "";

            LineNumbers();
            lineNumberBoxHTML.BackColor = Color.White;
            lineNumberBoxCSS.BackColor  = Color.White;

            //generate font box
            fontChooser = new FontDialog();
        }
Beispiel #17
0
        private void tb_TextChangedDelayed(object sender, TextChangedEventArgs e)
        {
            var tb = (FastColoredTextBox)sender;

            //highlight html
            //tb.SyntaxHighlighter.InitStyleSchema(Language.HTML);
            tb.SyntaxHighlighter.SyntaxHighlight(tb.Range);
            tb.Range.ClearFoldingMarkers();
            //find PHP fragments
            SyntaxHighlighter phpSource = SyntaxHighlighter.CreateSyntaxHighlighter(tb, Language.PHP);

            foreach (var r in tb.GetRanges(@"<\?php.*?\?>", RegexOptions.Singleline))
            {
                //remove HTML highlighting from this fragment
                r.ClearStyle(StyleIndex.All);
                //do PHP highlighting
                //tb.SyntaxHighlighter.InitStyleSchema(Language.PHP);
                phpSource.SyntaxHighlight(r);
            }
        }
        /// <summary>
        /// this is the main form of Graphical programming Language.
        /// </summary>
        public Form1()
        {
            InitializeComponent();
            //its for current date
            lblTime.Text = DateTime.Now.ToLongTimeString();
            var syntaxHighlighter = new SyntaxHighlighter(txtInput);

            // multi-line comments

            syntaxHighlighter.AddPattern(new PatternDefinition("circle", "rectangle", "int", "var"), new SyntaxStyle(Color.Blue));
            // keywords2
            syntaxHighlighter.AddPattern(new PatternDefinition("triangle", "3drectangle", "int", "var"), new SyntaxStyle(Color.Red));
            // keywords2
            syntaxHighlighter.AddPattern(new PatternDefinition("loop", "endloop", "int", "var"), new SyntaxStyle(Color.Purple));
            // keywords2
            syntaxHighlighter.AddPattern(new PatternDefinition("counter", "int", "var"), new SyntaxStyle(Color.Green));
            // keywords2
            syntaxHighlighter.AddPattern(new PatternDefinition("moveto", "radius", "int", "var"), new SyntaxStyle(Color.Pink));
            // keywords2
        }
Beispiel #19
0
        /// <summary>
        /// Handles whenever the text displayed in the view changes by adding the adornment to any
        /// reformatted lines
        /// </summary>
        /// <remarks>
        /// <para>
        /// This event is raised whenever the rendered text displayed in the <see cref="ITextView"/> changes.
        /// </para>
        /// <para>
        /// It is raised whenever the view does a layout (which happens when
        /// DisplayTextLineContainingBufferPosition is called or in response to text or
        /// classification changes).
        /// </para>
        /// <para>It is also raised whenever the view scrolls horizontally or when its size changes.</para>
        /// </remarks>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event arguments.</param>
        internal void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e)
        {
            if (!CoverageResultsProvider.ShowSyntaxHighlighting || !this.HasFileName)
            {
                return;
            }

            this.CoverageResultsForThisFile = CoverageResultsProvider.Instance?.CoverageResults?.FindFile(this.TextDocument.FilePath);
            if (this.CoverageResultsForThisFile == null)
            {
                return;
            }

            var highlighter = new SyntaxHighlighter();

            foreach (var line in e.NewOrReformattedLines)
            {
                this.CreateVisuals(line, highlighter);
            }
        }
Beispiel #20
0
        /// <summary>
        /// Syntax Highlighter Implementation Successfully
        /// </summary>
        public Form1()
        {
            InitializeComponent();

            var syntaxHighlighter = new SyntaxHighlighter(richTxt);


            syntaxHighlighter.AddPattern(new PatternDefinition(@"\d+\.\d+|\d+"), new SyntaxStyle(Color.Black));

            syntaxHighlighter.AddPattern(new PatternDefinition(@"\""([^""]|\""\"")+\"""), new SyntaxStyle(Color.Red));

            syntaxHighlighter.AddPattern(new PatternDefinition(@"\'([^']|\'\')+\'"), new SyntaxStyle(Color.Salmon));

            syntaxHighlighter.AddPattern(new PatternDefinition("circle", "rectangle", "int", "var"), new SyntaxStyle(Color.DeepSkyBlue));
            syntaxHighlighter.AddPattern(new PatternDefinition("polygon", "int", "var"), new SyntaxStyle(Color.Red));
            syntaxHighlighter.AddPattern(new PatternDefinition("triangle", "int", "var"), new SyntaxStyle(Color.CornflowerBlue));

            syntaxHighlighter.AddPattern(new PatternDefinition("radius", "if", "int", "var"), new SyntaxStyle(Color.Blue));

            syntaxHighlighter.AddPattern(new PatternDefinition("drawto", "moveto", "3drectangle"), new SyntaxStyle(Color.Crimson));
        }
        public RegisterBugSolution()
        {
            InitializeComponent();
            var syntaxHighlighter = new SyntaxHighlighter(txtCode);

            syntaxHighlighter.AddPattern(new PatternDefinition(new Regex(@"/\*(.|[\r\n])*?\*/", RegexOptions.Multiline | RegexOptions.Compiled)), new SyntaxStyle(Color.DarkSeaGreen, false, true));

            syntaxHighlighter.AddPattern(new PatternDefinition(new Regex(@"//.*?$", RegexOptions.Multiline | RegexOptions.Compiled)), new SyntaxStyle(Color.Green, false, true));

            syntaxHighlighter.AddPattern(new PatternDefinition(@"\d+\.\d+|\d+"), new SyntaxStyle(Color.Purple));

            syntaxHighlighter.AddPattern(new PatternDefinition(@"\""([^""]|\""\"")+\"""), new SyntaxStyle(Color.Red));

            syntaxHighlighter.AddPattern(new PatternDefinition(@"\'([^']|\'\')+\'"), new SyntaxStyle(Color.Salmon));

            syntaxHighlighter.AddPattern(new PatternDefinition("for", "foreach", "int", "var"), new SyntaxStyle(Color.Blue));

            syntaxHighlighter.AddPattern(new CaseInsensitivePatternDefinition("public", "partial", "class", "void"), new SyntaxStyle(Color.Navy, true, false));

            syntaxHighlighter.AddPattern(new PatternDefinition("+", "-", ">", "<", "&", "|"), new SyntaxStyle(Color.Brown));
        }
Beispiel #22
0
        /// <summary>
        ///     Default Constructor
        /// </summary>
        public Editor()
        {
            InitializeComponent();
            InitEvents();
            codebox.Dock = DockStyle.Fill;
            Highlighter  = new SyntaxHighlighter();
            InitSettings();
            var snipthread = new Thread(LoadSnippets);

            if (Globals.Snippets == null)
            {
                snipthread.SetApartmentState(ApartmentState.STA);
                snipthread.Start();
                snipthread.Join();
            }
            ThreadPool.QueueUserWorkItem(delegate { Shortcuts = GetDictionary(); });
            if (SyntaxHighlighter.LoadedSyntaxes.Any())
            {
                return;
            }
            Highlighter.LoadAllSyntaxes();
        }
Beispiel #23
0
    public string FormattedInfoString()
    {
        string info = "";

        info += SyntaxHighlighter.CreateColouredText(descriptionCol, description) + "\n";

        if (constants.Count > 0)
        {
            info += "\n" + SyntaxHighlighter.CreateColouredText(headerCol, "Constants:") + "\n";
            for (int i = 0; i < constants.Count; i++)
            {
                info += constants[i].name + " = " + constants[i].value;
                info += "\n";
            }
        }

        if (variables.Count > 0)
        {
            info += "\n" + SyntaxHighlighter.CreateColouredText(headerCol, "Variables:") + "\n";
            for (int i = 0; i < variables.Count; i++)
            {
                info += variables[i];
                info += "\n";
            }
        }

        if (outputs.Count > 0)
        {
            info += "\n" + SyntaxHighlighter.CreateColouredText(headerCol, "Outputs:") + "\n";
            for (int i = 0; i < outputs.Count; i++)
            {
                string paramName = (outputs[i].paramSize > 0) ? outputs[i].paramLabel : "";
                info += outputs[i].name + "(" + paramName + ")";
                info += "\n";
            }
        }

        return(info);
    }
        public MainForm()
        {
            InitializeComponent();
            var syntaxHighlighter = new SyntaxHighlighter(rtbInput);

            // multi-line comments
            syntaxHighlighter.AddPattern(new PatternDefinition(new Regex(@"/\*(.|[\r\n])*?\*/", RegexOptions.Multiline | RegexOptions.Compiled)), new SyntaxStyle(Color.DarkSeaGreen, false, true));
            // singlie-line comments
            syntaxHighlighter.AddPattern(new PatternDefinition(new Regex(@"//.*?$", RegexOptions.Multiline | RegexOptions.Compiled)), new SyntaxStyle(Color.Green, false, true));
            // numbers
            syntaxHighlighter.AddPattern(new PatternDefinition(@"\d+\.\d+|\d+"), new SyntaxStyle(Color.Purple));
            // double quote strings
            syntaxHighlighter.AddPattern(new PatternDefinition(@"\""([^""]|\""\"")+\"""), new SyntaxStyle(Color.Red));
            // single quote strings
            syntaxHighlighter.AddPattern(new PatternDefinition(@"\'([^']|\'\')+\'"), new SyntaxStyle(Color.Salmon));
            // keywords1
            syntaxHighlighter.AddPattern(new PatternDefinition("for", "foreach", "int", "var"), new SyntaxStyle(Color.Blue));
            // keywords2
            syntaxHighlighter.AddPattern(new CaseInsensitivePatternDefinition("public", "partial", "class", "void"), new SyntaxStyle(Color.Navy, true, false));
            // operators
            syntaxHighlighter.AddPattern(new PatternDefinition("+", "-", ">", "<", "&", "|"), new SyntaxStyle(Color.Brown));
        }
Beispiel #25
0
 /// <summary>
 /// Highlight words from KeyWords.
 /// </summary>
 private void UpdateDqlSyntax()
 {
     try
     {
         var syntaxHighlighter = new SyntaxHighlighter(this.txtScript);
         // zero strings
         syntaxHighlighter.AddPattern(new PatternDefinition("''"), new SyntaxStyle(Color.Red));
         // single quote strings
         syntaxHighlighter.AddPattern(new PatternDefinition(@"\'([^']|\'\')+\'"), new SyntaxStyle(Color.Red));
         // keywords1
         syntaxHighlighter.AddPattern(new PatternDefinition("UNION", "UPDATE", "SET", "WHERE", "GO", "APPEND", "INSERT", "INTO", "TRUNCATE", "REMOVE", "SELECT", "FROM", "TYPE", "FOLDER", "CABINET", "ORDER BY", "DESC", "ASC", "GROUP BY", "ALTER", "ADD", "DROP", "GROUP"), new SyntaxStyle(Color.Blue));
         // keywords2
         syntaxHighlighter.AddPattern(new PatternDefinition("OBJECTS", "objects"), new SyntaxStyle(Color.Green));
         // functions
         syntaxHighlighter.AddPattern(new PatternDefinition("UPPER", "LOWER", "SUBSTR", "COUNT", "MIN", "MAX", "AVG", "SUM", "DATEDIFF", "DATEADD", "DATEFLOOR", "DATETOSTRING", "ID", "MFILE_URL"), new SyntaxStyle(Color.Fuchsia));
         // operators
         syntaxHighlighter.AddPattern(new PatternDefinition("+", "-", ">", "<", "&", "|", "*", "**", "!", "=", "AND", "OR", "SOME", "ALL", "ANY", "LIKE", "NOT", "NULL", "NULLDATE", "NULLSTRING", "NULLINT", "IN", "EXISTS"), new SyntaxStyle(Color.Gray));
     }
     catch (Exception ex)
     {
         ErrorHandler.DisplayMessage(ex);
     }
 }
    // Update is called once per frame
    void Update()
    {
        if (!active)
        {
            return;
        }


        HandleTextInput();
        HandleSpecialInput();
        SetLineNumbers(); //Slow


        if (codeUI != null && caret != null)
        {
            SetCaret(code);
        }


        string formattedCode = FormatIndenting();

        codeUI.text = SyntaxHighlighter.HighlightCode(formattedCode, syntaxTheme);
    }
Beispiel #27
0
        private void ShowCoverageForWholeFile()
        {
            if (!CoverageResultsProvider.ShowSyntaxHighlighting || !this.HasFileName)
            {
                return;
            }

            // update all lines
            this.CoverageResultsForThisFile = CoverageResultsProvider.Instance?.CoverageResults?.FindFile(this.TextDocument.FilePath);

            if (this.CoverageResultsForThisFile == null)
            {
                return;
            }

            var highlighter   = new SyntaxHighlighter();
            var textViewLines = this.view.TextViewLines;

            foreach (var line in textViewLines)
            {
                this.CreateVisuals(line, highlighter);
            }
        }
Beispiel #28
0
 internal static Section[] ParseMultiLine(string code) => SyntaxHighlighter.Optimize.Invoke(SyntaxHighlighter.ParseCode(code));
Beispiel #29
0
        internal static (Section[] Sections, bool IsBlockComment) ParseSingleLine(string code, bool IsBlockComment = false)
        {
            Tuple <Section[], bool> res = SyntaxHighlighter.ParseLine(code, 0, IsBlockComment);

            return(SyntaxHighlighter.Optimize.Invoke(res.Item1), res.Item2);
        }
Beispiel #30
0
        internal virtual void WriteStandard(HtmlRenderer htmlRenderer, FlexiCodeBlock flexiCodeBlock)
        {
            ReadOnlyDictionary <string, string>    attributes         = flexiCodeBlock.Attributes;
            ReadOnlyCollection <NumberedLineRange> lineNumbers        = flexiCodeBlock.LineNumbers;
            ReadOnlyCollection <LineRange>         highlightedLines   = flexiCodeBlock.HighlightedLines;
            ReadOnlyCollection <Phrase>            highlightedPhrases = flexiCodeBlock.HighlightedPhrases;
            int    codeNumLines                 = flexiCodeBlock.CodeNumLines;
            string blockName                    = flexiCodeBlock.BlockName,
                   title                        = flexiCodeBlock.Title,
                   copyIcon                     = flexiCodeBlock.CopyIcon,
                   language                     = flexiCodeBlock.Language,
                   omittedLinesIcon             = flexiCodeBlock.OmittedLinesIcon,
                   code                         = flexiCodeBlock.Code;
            SyntaxHighlighter syntaxHighlighter = flexiCodeBlock.SyntaxHighlighter;
            bool hasTitle                       = !string.IsNullOrWhiteSpace(title),
                 hasCopyIcon                    = !string.IsNullOrWhiteSpace(copyIcon),
                 hasLanguage                    = !string.IsNullOrWhiteSpace(language),
                 hasSyntaxHighlights            = syntaxHighlighter != SyntaxHighlighter.None && hasLanguage,
                 hasLineNumbers                 = lineNumbers?.Count > 0,
                 hasOmittedLinesIcon            = !string.IsNullOrWhiteSpace(omittedLinesIcon),
                 hasHighlightedLines            = highlightedLines?.Count > 0,
                 hasHighlightedPhrases          = highlightedPhrases?.Count > 0,
                 hasHeader                      = flexiCodeBlock.RenderHeader;

            // Root element
            htmlRenderer.
            Write("<div class=\"").
            Write(blockName).
            WriteHasFeatureClass(hasTitle, blockName, "title").
            WriteHasFeatureClass(hasCopyIcon, blockName, "copy-icon").
            WriteHasFeatureClass(hasHeader, blockName, "header").
            WriteBlockKeyValueModifierClass(hasLanguage, blockName, "language", language).
            WriteHasFeatureClass(hasSyntaxHighlights, blockName, "syntax-highlights").
            WriteHasFeatureClass(hasLineNumbers, blockName, "line-numbers").
            WriteHasFeatureClass(hasOmittedLinesIcon, blockName, "omitted-lines-icon").
            WriteHasFeatureClass(hasHighlightedLines, blockName, "highlighted-lines").
            WriteHasFeatureClass(hasHighlightedPhrases, blockName, "highlighted-phrases").
            WriteAttributeValue(attributes, "class").
            Write('"').
            WriteAttributesExcept(attributes, "class").
            WriteLine(">");

            // Header
            if (hasHeader)
            {
                htmlRenderer.
                WriteStartTagLine("header", blockName, "header").
                WriteElementLine(hasTitle, "span", blockName, "title", title).
                WriteStartTagLineWithAttributes("button", blockName, "copy-button", "aria-label=\"Copy code\"").
                WriteHtmlFragmentLine(hasCopyIcon, copyIcon, blockName, "copy-icon").
                WriteEndTagLine("button").
                WriteEndTagLine("header");
            }

            // Code
            htmlRenderer.
            WriteStartTag("pre", blockName, "pre").
            WriteStartTag("code", blockName, "code");

            // Code - Syntax Highlighting
            if (hasSyntaxHighlights)
            {
                // All code up the stack from HighlightAsync calls ConfigureAwait(false), so there is no need to run these calls in the thread pool.
                // Use GetAwaiter and GetResult to avoid an AggregateException - https://blog.stephencleary.com/2014/12/a-tour-of-task-part-6-results.html
                code = (syntaxHighlighter == SyntaxHighlighter.HighlightJS ? _highlightJSService.HighlightAsync(code, language) : _prismService.HighlightAsync(code, language)).GetAwaiter().GetResult();
            }

            // If there is no need for code embellishements
            if (!hasLineNumbers && !hasHighlightedLines && !hasHighlightedPhrases)
            {
                if (code?.Length > 0)
                {
                    if (hasSyntaxHighlights)
                    {
                        htmlRenderer.Write(code); // Already escaped
                    }
                    else
                    {
                        htmlRenderer.WriteEscape(code);
                    }

                    htmlRenderer.
                    WriteLine();     // \n before </code> for consistency with CommonMark
                }

                htmlRenderer.
                WriteLine("</code></pre>").
                WriteLine("</div>");

                return;
            }

            // Code - Prepare to render line numbers
            bool currentLineHasLineNumber             = false;
            NumberedLineRange currentLineNumberRange  = default;
            int currentLineNumberToRender             = 0,
                currentUnrenderedRangeFirstLineNumber = 1;

            List <NumberedLineRange> .Enumerator lineNumbersEnumerator = default;
            if (hasLineNumbers)
            {
                lineNumbersEnumerator = (List <NumberedLineRange> .Enumerator)lineNumbers.GetEnumerator();
                lineNumbersEnumerator.MoveNext();
                currentLineNumberRange    = lineNumbersEnumerator.Current;
                currentLineNumberToRender = currentLineNumberRange.StartNumber;
            }

            // Code - Prepare to highlight lines
            bool      currentLineIsHighlighted    = false;
            LineRange currentHighlightedLineRange = default;

            List <LineRange> .Enumerator highlightedLinesEnumerator = default;
            if (hasHighlightedLines)
            {
                highlightedLinesEnumerator = (List <LineRange> .Enumerator)highlightedLines.GetEnumerator();
                highlightedLinesEnumerator.MoveNext();
                currentHighlightedLineRange = highlightedLinesEnumerator.Current;
                currentLineIsHighlighted    = currentHighlightedLineRange.GetRelativePosition(1, codeNumLines) == 0;
            }

            // Code - Prepare to highlight phrases
            bool   inHighlightedPhrase      = false;
            int    currentCodeCharIndex     = 0; // Index ignoring HTML elements
            Phrase currentHighlightedPhrase = default;

            List <Phrase> .Enumerator highlightedPhrasesEnumerator = default;
            if (hasHighlightedPhrases)
            {
                highlightedPhrasesEnumerator = (List <Phrase> .Enumerator)highlightedPhrases.GetEnumerator();
                highlightedPhrasesEnumerator.MoveNext();
                currentHighlightedPhrase = highlightedPhrasesEnumerator.Current;
            }

            // Code - Write Embellished
            // We have to iterate over every character so we can write elements for highlighted phrases.
            // Writing elements for highlighted phrases involves flattening intersecting elements, e.g <phrase>xxx<syntax>xxx</phrase>xxx</syntax>
            // is flattened to <phrase>xxx<syntax>xxx</syntax></phrase><syntax>xxx</syntax>. Flattening is the reason for the dense nature of the following code.
            // While dense, the following code is efficient, requiring only 1 pass and generating no intermediate strings/objects.
            var        openElements = new Stack <Element>();
            var        pendingElements = new Stack <Element>();
            TextWriter textWriter = htmlRenderer.Writer; // Faster to write chars directly
            bool       previousLineHasLineElement = false, currentLineHasLineElement = hasLineNumbers || currentLineIsHighlighted;
            int        codeLength        = code.Length,
                       currentLineNumber = 1,
                       i = -1; // Starting from -1 is necessary for HandleLineStart
            char currentChar;

            HandleLineStart();
            for (i = 0; i < codeLength; i++)
            {
                currentChar = code[i];

                if (hasSyntaxHighlights && currentChar == '<') // Syntax element tags
                {
                    HandleSyntaxElementTag();
                    continue;
                }

                HandlePhraseStart();

                if (currentChar == '\r' || currentChar == '\n')
                {
                    HandleEndOfLineChar();
                }
                else if (!hasSyntaxHighlights) // If code has not been syntax highlighted, it may have unescaped characters
                {
                    WriteUnescaped();
                }
                else
                {
                    WriteEscaped();
                }

                HandlePhraseEnd();
                currentCodeCharIndex++;
            }
            HandleLineEnd();

            htmlRenderer.
            WriteLine().
            WriteLine("</code></pre>").
            WriteLine("</div>");

            void HandleSyntaxElementTag()
            {
                if (code[i + 1] == '/')
                {
                    WriteEndTag();
                    Element lastElement = openElements.Pop();
                    if (lastElement.Type != 0) // Last element is a highlighted phrase element, only one such element can be open at a time
                    {
                        WriteEndTag();
                        WriteStartTag("__highlighted-phrase");
                        openElements.Pop();
                        openElements.Push(lastElement);
                    }

                    i += 6; // Skip end tag
                }
                else
                {
                    HandlePhraseStart();                      // If a phrase starts at the current index, write the phrase start element first to minimize splitting

                    for (int j = i + 15; j < codeLength; j++) // 16 is the min number of characters in a start tag: <span class="x">
                    {
                        if (code[j] == '>')
                        {
                            int length = j - i + 1;
                            openElements.Push(new Element(i, length));
                            htmlRenderer.Write(code, i, length);
                            i = j;
                            break;
                        }
                    }
                }
            }

            void HandlePhraseStart()
            {
                if (hasHighlightedPhrases &&
                    !inHighlightedPhrase &&
                    currentHighlightedPhrase?.Start == currentCodeCharIndex)
                {
                    inHighlightedPhrase = true;
                    openElements.Push(new Element(1));
                    WriteStartTag("__highlighted-phrase");
                }
            }

            void HandlePhraseEnd()
            {
                if (inHighlightedPhrase &&
                    currentHighlightedPhrase?.End == currentCodeCharIndex)
                {
                    // Find next phrase
                    do
                    {
                        if (highlightedPhrasesEnumerator.MoveNext())
                        {
                            currentHighlightedPhrase = highlightedPhrasesEnumerator.Current;
                        }
                        else
                        {
                            currentHighlightedPhrase = null;
                            break;
                        }
                    }while (currentHighlightedPhrase.End <= currentCodeCharIndex); // If two phrases have the same start index, the longer one is ordered before the shorter one

                    // Write end
                    if (currentHighlightedPhrase == null || currentHighlightedPhrase.Start > currentCodeCharIndex + 1) // Ignore overlapping and adjacent phrases so they get combined
                    {
                        inHighlightedPhrase = false;

                        if (hasSyntaxHighlights)
                        {
                            // If syntax elements end at the same code index, close them first so that we don't end up with empty elements
                            int nextIndex = i + 1;
                            while (nextIndex < codeLength && code[nextIndex] == '<' && code[nextIndex + 1] == '/')
                            {
                                WriteEndTag();
                                if (openElements.Pop().Type == 1)
                                {
                                    return;
                                }
                                i        += 7;
                                nextIndex = i + 1;
                            }
                        }

                        while (openElements.Count > 0)
                        {
                            WriteEndTag();
                            Element element = openElements.Pop();
                            if (element.Type == 1)
                            {
                                break;
                            }
                            else
                            {
                                pendingElements.Push(element);
                            }
                        }

                        while (pendingElements.Count > 0)
                        {
                            Element element = pendingElements.Pop();
                            htmlRenderer.Write(code, element.StartIndex, element.Length);
                            openElements.Push(element);
                        }
                    }
                }
            }

            void HandleEndOfLineChar()
            {
                int nextIndex;

                if (currentChar == '\r' && (nextIndex = i + 1) < codeLength && code[nextIndex] == '\n')
                {
                    HandlePhraseEnd(); // If a phrase ends at \r, allow it to end

                    i = nextIndex;
                    currentCodeCharIndex++;
                }

                HandleLineEnd();
                textWriter.WriteLine();
                HandleLineStart();
            }

            void HandleLineStart()
            {
                // Prefix element
                if (hasLineNumbers)
                {
                    WriteStartTag("__line-prefix");

                    int relativePosition = -1;
                    if (currentLineNumberRange != null)
                    {
                        relativePosition = currentLineNumberRange.GetRelativePosition(currentLineNumber, codeNumLines);
                        if (relativePosition == -1)
                        {
                            currentUnrenderedRangeFirstLineNumber = currentLineNumberToRender;
                            if (lineNumbersEnumerator.MoveNext())
                            {
                                currentLineNumberRange    = lineNumbersEnumerator.Current;
                                currentLineNumberToRender = currentLineNumberRange.StartNumber;
                                relativePosition          = currentLineNumberRange.GetRelativePosition(currentLineNumber, codeNumLines);
                            }
                            else
                            {
                                currentLineNumberRange = null;
                            }
                        }
                    }

                    if (currentLineHasLineNumber = relativePosition == 0)
                    {
                        textWriter.Write(currentLineNumberToRender++);
                    }
                    else
                    {
                        htmlRenderer.WriteHtmlFragment(hasOmittedLinesIcon, omittedLinesIcon, blockName, "omitted-lines-icon");
                    }

                    WriteEndTag();
                }

                // Write line element start tag
                if (currentLineHasLineElement)
                {
                    textWriter.Write("<span class=\"");
                    textWriter.Write(blockName);
                    textWriter.Write("__line");

                    if (currentLineIsHighlighted)
                    {
                        textWriter.Write(' ');
                        textWriter.Write(blockName);
                        textWriter.Write("__line_highlighted");
                    }

                    bool representsOmittedLines = hasLineNumbers && !currentLineHasLineNumber;
                    if (representsOmittedLines)
                    {
                        textWriter.Write(' ');
                        textWriter.Write(blockName);
                        textWriter.Write("__line_omitted-lines");
                    }

                    textWriter.Write("\">");

                    openElements.Push(new Element(2));

                    // Write omitted lines notice
                    char nextChar;
                    int  nextIndex;
                    if (representsOmittedLines &&
                        // These conditions check whether the line is empty
                        ((nextIndex = i + 1) == codeLength ||
                         (nextChar = code[nextIndex]) == '\n' ||
                         nextChar == '\r'))
                    {
                        // TODO if currentUnrenderedRangeFirstLineNumber > currentLineNumberToRender.
                        // Also, consider making notices customizable through FlexiCodeBlockOptions
                        int currentUnrenderedRangeLastLineNumber = currentLineNumberToRender - 1;
                        if (currentUnrenderedRangeFirstLineNumber == currentUnrenderedRangeLastLineNumber)
                        {
                            textWriter.Write("Line {0} omitted for brevity", currentUnrenderedRangeLastLineNumber);
                        }
                        else
                        {
                            object firstArg, secondArg;
                            if (currentLineNumberRange == null) // Till end of document
                            {
                                firstArg  = currentUnrenderedRangeFirstLineNumber;
                                secondArg = "the end";
                            }
                            else
                            {
                                firstArg  = currentUnrenderedRangeFirstLineNumber;
                                secondArg = currentUnrenderedRangeLastLineNumber;
                            }

                            textWriter.Write("Lines {0} to {1} omitted for brevity", firstArg, secondArg);
                        }
                    }
                }

                // Reopen pending elements
                if (currentLineHasLineElement || previousLineHasLineElement)
                {
                    while (pendingElements.Count > 0)
                    {
                        Element element = pendingElements.Pop();
                        if (element.Type == 0)
                        {
                            htmlRenderer.Write(code, element.StartIndex, element.Length);
                        }
                        else
                        {
                            WriteStartTag("__highlighted-phrase");
                        }

                        openElements.Push(element);
                    }
                }
            }

            void HandleLineEnd()
            {
                // Increment line number
                currentLineNumber++;

                // Update currentLineIsHighlighted
                if (currentHighlightedLineRange != null)
                {
                    int relativePosition = currentHighlightedLineRange.GetRelativePosition(currentLineNumber, codeNumLines);
                    if (relativePosition == -1)
                    {
                        if (highlightedLinesEnumerator.MoveNext())
                        {
                            currentHighlightedLineRange = highlightedLinesEnumerator.Current;
                            relativePosition            = currentHighlightedLineRange.GetRelativePosition(currentLineNumber, codeNumLines);
                        }
                        else
                        {
                            currentHighlightedLineRange = null;
                        }
                    }
                    currentLineIsHighlighted = relativePosition == 0;
                }

                // Line end tags
                previousLineHasLineElement = currentLineHasLineElement;
                currentLineHasLineElement  = hasLineNumbers || currentLineIsHighlighted;
                if (previousLineHasLineElement || currentLineHasLineElement)
                {
                    while (openElements.Count > 0)
                    {
                        WriteEndTag();
                        Element element = openElements.Pop();
                        if (element.Type == 2)
                        {
                            break; // Line element is always the last
                        }
                        else
                        {
                            pendingElements.Push(element);
                        }
                    }
                }
            }

            void WriteStartTag(string element)
            {
                textWriter.Write("<span class=\"");
                textWriter.Write(blockName);
                textWriter.Write(element);
                textWriter.Write("\">");
            }

            void WriteEndTag()
            {
                textWriter.Write("</span>");
            }

            void WriteUnescaped()
            {
                switch (currentChar)
                {
                case '<':
                    textWriter.Write("&lt;");
                    break;

                case '>':
                    textWriter.Write("&gt;");
                    break;

                case '&':
                    textWriter.Write("&amp;");
                    break;

                case '"':
                    textWriter.Write("&quot;");
                    break;

                default:
                    textWriter.Write(currentChar);
                    break;
                }
            }

            void WriteEscaped()
            {
                if (currentChar == '&')
                {
                    switch (code[i + 1])
                    {
                    case 'l':
                        textWriter.Write("&lt;");
                        i += 3;
                        break;

                    case 'g':
                        textWriter.Write("&gt;");
                        i += 3;
                        break;

                    case 'a':
                        textWriter.Write("&amp;");
                        i += 4;
                        break;

                    case 'q':
                        textWriter.Write("&quot;");
                        i += 5;
                        break;
                    }
                }
                else
                {
                    textWriter.Write(currentChar);
                }
            }
        }
        public ModuleResult ProcessElement(XmlElement moduleElement, ViewConfiguration configuration)
        {
            SageContext context = configuration.Context;
            Initialize(context);

            if (languages.Count == 0)
            {
                log.ErrorFormat("The syntax highligher module isn't configured with any languages. Until this is fixed, the module will not work.");
                return new ModuleResult(ModuleResultStatus.ConfigurationError);
            }

            XmlNode languageNode = moduleElement.SelectSingleNode("mod:config/mod:language", nm);
            XmlElement codeNode = moduleElement.SelectSingleElement("mod:config/mod:code", nm);
            XmlNodeList keywordGroups = moduleElement.SelectNodes("mod:config/mod:keywords/mod:group", nm);
            XmlElement digitsNode = moduleElement.SelectSingleElement("mod:config/mod:digits", nm);

            if (languageNode == null)
                log.ErrorFormat("The required element mod:language is missing from the module configuration");

            if (codeNode == null)
                log.ErrorFormat("The required element mod:code is missing from the module configuration");

            if (languageNode == null || codeNode == null)
                return new ModuleResult(ModuleResultStatus.MissingParameters);

            string language = languageNode.InnerText.Trim();
            string sourceCode = codeNode.InnerText.Trim();
            string sourcePath = codeNode.GetAttribute("src");

            if (string.IsNullOrWhiteSpace(language))
            {
                log.ErrorFormat("The mod:language is missing the required text value");
                return new ModuleResult(ModuleResultStatus.MissingParameters);
            }

            if (!languages.ContainsKey(language))
            {
                log.ErrorFormat("The specified language '{0}' is not recognized. Valid languages are: '{1}'.",
                    language, string.Join(", ", languages.Keys.ToArray()));

                return new ModuleResult(ModuleResultStatus.MissingParameters);
            }

            if (!string.IsNullOrEmpty(sourcePath) && string.IsNullOrWhiteSpace(sourceCode))
            {
                string expanded = context.Path.Resolve(sourcePath);
                if (!File.Exists(expanded))
                {
                    log.ErrorFormat("The specified source code location '{0}' ('{1}') doesn't exist.",
                        sourcePath, expanded);

                    return new ModuleResult(ModuleResultStatus.NoData);
                }

                sourceCode = File.ReadAllText(expanded);
            }

            string indent = null;
            string[] sourceLines = sourceCode.Split('\n');

            foreach (string line in sourceLines)
            {
                Match m;
                if ((m = indentExpr.Match(line)).Success)
                {
                    if (indent == null || m.Groups[1].Value.Length < indent.Length)
                        indent = m.Groups[1].Value;
                }
            }

            if (!string.IsNullOrEmpty(indent))
            {
                StringBuilder trimmed = new StringBuilder();
                Regex cleanup = new Regex("^" + indent);
                foreach (string line in sourceLines)
                {
                    trimmed.AppendLine(cleanup.Replace(line, string.Empty));
                }

                sourceCode = trimmed.ToString();
            }

            List<ExpressionGroup> additionalGroups = new List<ExpressionGroup>();
            if (keywordGroups.Count != 0)
            {
                additionalGroups = new List<ExpressionGroup>();
                foreach (XmlElement keywordElement in keywordGroups)
                {
                    additionalGroups.Add(new ExpressionGroup(keywordElement, languages[language].CaseSensitive));
                }
            }

            SyntaxHighlighter highlighter = new SyntaxHighlighter(languages[language], additionalGroups);
            if (digitsNode != null)
            {
                int lineCountDigits = 0;
                if (int.TryParse(digitsNode.InnerText.Trim(), out lineCountDigits))
                    highlighter.LineCountDigits = lineCountDigits;
            }

            string highlighted = highlighter.Format(sourceCode);

            ModuleResult result = new ModuleResult(moduleElement);
            XmlElement dataElement = result.AppendDataElement();
            XmlElement sourceElement = dataElement.AppendElement("mod:formatted", XmlNamespaces.ModulesNamespace);
            sourceElement.InnerText = highlighted;

            return result;
        }
Beispiel #32
0
 public RtfItem(SyntaxHighlighter highlighter, string line, int lineNumber) : base(line)
 {
     LineNumber   = lineNumber;
     _line        = line;
     _highlighter = highlighter;
 }
Beispiel #33
0
        public static void Main(string[] args)
        {
            string au3 = @"
#cs
    comment
#ce still ignored
code() ; test

#warning This is a warning!
#using <system32/kernel32.dll>
#include ""\\8.8.8.8\test.au3""

If $a Or @macro @ macro() ..1-2 Then
    $test = $""Interpolated $var @lel and \@lol \$escaped \\$unescaped \\@kek \nhello, \""test "" << 2
    $test = ""quotes --> """" <-- and  --> ' <-- "" + 2
    $test = 'quotes --> '' <-- and  --> """" <-- ' - 4
Ifn't
    $com = .... ; dunno
    $com.xyz[$a].bc().d
EndIf

enum $x = 0, $y,$z, $w = ""test""#3

°$x = °°$y ~^^ °0
$b %= $""this is $b inside a text, e.g. '$x' or $a"" & ""test\n""
";
            int    ll  = 0;
            var    fgc = new Dictionary <HighlightningStyle, ConsoleColor> {
                [HighlightningStyle.Code]                 = ConsoleColor.White,
                [HighlightningStyle.Number]               = ConsoleColor.Gray,
                [HighlightningStyle.Directive]            = ConsoleColor.Yellow,
                [HighlightningStyle.DirectiveParameters]  = ConsoleColor.DarkYellow,
                [HighlightningStyle.Variable]             = ConsoleColor.Cyan,
                [HighlightningStyle.Macro]                = ConsoleColor.Magenta,
                [HighlightningStyle.String]               = ConsoleColor.Red,
                [HighlightningStyle.StringEscapeSequence] = ConsoleColor.DarkCyan,
                [HighlightningStyle.Keyword]              = ConsoleColor.Blue,
                [HighlightningStyle.Function]             = ConsoleColor.White,
                [HighlightningStyle.Operator]             = ConsoleColor.DarkGray,
                [HighlightningStyle.Symbol]               = ConsoleColor.DarkGray,
                [HighlightningStyle.DotMember]            = ConsoleColor.DarkMagenta,
                [HighlightningStyle.Comment]              = ConsoleColor.Green,
                [HighlightningStyle.Error]                = ConsoleColor.Black,
            };

            foreach (var sec in SyntaxHighlighter.ParseCode(au3.Trim()))
            {
                if (ll != sec.Line)
                {
                    Console.WriteLine();
                    ll = sec.Line;
                }
                Console.ForegroundColor = fgc[sec.Style];
                Console.Write(sec.StringContent);
            }
            Console.WriteLine();
            Console.ReadKey(true);
            return;

            v mat = v.NewMatrix(3, 3, 3);

            for (int z = 0; z < 3; ++z)
            {
                for (int y = 0; y < 3; ++y)
                {
                    for (int x = 0; x < 3; ++x)
                    {
                        mat[z, y, x] = $"({z}|{y}|{x})";
                    }
                }
            }

            mat[1, 1, 1] = v.NewDelegate <AutoItDelegate4Opt1>(TOP_KEK);

            Console.ForegroundColor = ConsoleColor.DarkYellow;

            AutoItFunctions.Debug(mat);

            //v server = AutoItFunctions.TCPListen("[::]", 41488);
            //v client = AutoItFunctions.TCPAccept(server);
            //v txt = AutoItFunctions.TCPRecv(client);

            AutoItFunctions.Debug(v.NewArray(v.NewArray(1, 0, 0), v.NewArray(0, 1, 0), v.NewArray(0, 0, 1)));

            v   com = v.CreateCOM("shell.application");
            var tp  = com.GetCOM().Type;

            AutoItFunctions.Debug(com);
        }
Beispiel #34
0
 void Run()
 {
     textUI.text = SyntaxHighlighter.HighlightCode(instructions, syntaxTheme);
 }
Beispiel #35
0
    // Method for creating a SyntaxHighlighter class
    private void SetupSyntaxHighlighter(TextAsset keywordTxtFile)
    {
        // Init an instance of the SyntaxHighlighter class
        syntaxHighlighter = new SyntaxHighlighter();

        //Add the keywords in keywordTxtFile to the SyntaxHighlighter
        syntaxHighlighter.AddKeywords(keywordTxtFile);
    }
Beispiel #36
0
    // Method for creating a SyntaxHighlighter class
    private void SetupSyntaxHighlighter(TextAsset[] keywordTxtFiles)
    {
        // Init an instance of the SyntaxHighlighter class
        syntaxHighlighter = new SyntaxHighlighter();

        // Loop through the keywords array and add them to the SyntaxHighlighter
        for (int i = 0; i < keywordTxtFiles.Length; i++)
        {
            syntaxHighlighter.AddKeywords(keywordTxtFiles[i]);
        }
    }
        private static void InitStyle(string name, FontStyle style, Color color, SyntaxHighlighter sh)
        {
            if (sh == null)
                return;
            var tcstyle = new TextStyle(new SolidBrush(color), null, style);
            switch (name)
            {
                case "Comment":
                    sh.Comment = tcstyle;
                    break;

                case "String":
                    sh.String = tcstyle;
                    break;

                case "Number":
                    sh.Number = tcstyle;
                    break;

                case "Variable":
                    sh.Variable = tcstyle;
                    break;

                case "Keyword":
                    sh.Keyword = tcstyle;
                    break;

                case "Constant":
                    sh.Constant = tcstyle;
                    break;

                case "Storage":
                    sh.Storage = tcstyle;
                    break;

                case "TagBracket":
                    sh.TagBracket = tcstyle;
                    break;

                case "TagName":
                    sh.TagName = tcstyle;
                    break;

                case "ClassName":
                    sh.ClassName = tcstyle;
                    break;

                case "FunctionName":
                    sh.FunctionName = tcstyle;
                    break;
                case "FunctionArgument":
                    sh.FunctionArgument = tcstyle;
                    break;
                case "Punctuation":
                    sh.Punctuation = tcstyle;
                    break;
                case "AttributeName":
                    sh.AttributeName = tcstyle;
                    break;

                case "AttributeValue":
                    sh.AttributeValue = tcstyle;
                    break;

                case "CSSProperty":
                    sh.CSSProperty = tcstyle;
                    break;

                case "CSSSelector":
                    sh.CSSSelector = tcstyle;
                    break;

                case "CSSPropertyValue":
                    sh.CSSPropertyValue = tcstyle;
                    break;

                case "Preprocessor":
                    sh.Preprocessor = tcstyle;
                    break;

                case "LibraryClass":
                    sh.LibraryClass = tcstyle;
                    break;

                case "LibraryFunction":
                    sh.LibraryFunction = tcstyle;
                    break;
                case "DoctypeDeclaration":
                    sh.DoctypeDeclaration = tcstyle;
                    break;
            }
        }