Exemplo n.º 1
0
        public void EnsureEmptyBlockIsWritten()
        {
            CodeBlock block = new FencedCodeBlock(new FencedCodeBlockParser());

            renderer.Write(pdfBuilder, block);
            Assert.AreEqual(0, document.LastSection.Elements.Count);
        }
        public static bool FirstLineStartsWith(
            this FencedCodeBlock block,
            string text,
            bool allowLeadingWhitespace     = true,
            StringComparison comparisonType =
            StringComparison.OrdinalIgnoreCase)
        {
            if (block.Lines.Count < 1)
            {
                return(false);
            }

            var firstLine = block.Lines.Lines.First();

            if (allowLeadingWhitespace == false)
            {
                return(firstLine.Slice.ToString() != null &&
                       firstLine.Slice.ToString().StartsWith(text, comparisonType));
            }
            else
            {
                return(firstLine.Slice.ToString() != null &&
                       firstLine.Slice.ToString().Trim()
                       .StartsWith(text, comparisonType));
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Convert a Markdown element to a Forkdown one.
        /// </summary>
        /// <param name="mdo">Markdown object to convert.</param>
        public static Element ToForkdown(IMarkdownObject mdo)
        {
            Element result = mdo switch {
                MarkdownDocument _ => new Document(),
                HeadingBlock h => new Heading(h),
                ListBlock l => new Listing(l),
                ListItemBlock li => new ListItem(li),
                ParagraphBlock p => new Paragraph(p),
                CustomContainer c => new Section(c),
                CustomContainerInline c => new ExplicitInlineContainer(c),
                CodeInline c => new Code(c),
                FencedCodeBlock c => new CodeBlock(c),
                LinkInline l => new Link(l),
                LiteralInline t => new Text(t),
                LineBreakInline _ => new LineBreak(),
                ThematicBreakBlock _ => new Separator(),
                Tables.Table t => new Table(t),
                Tables.TableRow tr => new TableRow(tr),
                Tables.TableCell tc => new TableCell(tc),
                EmphasisInline e => new Emphasis(e),
                HtmlBlock b => new Html(b),
                _ => new Placeholder(mdo),
            };

            var subs = mdo switch {
                LeafBlock b => b.Inline,
                IEnumerable <MarkdownObject> e => e,
                _ => null
            } ?? Nil.E <MarkdownObject>();
        protected override void Write(HtmlRenderer renderer, CodeBlock obj)
        {
            FencedCodeBlock       fencedCodeBlock = obj as FencedCodeBlock;
            FencedCodeBlockParser parser          = obj.Parser as FencedCodeBlockParser;

            if (fencedCodeBlock == null || parser == null)
            {
                _underlyingRenderer.Write(renderer, obj);
                return;
            }

            var languageMoniker = fencedCodeBlock.Info.Replace(parser.InfoPrefix, string.Empty);

            if (string.IsNullOrEmpty(languageMoniker))
            {
                _underlyingRenderer.Write(renderer, obj);
                return;
            }

            string firstLine;
            var    code = GetCode(obj, out firstLine);

            Console.WriteLine(formatter.GetCSSString());
            renderer.WriteLine(formatter.GetHtmlString(code, Languages.FindById(languageMoniker)));
        }
Exemplo n.º 5
0
        public MarkdownFencedCodeBlock(FencedCodeBlock fencedCodeBlock)
        {
            this.fencedCodeBlock = fencedCodeBlock;

            AutoSizeAxes     = Axes.Y;
            RelativeSizeAxes = Axes.X;
        }
Exemplo n.º 6
0
        public void Transform(ExtensionHtmlRenderer extensionHtmlRenderer, FencedCodeBlock block, object astNode)
        {
            var typedBlock   = block as TBlock;
            var typedAstNode = astNode as TModel;

            Transform(extensionHtmlRenderer, typedBlock, typedAstNode);
        }
        /// <summary>
        /// Writes the specified <paramref name="block"/> to the <paramref name="renderer"/>.
        /// </summary>
        /// <param name="renderer">The renderer.</param>
        /// <param name="block">The object to render.</param>
        protected override void Write(HtmlRenderer renderer, CodeBlock block)
        {
            // Make sure "obj" is an instance of "FencedCodeBlock"
            FencedCodeBlock fenced = block as FencedCodeBlock;

            // Make sure "obj" is an instance of "FencedCodeBlockParser"
            FencedCodeBlockParser parser = block.Parser as FencedCodeBlockParser;

            // Use the fallback code block renderer
            if (fenced == null || parser == null)
            {
                Fallback.Write(renderer, block);
                return;
            }

            // Get the language from the fenced block
            string language = fenced.Info.ToLowerInvariant();

            // Get the actual contents of the fenced block
            string code = String.Join(Environment.NewLine, block.Lines.Lines);

            // TODO: is this really a good idea?
            code = code.TrimEnd();

            // Get the syntax language matching "language"
            Options.TryGetAlias(language, out Language lang);

            renderer.Write(Highlighter.Highlight(code, lang));
        }
 public static bool AnyLineStartsAndEndsWithSquareBrackets(
     this FencedCodeBlock block)
 {
     return(block.Lines.Lines.Where(x =>
                                    x.Slice.ToString() != null &&
                                    x.Slice.ToString().Trim().StartsWith("[") &&
                                    x.Slice.ToString().Trim().EndsWith("]")).Any());
 }
 public static bool AnyLineMatches(
     this FencedCodeBlock block,
     Regex regex)
 {
     return(block.Lines.Lines.Where(x =>
                                    x.Slice.ToString() != null &&
                                    regex.IsMatch(x.Slice.ToString())).Any());
 }
 public static bool AnyLineContains(
     this FencedCodeBlock block,
     string text,
     StringComparison comparisonType =
     StringComparison.OrdinalIgnoreCase)
 {
     return(block.Lines.Lines.Where(x =>
                                    x.Slice.ToString() != null &&
                                    x.Slice.ToString().IndexOf(text, comparisonType) >= 0).Any());
 }
        public void Transform(ExtensionHtmlRenderer extensionHtmlRenderer, FencedCodeBlock block, object astNode)
        {
            NestedBlock nestedBlock = astNode as NestedBlock;
            // 1. parse markdown
            // 2. normalize markdown headings
            // 3. replace fencedblock with markdown node
            var node  = Markdown.Parse(nestedBlock.Markdown);
            var index = block.Parent.IndexOf(block);

            block.Parent.Insert(index, node);
            block.Parent.RemoveAt(index + 1);
        }
Exemplo n.º 12
0
        private HashSet <int> GetHighlightedLines(FencedCodeBlock fencedCodeBlock)
        {
            var highlightedLines = new HashSet <int>();

            if (string.IsNullOrWhiteSpace(fencedCodeBlock?.Arguments) || !Regex.IsMatch(pattern: Pattern, input: fencedCodeBlock.Arguments))
            {
                return(highlightedLines);
            }

            var match  = Regex.Match(fencedCodeBlock.Arguments, Pattern);
            var groups = match.Groups;

            if (groups.Count < 2 || string.IsNullOrWhiteSpace(groups[1].Value))
            {
                return(highlightedLines);
            }

            var lines = groups[1].Value.Split(",");

            foreach (var line in lines)
            {
                if (line.Contains("-"))
                {
                    var numbers = line.Split("-");
                    if (numbers.Length > 2)
                    {
                        continue;
                    }

                    if (!int.TryParse(numbers[0], out var minLineNumber) ||
                        !int.TryParse(numbers[1], out var maxLineNumber))
                    {
                        continue;
                    }

                    for (var lineNumber = minLineNumber; lineNumber < maxLineNumber + 1; lineNumber++)
                    {
                        highlightedLines.Add(lineNumber);
                    }
                }
                else
                {
                    if (int.TryParse(line, out var lineNumber))
                    {
                        highlightedLines.Add(lineNumber);
                    }
                }
            }

            return(highlightedLines);
        }
Exemplo n.º 13
0
 private string GetCachedResult(int blockNumber, int hash, FencedCodeBlock block)
 {
     if (blockNumber >= _blocks.Count)
     {
         return(null);
     }
     if (_blocks[_blockNumber].Hash != hash)
     {
         InvalidateCacheFrom(_blockNumber);
         return(null);
     }
     // can be null if block hasn't been rendered yet
     return(_blocks[_blockNumber].Result);
 }
        public static bool FirstLineMatches(
            this FencedCodeBlock block,
            Regex regex)
        {
            if (block.Lines.Count < 1)
            {
                return(false);
            }

            var firstLine = block.Lines.Lines.First();

            return(firstLine.Slice.ToString() != null &&
                   regex.IsMatch(firstLine.Slice.ToString()) == true);
        }
Exemplo n.º 15
0
        internal CodeBlockInfo(FencedCodeBlock codeBlock, StringSlice slice)
        {
            Info           = codeBlock.Info ?? string.Empty;
            Arguments      = codeBlock.Arguments ?? string.Empty;
            Lines          = codeBlock.Lines;
            CodeBlockSlice = slice;
            Source         = CodeBlockSlice.Text;

            int contentStart = Lines.Lines[0].Position;
            var lastLine     = Lines.Last();
            int contentEnd   = lastLine.Position + lastLine.Slice.Length - 1;

            ContentSpan  = new SourceSpan(contentStart, contentEnd);
            ContentSlice = CodeBlockSlice.Reposition(ContentSpan);
            Content      = ContentSlice.ToString();
        }
Exemplo n.º 16
0
        /// <summary>
        /// Creates a new instance of <see cref="BlockElement"/>.
        /// Its type will be determined with the specified first line.
        /// </summary>
        /// <param name="line">The line which is the first line of the block.</param>
        /// <param name="currentIndent">The indent count of <paramref name="line"/>.</param>
        /// <param name="config">Configuration of the parser.</param>
        /// <param name="createListItem">
        /// Creates a <see cref="ListItem"/> instead of <see cref="ListBlock"/> when <c>true</c> is specified.
        /// </param>
        /// <returns>The new element that the type corresponds to <paramref name="line"/>.</returns>
        public static BlockElement CreateBlockFromLine(string line, int currentIndent, ParserConfig config,
                                                       bool createListItem = false)
        {
            if (IndentedCodeBlock.CanStartBlock(line, currentIndent))
            {
                return(new IndentedCodeBlock(config));
            }

            if (ThematicBreak.CanStartBlock(line, currentIndent))
            {
                return(new ThematicBreak(config));
            }

            if (AtxHeading.CanStartBlock(line, currentIndent))
            {
                return(new AtxHeading(config));
            }

            if (FencedCodeBlock.CanStartBlock(line, currentIndent))
            {
                return(new FencedCodeBlock(config));
            }

            if (HtmlBlock.CanStartBlock(line, currentIndent))
            {
                return(new HtmlBlock(config));
            }

            if (BlockQuote.CanStartBlock(line, currentIndent))
            {
                return(new BlockQuote(config));
            }

            if (ListBlock.CanStartBlock(line, currentIndent))
            {
                return(createListItem ? (BlockElement) new ListItem(config) : new ListBlock(config));
            }

            if (BlankLine.CanStartBlock(line))
            {
                return(new BlankLine(config));
            }

            return(new UnknownElement(config));
        }
Exemplo n.º 17
0
    private string GetFencedText(FencedCodeBlock fencedCodeBlock)
    {
        if (fencedCodeBlock == null)
        {
            return(string.Empty);
        }

        var lines = fencedCodeBlock.Lines.Lines.Select(l =>
        {
            var slice = l.Slice;
            if (EqualityComparer <StringSlice> .Default.Equals(slice, default(StringSlice)))
            {
                return(string.Empty);
            }

            return(slice.Text?.Substring(l.Slice.Start, l.Slice.Length) ?? string.Empty);
        });

        return(string.Join(Environment.NewLine, lines));
    }
 public static bool HasSingleLineWithText(
     this FencedCodeBlock block,
     string text,
     bool allowLeadingAndTrailingWhitespace = true,
     StringComparison comparisonType        =
     StringComparison.OrdinalIgnoreCase)
 {
     if (allowLeadingAndTrailingWhitespace == false)
     {
         return(block.Lines.Count == 1 &&
                block.Lines.Lines[0].Slice.ToString()
                .Equals(text, comparisonType));
     }
     else
     {
         return(block.Lines.Count == 1 &&
                block.Lines.Lines[0].Slice.ToString().Trim()
                .Equals(text, comparisonType));
     }
 }
Exemplo n.º 19
0
        private void WriteHighlightedCodeLines(HtmlRenderer renderer, FencedCodeBlock fencedCodeBlock)
        {
            var highlightedLines = GetHighlightedLines(fencedCodeBlock);

            if (highlightedLines.Any())
            {
                renderer.WriteAttributes(new HtmlAttributes
                {
                    Classes = new List <string> {
                        "line-numbers"
                    }                                           //prevents adding line-numbers for highlighted lines
                });

                var lines = string.Join(",", highlightedLines);
                renderer.Write($"data-line={lines}><code");
            }
            else
            {
                renderer.Write("><code");
            }
        }
 public static bool AnyLineStartsWith(
     this FencedCodeBlock block,
     string text,
     bool allowLeadingWhitespace     = true,
     StringComparison comparisonType =
     StringComparison.OrdinalIgnoreCase)
 {
     if (allowLeadingWhitespace == false)
     {
         return(block.Lines.Lines.Where(x =>
                                        x.Slice.ToString() != null &&
                                        x.Slice.ToString().StartsWith(text, comparisonType)).Any());
     }
     else
     {
         return(block.Lines.Lines.Where(x =>
                                        x.Slice.ToString() != null &&
                                        x.Slice.ToString().Trim()
                                        .StartsWith(text, comparisonType)).Any());
     }
 }
Exemplo n.º 21
0
        public void TestInfoAndArguments(string infoString, string expectedInfo, string expectedArguments)
        {
            Test('`');
            Test('~');

            void Test(char fencedChar)
            {
                const string Contents = "Foo\nBar\n";

                string fence        = new string(fencedChar, 3);
                string markdownText = $"{fence}{infoString}\n{Contents}\n{fence}\n";

                MarkdownDocument document = Markdown.Parse(markdownText);

                FencedCodeBlock codeBlock = document.Descendants <FencedCodeBlock>().Single();

                Assert.AreEqual(fencedChar, codeBlock.FencedChar);
                Assert.AreEqual(3, codeBlock.OpeningFencedCharCount);
                Assert.AreEqual(3, codeBlock.ClosingFencedCharCount);
                Assert.AreEqual(expectedInfo, codeBlock.Info);
                Assert.AreEqual(expectedArguments, codeBlock.Arguments);
                Assert.AreEqual(Contents, codeBlock.Lines.ToString());
            }
        }
Exemplo n.º 22
0
 private static bool TryParseFencedCode(FencedCodeBlock fencedCodeBlock, string wholeSource, out (string code, int index, int length, string fence) result)
Exemplo n.º 23
0
        private string InferLanguage(FencedCodeBlock block)
        {
            var lines = block.Lines.ToString().Trim();

            //this._logger.LogDebug(
            //    "Inferring language for code block:" + Environment.NewLine
            //        + Environment.NewLine
            //        + lines);

            // e.g. C:\Users\foo>
            Regex commandPromptRegex = new Regex(
                @"^\w:\\[\w\\]*>");

            // e.g. "foo.bar<string>("
            Regex csharpGenericMethodCallRegex = new Regex(
                @"[\w]+\.[\w]+<[\w]+>\(");

            // e.g. "foo.bar("
            Regex objectMethodCallRegex = new Regex(
                @"[\w]+\.[\w]+\(");

            // e.g. "= foo.bar"
            Regex objectGetPropertyRegex = new Regex(
                @".*?=\s[\w]+\.[\w]+");

            // e.g. "foo.bar ="
            Regex objectSetPropertyRegex = new Regex(
                @".*?[\w]+\.[\w]+\s=");

            // e.g. .class-name {
            // e.g. table.class-name {
            // e.g. table .class-name
            // e.g. table.class-name tr.class-name {
            Regex cssRuleRegex = new Regex(
                @"^\s*[\w-]*\.[\w-]+\s*{|^\s*[\.\w-]+\s+[\w]*\.[\w-]+\s*{?$");

            // e.g. tt-mail-test01.corp.technologytoolbox.com
            Regex hostnameRegex = new Regex(
                @"^[\w\-\.]*\.technologytoolbox\.com$");

            // e.g. 10.1.20.41      ext-foobar9
            Regex hostsFileRegex = new Regex(
                @"^\s*[\d]+\.[\d]+\.[\d]+\.[\d]+\s+\w");

            // e.g.
            // {
            //   "terminal.integrated.fontFamily": "monospace, PowerlineSymbols",
            //   "workbench.iconTheme": "vscode-icons",
            //   foo: { }
            // }
            Regex jsonRegex = new Regex(
                "^{[\\s\\w\\.\\-\",:{ }]*}$");

            // e.g. Get-Date
            // e.g.     Get-Date
            // e.g. # Get-Date
            // e.g. (Get-Date
            // e.g. Remove-VpnS2SInterface
            // e.g. (Get-InitiatorPort).NodeAddress
            Regex powerShellCmdletRegex = new Regex(
                @"^[\s#\(]*[\w]+\-[[\w]+[\).\w]*(\s|$)");

            Regex powerShellScriptRegex = new Regex(
                @"\S+\.ps1", RegexOptions.IgnoreCase);

            Regex powerShellStaticMethodRegex = new Regex(
                @"\[[\w]+\]::[\w]+");

            Regex timestampRegex = new Regex(
                @"^[\d]+:[\d]+:[\d]+");

            Regex windowsCommandFileRegex = new Regex(
                @"\S+\.cmd", RegexOptions.IgnoreCase);

            Regex windowsExecutableRegex = new Regex(
                @"\S+\.exe", RegexOptions.IgnoreCase);

            Regex windowsInstallerRegex = new Regex(
                @"\S+\.msi", RegexOptions.IgnoreCase);

            Regex xmlEndElementRegex = new Regex(
                @"^\s*<\/[\w:]+>?");

            Regex xmlStartElementRegex = new Regex(
                @"^\s*<[\w:]+>?");

            if (block.HasSingleLineWithText(
                    "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
                    ) == true)
            {
                return("Text");
            }
            else if (block.AnyLineStartsWith(".ms-") ||
                     block.AnyLineStartsWith("#search") ||
                     block.AnyLineStartsWith(".main-container") ||
                     block.AnyLineContains("div.more-btn a:link, div.more-btn a:visited {"))
            {
                return("CSS");
            }
            else if (block.AnyLineContains("<add key=\"Captcha.Encryption.Key\" value=\"ppujW5AxO9oz...=\"/>"))
            {
                return("XML");
            }
            else if (
                block.AnyLineStartsWith("=MID") == true ||
                block.AnyLineStartsWith("=SEARCH") == true ||
                block.AnyLineStartsWith("!(Tcp.port") == true ||
                block.AnyLineStartsWith("(skipped)") == true ||
                block.AnyLineStartsWith(
                    "************** Exception Text **************") == true ||
                block.AnyLineStartsWith("[Error ") == true ||
                block.AnyLineStartsWith("* Modifying computer account") == true ||
                block.AnyLineStartsWith("$2007") == true ||
                block.FirstLineStartsWith("AlternateSignatureAlgorithm=") == true ||
                block.AnyLineStartsWith("= Demonstrating problem:") == true ||
                block.AnyLineStartsWith("cache = ") == true ||
                block.FirstLineStartsWith("darfka.vbscript") == true ||
                block.FirstLineStartsWith("dsznajder.es7-react-js-snippets") == true ||
                block.FirstLineStartsWith("ExcludeFromSelect =") == true ||
                block.AnyLineStartsWith("ext install ") == true ||
                block.AnyLineStartsWith("GRUB_CMDLINE_LINUX_DEFAULT=") == true ||
                block.FirstLineStartsWith("HTTP/1.1") == true ||
                block.FirstLineStartsWith("network:") == true ||
                block.AnyLineStartsWith("Invoking tier optimization on ") == true ||
                block.FirstLineStartsWith("MSI (s)") == true
                // e.g. PS C:\Users\jjameson-admin> nslookup
                || block.AnyLineStartsWith(@"PS C:\") == true ||
                block.AnyLineStartsWith(@"PS E:\") == true ||
                block.AnyLineStartsWith("security = ") == true ||
                block.AnyLineStartsWith("session required ") == true ||
                block.FirstLineStartsWith("System.Data.SqlClient.SqlException:") == true ||
                block.AnyLineStartsWith("Unhandled Exception: ") == true ||
                block.AnyLineStartsWith("VERBOSE: ") == true)
            {
                return("Text");
            }
            // Apply "narrow focus" tests for PowerShell to avoid issues when
            // PowerShell contains other code (e.g. HTML elements)
            else if (block.AnyLineStartsWith("param(") == true ||
                     block.AnyLineStartsWith("Set-StrictMode") == true)
            {
                return("PowerShell");
            }
            else if (jsonRegex.IsMatch(lines) == true)
            {
                return("JSON");
            }
            else if (block.AnyLineStartsWith("<%") == true ||
                     block.AnyLineStartsWith("<asp:") == true ||
                     block.AnyLineStartsWith("<SharePoint:") == true)
            {
                return("ASP.NET");
            }
            else if (block.AnyLineStartsWith("<xsl:") == true)
            {
                return("XSLT");
            }
            else if (
                block.AnyLineStartsWith("Private Function ") == true ||
                block.AnyLineStartsWith("Private Sub ") == true ||
                block.AnyLineStartsWith("Public Function ") == true ||
                block.AnyLineStartsWith("Public Sub ") == true)
            {
                return("VBA");
            }
            else if (block.AnyLineStartsWith("Option Explicit") == true)
            {
                return("VBScript");
            }
            else if (
                // Distinguish Linq from SQL using "orderby"
                block.AnyLineContains(
                    "orderby ", StringComparison.Ordinal) == true ||
                block.AnyLineStartsWith(
                    "catch ", true, StringComparison.Ordinal) == true ||
                block.AnyLineStartsWith(
                    "const ", true, StringComparison.Ordinal) == true ||
                block.AnyLineStartsWith(
                    "internal ", true, StringComparison.Ordinal) == true ||
                block.AnyLineStartsWith(
                    "private ", true, StringComparison.Ordinal) == true ||
                block.AnyLineStartsWith(
                    "protected ", true, StringComparison.Ordinal) == true ||
                block.AnyLineStartsWith(
                    "public ", true, StringComparison.Ordinal) == true ||
                block.AnyLineStartsWith(
                    "static ", true, StringComparison.Ordinal) == true ||
                block.AnyLineStartsWith(
                    "using ", true, StringComparison.Ordinal) == true ||
                block.AnyLineMatches(csharpGenericMethodCallRegex) == true)
            {
                // Avoid matching:
                //
                // <appSettings>
                //   <!--
                //   ...
                //   static ...

                if (block.FirstLineMatches(xmlStartElementRegex) == false)
                {
                    return("C#");
                }
            }
            else if (block.FirstLineStartsWith("<!DOCTYPE html") == true ||
                     block.AnyLineStartsWith("<html") == true ||
                     block.AnyLineStartsWith("<head") == true ||
                     block.AnyLineStartsWith("<meta") == true ||
                     block.AnyLineStartsWith("<body") == true ||
                     block.AnyLineStartsWith("<blockquote") == true ||
                     block.AnyLineStartsWith("<div") == true ||
                     block.AnyLineStartsWith("<form ") == true || // don't match <forms
                     block.AnyLineStartsWith("<input") == true ||
                     block.AnyLineStartsWith("<p>") == true || // don't match <ProjectReference
                     block.AnyLineStartsWith("<script") == true ||
                     block.AnyLineStartsWith("<table") == true ||
                     block.AnyLineStartsWith("<asp:") == true)
            {
                return("HTML");
            }
            else if (block.FirstLineStartsWith("<?xml") == true ||
                     block.FirstLineStartsWith("<!--") == true ||
                     block.FirstLineMatches(xmlStartElementRegex) == true ||
                     block.LastLineMatches(xmlEndElementRegex) == true)
            {
                return("XML");
            }
            else if (
                // Avoid confusing jQuery ("$(...)") with PowerShell
                block.AnyLineStartsWith("$.fn") == true ||
                block.AnyLineStartsWith("jQuery.fn") == true ||
                block.AnyLineContains(".blur") == true ||
                block.AnyLineContains(".keypress") == true ||
                block.AnyLineContains("button.className") == true ||
                block.AnyLineContains("event.returnValue") == true ||
                block.AnyLineContains("window.Location") == true)
            {
                return("JavaScript");
            }
            else if (
                block.AnyLineStartsWith("$") == true ||
                block.AnyLineContains("$env:") == true ||
                block.AnyLineContains("$false") == true ||
                block.AnyLineContains("$true") == true ||
                block.AnyLineContains("| % {") == true ||
                block.AnyLineEndsWith("|") == true ||
                block.AnyLineEndsWith(" `") == true ||
                block.AnyLineStartsWith("asnp ") == true ||
                block.FirstLineMatches(powerShellCmdletRegex) == true)
            {
                return("PowerShell");
            }
            else if (
                block.AnyLineStartsWith("ALTER") == true ||
                block.AnyLineStartsWith("BACKUP") == true ||
                block.AnyLineStartsWith("CREATE") == true ||
                block.AnyLineContains("CREATE LOGIN") == true ||
                block.AnyLineStartsWith("DECLARE") == true ||
                block.AnyLineStartsWith("DELETE") == true ||
                block.AnyLineStartsWith("DROP") == true ||
                block.AnyLineStartsWith("EXEC") == true ||
                block.AnyLineStartsWith("INSERT") == true ||
                block.AnyLineContains("ORDER BY") == true ||
                block.AnyLineStartsWith("RESTORE") == true ||
                block.AnyLineStartsWith("SELECT") == true ||
                block.AnyLineStartsWith("sp_configure") == true ||
                block.AnyLineStartsWith("UPDATE") == true ||
                block.AnyLineStartsWith("USE") == true)
            {
                return("SQL");
            }
            else if (block.AnyLineStartsWith("@echo") == true ||
                     block.AnyLineStartsWith(":: ") == true ||
                     block.AnyLineStartsWith("REM ") == true)
            {
                return("Batch");
            }
            else if (block.FirstLineMatches(cssRuleRegex) == true)
            {
                return("CSS");
            }
            // The following rule needs to come immediately before the "Console"
            // rules (to avoid confusing "Console" for "PowerShell")
            else if (block.AnyLineStartsWith("& ") == true)
            {
                return("PowerShell");
            }
            else if (block.AnyLineStartsWith("bcdedit ") == true ||
                     block.AnyLineStartsWith("cd ") == true ||
                     block.AnyLineStartsWith("certutil ") == true ||
                     block.AnyLineStartsWith("choco ") == true ||
                     block.AnyLineStartsWith("cls") == true ||
                     block.AnyLineStartsWith("copy ") == true ||
                     block.AnyLineStartsWith("cscript ") == true ||
                     block.AnyLineStartsWith("dcdiag") == true ||
                     block.AnyLineStartsWith("dcpromo") == true ||
                     block.AnyLineStartsWith("dfsrmig ") == true ||
                     block.AnyLineStartsWith("dir") == true ||
                     block.AnyLineStartsWith("diskpart") == true ||
                     block.AnyLineStartsWith("docker ") == true ||
                     block.HasSingleLineWithText("exit") == true ||
                     block.AnyLineStartsWith("format ") == true ||
                     block.AnyLineStartsWith("git ") == true ||
                     block.AnyLineStartsWith("gulp ") == true ||
                     block.AnyLineStartsWith("icacls ") == true ||
                     block.AnyLineStartsWith("ipconfig") == true ||
                     block.AnyLineStartsWith("iisreset") == true ||
                     block.AnyLineStartsWith("klist") == true ||
                     block.AnyLineStartsWith("logoff") == true ||
                     block.AnyLineStartsWith("mkdir ") == true ||
                     block.AnyLineStartsWith("minikube ") == true ||
                     block.AnyLineStartsWith("move ") == true ||
                     block.AnyLineStartsWith("msiexec ") == true ||
                     block.AnyLineStartsWith("nbtstat") == true ||
                     block.AnyLineStartsWith("netdom ") == true ||
                     block.AnyLineStartsWith("net ") == true ||
                     block.AnyLineStartsWith("netsh ") == true ||
                     block.AnyLineStartsWith("nltest ") == true ||
                     block.AnyLineStartsWith("notepad") == true ||
                     block.AnyLineStartsWith("npm ") == true ||
                     block.AnyLineStartsWith("ping ") == true ||
                     block.AnyLineStartsWith("pnputil ") == true ||
                     block.AnyLineStartsWith("powercfg ") == true ||
                     block.AnyLineStartsWith("powershell") == true ||
                     block.AnyLineStartsWith("reg ") == true ||
                     block.AnyLineStartsWith("ren ") == true ||
                     block.AnyLineStartsWith("rmdir ") == true ||
                     block.AnyLineStartsWith("robocopy ") == true ||
                     block.AnyLineStartsWith("runas ") == true ||
                     block.AnyLineStartsWith("sconfig") == true ||
                     block.AnyLineStartsWith("set ") == true ||
                     block.AnyLineStartsWith("setspn ") == true ||
                     block.AnyLineStartsWith("setup ") == true ||
                     block.AnyLineStartsWith("setx ") == true ||
                     block.AnyLineStartsWith("slmgr ") == true ||
                     block.AnyLineStartsWith("slmgr.vbs ") == true ||
                     block.AnyLineStartsWith("stsadm ") == true ||
                     block.AnyLineStartsWith("tf ") == true ||
                     block.AnyLineStartsWith("tfsmigrator ") == true ||
                     block.AnyLineStartsWith("tzutil ") == true ||
                     block.AnyLineStartsWith("w32tm ") == true ||
                     block.AnyLineStartsWith("wdsutil ") == true ||
                     block.AnyLineStartsWith("witadmin ") == true ||
                     block.AnyLineStartsWith("wuauclt ") == true)
            {
                return("Console");
            }
            else if (
                block.AnyLineContains("~/") == true ||
                block.AnyLineStartsWith("/home") == true ||
                block.AnyLineStartsWith("bash") == true ||
                block.AnyLineStartsWith("cat /") == true ||
                block.AnyLineStartsWith("cat <") == true ||
                block.AnyLineStartsWith("clear") == true ||
                block.AnyLineStartsWith("dig ") == true ||
                block.AnyLineStartsWith("gem ") == true ||
                block.AnyLineStartsWith("gsettings ") == true ||
                block.AnyLineStartsWith("ifconfig") == true ||
                block.AnyLineStartsWith("nano ") == true ||
                block.AnyLineStartsWith("realm ") == true ||
                block.AnyLineStartsWith("reboot") == true ||
                block.AnyLineStartsWith("rm /") == true ||
                block.AnyLineStartsWith("ruby") == true ||
                block.AnyLineStartsWith("ssh ") == true ||
                block.AnyLineStartsWith("sudo") == true ||
                block.AnyLineStartsWith("sudoedit") == true ||
                block.AnyLineStartsWith("wget ") == true)
            {
                return("Shell");
            }
            else if (
                block.AnyLineStartsWith("SP.UI.Notify") == true ||
                block.AnyLineStartsWith("SP.UI.Status") == true ||
                block.AnyLineContains(
                    "decodeURIComponent", StringComparison.Ordinal) == true ||
                block.AnyLineContains(
                    "document.getElementById", StringComparison.Ordinal) == true ||
                block.AnyLineContains(
                    "document.querySelectorAll", StringComparison.Ordinal) == true)
            {
                return("JavaScript");
            }
            else if (
                block.AnyLineStartsAndEndsWithSquareBrackets() == true ||
                block.AnyLineStartsWith("MENU COLOR ") == true ||
                block.AnyLineStartsWith("MENU LABEL ") == true)
            {
                return("INI");
            }
            else if (
                block.FirstLineMatches(commandPromptRegex) == true ||
                block.FirstLineMatches(hostnameRegex) == true ||
                block.AnyLineMatches(hostsFileRegex) == true ||
                block.AnyLineMatches(timestampRegex) == true ||
                block.AnyLineStartsWith("----") == true ||
                block.AnyLineStartsWith("TODO") == true ||
                block.AnyLineContains(@"prefix=${APPDATA}\npm") == true ||
                block.AnyLineContains("FullyQualifiedErrorId :") == true)
            {
                return("Text");
            }
            else if (block.AnyLineContains("ElseIf") == true ||
                     block.AnyLineMatches(powerShellCmdletRegex) == true ||
                     block.AnyLineMatches(powerShellScriptRegex) == true ||
                     block.AnyLineMatches(powerShellStaticMethodRegex) == true)
            {
                return("PowerShell");
            }
            else if (
                block.AnyLineMatches(windowsCommandFileRegex) == true ||
                block.AnyLineMatches(windowsExecutableRegex) == true ||
                block.AnyLineMatches(windowsInstallerRegex) == true)
            {
                return("Console");
            }
            // If no language has been inferred, try looking for a simple
            // method call on an object (e.g. "foo.bar("), a "get property"
            // accessor (e.g. "= foo.bar"), or a "set property" accessor
            // (e.g. "foo.bar ="); only use this as a last resort, since they
            // could match multiple languages (e.g. C#, C/C++, JavaScript,
            // PowerShell, etc).
            else if (block.AnyLineMatches(objectMethodCallRegex) == true ||
                     block.AnyLineMatches(objectGetPropertyRegex) == true ||
                     block.AnyLineMatches(objectSetPropertyRegex) == true)
            {
                return("C#");
            }
            else if (block.Lines.Count == 1 &&
                     block.FirstLineStartsWith("#") == true)
            {
                if (block.FirstLineStartsWith(
                        "# Note: NullReferenceException") == true)
                {
                    // Don't log a warning in this case, since the code block is
                    // likely:
                    //
                    // # Note: NullReferenceException occurs if you attempt to
                    // perform this step before starting the User Profile
                    // Synchronization Service.
                }
                else
                {
                    //this._logger.LogWarning(
                    //    "Assuming PowerShell for code block (based on single line"
                    //        + " with comment character):" + Environment.NewLine
                    //        + Environment.NewLine
                    //        + lines);
                }

                return("PowerShell");
            }

            //this._logger.LogWarning(
            //    "Unable to infer language for code block:" + Environment.NewLine
            //        + Environment.NewLine
            //        + lines);

            return(null);
        }
Exemplo n.º 24
0
 private static bool IsCSharpCodeBlock(FencedCodeBlock codeBlock)
 {
     return((codeBlock?.Info ?? "")
            .Split()
            .Any(x => x.Equals("csharp", StringComparison.OrdinalIgnoreCase)));
 }
Exemplo n.º 25
0
 // TODO : change to monospace font for this component
 public OsuMarkdownFencedCodeBlock(FencedCodeBlock fencedCodeBlock)
     : base(fencedCodeBlock)
 {
 }
Exemplo n.º 26
0
 protected override MarkdownFencedCodeBlock CreateFencedCodeBlock(FencedCodeBlock fencedCodeBlock) => new OsuMarkdownFencedCodeBlock(fencedCodeBlock);